server_GPIO.cpp 22 KB

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