server_GPIO.cpp 22 KB

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