server_GPIO.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. // Wait until RMT has finished using the LED buffers before destroying the driver.
  274. leds_global->wait();
  275. delete leds_global;
  276. leds_global = NULL;
  277. }
  278. #endif
  279. clear();
  280. if (gpio_queue_handle != NULL) {
  281. vQueueDelete(gpio_queue_handle);
  282. gpio_queue_handle = NULL;
  283. }
  284. _isEnabled = false;
  285. }
  286. void GpioHandler::gpioInterrupt(GpioResult* gpioResult) {
  287. if ((gpioMap != NULL) && (gpioMap->find(gpioResult->gpio) != gpioMap->end())) {
  288. (*gpioMap)[gpioResult->gpio]->gpioInterrupt(gpioResult->value);
  289. }
  290. }
  291. bool GpioHandler::readConfig()
  292. {
  293. if (!gpioMap->empty())
  294. clear();
  295. ConfigFile configFile = ConfigFile(_configFile);
  296. std::vector<std::string> splitted;
  297. std::string line = "";
  298. bool disabledLine = false;
  299. bool eof = false;
  300. gpio_num_t gpioExtLED = (gpio_num_t) 0;
  301. // ESP_LOGD(TAG, "readConfig - Start 1");
  302. while ((!configFile.GetNextParagraph(line, disabledLine, eof) || (line.compare("[GPIO]") != 0)) && !eof) {}
  303. if (eof)
  304. return false;
  305. // ESP_LOGD(TAG, "readConfig - Start 2 line: %s, disabbledLine: %d", line.c_str(), (int) disabledLine);
  306. _isEnabled = !disabledLine;
  307. if (!_isEnabled)
  308. return false;
  309. // ESP_LOGD(TAG, "readConfig - Start 3");
  310. #ifdef ENABLE_MQTT
  311. // std::string mainTopicMQTT = "";
  312. std::string mainTopicMQTT = mqttServer_getMainTopic();
  313. if (mainTopicMQTT.length() > 0)
  314. {
  315. mainTopicMQTT = mainTopicMQTT + "/GPIO";
  316. ESP_LOGD(TAG, "MAINTOPICMQTT found");
  317. }
  318. #endif // ENABLE_MQTT
  319. bool registerISR = false;
  320. while (configFile.getNextLine(&line, disabledLine, eof) && !configFile.isNewParagraph(line))
  321. {
  322. splitted = ZerlegeZeile(line);
  323. // const std::regex pieces_regex("IO([0-9]{1,2})");
  324. // std::smatch pieces_match;
  325. // if (std::regex_match(splitted[0], pieces_match, pieces_regex) && (pieces_match.size() == 2))
  326. // {
  327. // std::string gpioStr = pieces_match[1];
  328. ESP_LOGD(TAG, "conf param %s", toUpper(splitted[0]).c_str());
  329. if (toUpper(splitted[0]) == "MAINTOPICMQTT") {
  330. // ESP_LOGD(TAG, "MAINTOPICMQTT found");
  331. // mainTopicMQTT = splitted[1];
  332. } else if ((splitted[0].rfind("IO", 0) == 0) && (splitted.size() >= 6))
  333. {
  334. ESP_LOGI(TAG,"Enable GP%s in %s mode", splitted[0].c_str(), splitted[1].c_str());
  335. std::string gpioStr = splitted[0].substr(2, 2);
  336. gpio_num_t gpioNr = (gpio_num_t)atoi(gpioStr.c_str());
  337. gpio_pin_mode_t pinMode = resolvePinMode(toLower(splitted[1]));
  338. gpio_int_type_t intType = resolveIntType(toLower(splitted[2]));
  339. uint16_t dutyResolution = (uint8_t)atoi(splitted[3].c_str());
  340. #ifdef ENABLE_MQTT
  341. bool mqttEnabled = (toLower(splitted[4]) == "true");
  342. #endif // ENABLE_MQTT
  343. bool httpEnabled = (toLower(splitted[5]) == "true");
  344. char gpioName[100];
  345. if (splitted.size() >= 7) {
  346. strlcpy(gpioName, trim(splitted[6]).c_str(), sizeof(gpioName));
  347. } else {
  348. sprintf(gpioName, "GPIO%d", gpioNr);
  349. }
  350. #ifdef ENABLE_MQTT
  351. std::string mqttTopic = mqttEnabled ? (mainTopicMQTT + "/" + gpioName) : "";
  352. #else // ENABLE_MQTT
  353. std::string mqttTopic = "";
  354. #endif // ENABLE_MQTT
  355. GpioPin* gpioPin = new (std::nothrow) GpioPin(
  356. gpioNr, gpioName, pinMode, intType, dutyResolution, mqttTopic, httpEnabled);
  357. if (gpioPin == NULL) {
  358. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO pin configuration");
  359. return false;
  360. }
  361. const auto existingPin = gpioMap->find(gpioNr);
  362. if (existingPin != gpioMap->end()) {
  363. // Duplicate GPIO entries replace the previous uninitialized definition.
  364. delete existingPin->second;
  365. existingPin->second = gpioPin;
  366. } else {
  367. gpioMap->emplace(gpioNr, gpioPin);
  368. }
  369. if (pinMode == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
  370. {
  371. ESP_LOGD(TAG, "Set WS2812 to GPIO %d", gpioNr);
  372. gpioExtLED = gpioNr;
  373. }
  374. if (intType != GPIO_INTR_DISABLE) {
  375. registerISR = true;
  376. }
  377. }
  378. if (toUpper(splitted[0]) == "LEDNUMBERS")
  379. {
  380. LEDNumbers = stoi(splitted[1]);
  381. }
  382. if (toUpper(splitted[0]) == "LEDCOLOR")
  383. {
  384. uint8_t _r, _g, _b;
  385. _r = stoi(splitted[1]);
  386. _g = stoi(splitted[2]);
  387. _b = stoi(splitted[3]);
  388. LEDColor = Rgb{_r, _g, _b};
  389. }
  390. if (toUpper(splitted[0]) == "LEDTYPE")
  391. {
  392. if (splitted[1] == "WS2812")
  393. LEDType = LED_WS2812;
  394. if (splitted[1] == "WS2812B")
  395. LEDType = LED_WS2812B;
  396. if (splitted[1] == "SK6812")
  397. LEDType = LED_SK6812;
  398. if (splitted[1] == "WS2813")
  399. LEDType = LED_WS2813;
  400. }
  401. }
  402. if (registerISR) {
  403. //install gpio isr service
  404. gpio_install_isr_service(ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM);
  405. }
  406. if (gpioExtLED > 0)
  407. {
  408. // LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Startsequence 06"); // Nremove
  409. // vTaskDelay( xDelay );
  410. // xDelay = 5000 / portTICK_PERIOD_MS;
  411. // ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay);
  412. // SmartLed leds( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer );
  413. // leds[ 0 ] = Rgb{ 255, 0, 0 };
  414. // leds[ 1 ] = Rgb{ 255, 255, 255 };
  415. // leds.show();
  416. // SmartLed leds = new SmartLed(LEDType, LEDNumbers, gpioExtLED, 0, DoubleBuffer);
  417. // _SmartLED = new SmartLed( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer );
  418. }
  419. return true;
  420. }
  421. void GpioHandler::clear()
  422. {
  423. ESP_LOGD(TAG, "GpioHandler::clear");
  424. if (gpioMap != NULL) {
  425. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  426. delete it->second;
  427. }
  428. gpioMap->clear();
  429. }
  430. // gpio_uninstall_isr_service(); can't uninstall, isr service is used by camera
  431. }
  432. void GpioHandler::registerGpioUri()
  433. {
  434. ESP_LOGI(TAG, "server_GPIO - Registering URI handlers");
  435. httpd_uri_t camuri = { };
  436. camuri.method = HTTP_GET;
  437. camuri.uri = "/GPIO";
  438. camuri.handler = APPLY_BASIC_AUTH_FILTER(callHandleHttpRequest);
  439. camuri.user_ctx = (void*)this;
  440. httpd_register_uri_handler(_httpServer, &camuri);
  441. }
  442. esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
  443. {
  444. ESP_LOGD(TAG, "handleHttpRequest");
  445. if (gpioMap == NULL) {
  446. std::string resp_str = "GPIO handler not initialized";
  447. httpd_resp_send(req, resp_str.c_str(), resp_str.length());
  448. return ESP_OK;
  449. }
  450. #ifdef DEBUG_DETAIL_ON
  451. LogFile.WriteHeapInfo("handler_switch_GPIO - Start");
  452. #endif
  453. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_switch_GPIO");
  454. char _query[200];
  455. char _valueGPIO[30];
  456. char _valueStatus[30];
  457. std::string gpio, status;
  458. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK) {
  459. ESP_LOGD(TAG, "Query: %s", _query);
  460. if (httpd_query_key_value(_query, "GPIO", _valueGPIO, 30) == ESP_OK)
  461. {
  462. ESP_LOGD(TAG, "GPIO is found %s", _valueGPIO);
  463. gpio = std::string(_valueGPIO);
  464. } else {
  465. std::string resp_str = "GPIO No is not defined";
  466. httpd_resp_send(req, resp_str.c_str(), resp_str.length());
  467. return ESP_OK;
  468. }
  469. if (httpd_query_key_value(_query, "Status", _valueStatus, 30) == ESP_OK)
  470. {
  471. ESP_LOGD(TAG, "Status is found %s", _valueStatus);
  472. status = std::string(_valueStatus);
  473. }
  474. } else {
  475. const char* resp_str = "Error in call. Use /GPIO?GPIO=12&Status=high";
  476. httpd_resp_send(req, resp_str, strlen(resp_str));
  477. return ESP_OK;
  478. }
  479. status = toUpper(status);
  480. if ((status != "HIGH") && (status != "LOW") && (status != "TRUE") && (status != "FALSE") && (status != "0") && (status != "1") && (status != ""))
  481. {
  482. std::string zw = "Status not valid: " + status;
  483. httpd_resp_sendstr_chunk(req, zw.c_str());
  484. httpd_resp_sendstr_chunk(req, NULL);
  485. return ESP_OK;
  486. }
  487. int gpionum = stoi(gpio);
  488. // frei: 16; 12-15; 2; 4 // nur 12 und 13 funktionieren 2: reboot, 4: BlitzLED, 15: PSRAM, 14/15: DMA für SDKarte ???
  489. gpio_num_t gpio_num = resolvePinNr(gpionum);
  490. if (gpio_num == GPIO_NUM_NC)
  491. {
  492. std::string zw = "GPIO" + std::to_string(gpionum) + " unsupported - only 12 & 13 free";
  493. httpd_resp_sendstr_chunk(req, zw.c_str());
  494. httpd_resp_sendstr_chunk(req, NULL);
  495. return ESP_OK;
  496. }
  497. if (gpioMap->count(gpio_num) == 0) {
  498. char resp_str [30];
  499. sprintf(resp_str, "GPIO%d is not registred", gpio_num);
  500. httpd_resp_send(req, resp_str, strlen(resp_str));
  501. return ESP_OK;
  502. }
  503. if (status == "")
  504. {
  505. std::string resp_str = "";
  506. status = (*gpioMap)[gpio_num]->getValue(&resp_str) ? "HIGH" : "LOW";
  507. if (resp_str == "") {
  508. resp_str = status;
  509. }
  510. httpd_resp_sendstr_chunk(req, resp_str.c_str());
  511. httpd_resp_sendstr_chunk(req, NULL);
  512. }
  513. else
  514. {
  515. std::string resp_str = "";
  516. (*gpioMap)[gpio_num]->setValue((status == "HIGH") || (status == "TRUE") || (status == "1"), GPIO_SET_SOURCE_HTTP, &resp_str);
  517. if (resp_str == "") {
  518. resp_str = "GPIO" + std::to_string(gpionum) + " switched to " + status;
  519. }
  520. httpd_resp_sendstr_chunk(req, resp_str.c_str());
  521. httpd_resp_sendstr_chunk(req, NULL);
  522. }
  523. return ESP_OK;
  524. };
  525. void GpioHandler::flashLightEnable(bool value)
  526. {
  527. ESP_LOGD(TAG, "GpioHandler::flashLightEnable %s", value ? "true" : "false");
  528. if (gpioMap != NULL) {
  529. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it)
  530. {
  531. 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))
  532. {
  533. std::string resp_str = "";
  534. it->second->setValue(value, GPIO_SET_SOURCE_INTERNAL, &resp_str);
  535. if (resp_str == "") {
  536. ESP_LOGD(TAG, "Flash light pin GPIO %d switched to %s", (int)it->first, (value ? "on" : "off"));
  537. } else {
  538. ESP_LOGE(TAG, "Can't set flash light pin GPIO %d. Error: %s", (int)it->first, resp_str.c_str());
  539. }
  540. } else
  541. {
  542. if (it->second->getMode() == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
  543. {
  544. #ifdef __LEDGLOBAL
  545. if (leds_global == NULL) {
  546. ESP_LOGI(TAG, "init SmartLed: LEDNumber=%d, GPIO=%d", LEDNumbers, (int)it->second->getGPIO());
  547. leds_global = new SmartLed( LEDType, LEDNumbers, it->second->getGPIO(), 0, DoubleBuffer );
  548. } else {
  549. // wait until we can update: https://github.com/RoboticsBrno/SmartLeds/issues/10#issuecomment-386921623
  550. leds_global->wait();
  551. }
  552. #else
  553. SmartLed leds( LEDType, LEDNumbers, it->second->getGPIO(), 0, DoubleBuffer );
  554. #endif
  555. if (value)
  556. {
  557. for (int i = 0; i < LEDNumbers; ++i)
  558. #ifdef __LEDGLOBAL
  559. (*leds_global)[i] = LEDColor;
  560. #else
  561. leds[i] = LEDColor;
  562. #endif
  563. }
  564. else
  565. {
  566. for (int i = 0; i < LEDNumbers; ++i)
  567. #ifdef __LEDGLOBAL
  568. (*leds_global)[i] = Rgb{0, 0, 0};
  569. #else
  570. leds[i] = Rgb{0, 0, 0};
  571. #endif
  572. }
  573. #ifdef __LEDGLOBAL
  574. leds_global->show();
  575. #else
  576. leds.show();
  577. #endif
  578. }
  579. }
  580. }
  581. }
  582. }
  583. gpio_num_t GpioHandler::resolvePinNr(uint8_t pinNr)
  584. {
  585. switch(pinNr) {
  586. case 0:
  587. return GPIO_NUM_0;
  588. case 1:
  589. return GPIO_NUM_1;
  590. case 3:
  591. return GPIO_NUM_3;
  592. case 4:
  593. return GPIO_NUM_4;
  594. case 12:
  595. return GPIO_NUM_12;
  596. case 13:
  597. return GPIO_NUM_13;
  598. default:
  599. return GPIO_NUM_NC;
  600. }
  601. }
  602. gpio_pin_mode_t GpioHandler::resolvePinMode(std::string input)
  603. {
  604. if( input == "disabled" ) return GPIO_PIN_MODE_DISABLED;
  605. if( input == "input" ) return GPIO_PIN_MODE_INPUT;
  606. if( input == "input-pullup" ) return GPIO_PIN_MODE_INPUT_PULLUP;
  607. if( input == "input-pulldown" ) return GPIO_PIN_MODE_INPUT_PULLDOWN;
  608. if( input == "output" ) return GPIO_PIN_MODE_OUTPUT;
  609. if( input == "built-in-led" ) return GPIO_PIN_MODE_BUILT_IN_FLASH_LED;
  610. if( input == "output-pwm" ) return GPIO_PIN_MODE_OUTPUT_PWM;
  611. if( input == "external-flash-pwm" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_PWM;
  612. if( input == "external-flash-ws281x" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X;
  613. return GPIO_PIN_MODE_DISABLED;
  614. }
  615. gpio_int_type_t GpioHandler::resolveIntType(std::string input)
  616. {
  617. if( input == "disabled" ) return GPIO_INTR_DISABLE;
  618. if( input == "rising-edge" ) return GPIO_INTR_POSEDGE;
  619. if( input == "falling-edge" ) return GPIO_INTR_NEGEDGE;
  620. if( input == "rising-and-falling" ) return GPIO_INTR_ANYEDGE ;
  621. if( input == "low-level-trigger" ) return GPIO_INTR_LOW_LEVEL;
  622. if( input == "high-level-trigger" ) return GPIO_INTR_HIGH_LEVEL;
  623. return GPIO_INTR_DISABLE;
  624. }
  625. static GpioHandler *gpioHandler = NULL;
  626. void gpio_handler_create(httpd_handle_t server)
  627. {
  628. if (gpioHandler == NULL) {
  629. gpioHandler = new (std::nothrow) GpioHandler(CONFIG_FILE, server);
  630. if (gpioHandler == NULL) {
  631. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO handler");
  632. }
  633. }
  634. }
  635. void gpio_handler_init()
  636. {
  637. if (gpioHandler != NULL) {
  638. gpioHandler->init();
  639. }
  640. }
  641. void gpio_handler_deinit() {
  642. if (gpioHandler != NULL) {
  643. gpioHandler->deinit();
  644. }
  645. }
  646. void gpio_handler_destroy()
  647. {
  648. if (gpioHandler != NULL) {
  649. gpio_handler_deinit();
  650. delete gpioHandler;
  651. gpioHandler = NULL;
  652. }
  653. }
  654. GpioHandler* gpio_handler_get()
  655. {
  656. return gpioHandler;
  657. }