server_GPIO.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 "esp_log.h"
  10. //#include "errno.h"
  11. #include <sys/stat.h>
  12. #include <vector>
  13. //#include <regex>
  14. #include "server_GPIO.h"
  15. #include "ClassLogFile.h"
  16. #include "configFile.h"
  17. #include "Helper.h"
  18. #include "interface_mqtt.h"
  19. #include "ClassFlowMQTT.h"
  20. static const char *TAG_SERVERGPIO = "server_GPIO";
  21. QueueHandle_t gpio_queue_handle = NULL;
  22. #define DEBUG_DETAIL_ON
  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_SERVERGPIO,"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) == 1;
  45. BaseType_t ContextSwitchRequest = pdFALSE;
  46. xQueueSendToBackFromISR(gpio_queue_handle,(void*)&gpioResult,&ContextSwitchRequest);
  47. if(ContextSwitchRequest){
  48. taskYIELD();
  49. }
  50. }
  51. static void gpioInterruptTask(void *arg) {
  52. while(1){
  53. if(uxQueueMessagesWaiting(gpio_queue_handle)){
  54. while(uxQueueMessagesWaiting(gpio_queue_handle)){
  55. GpioResult gpioResult;
  56. xQueueReceive(gpio_queue_handle,(void*)&gpioResult,10);
  57. ESP_LOGD(TAG_SERVERGPIO,"gpio: %d state: %d", gpioResult.gpio, gpioResult.value);
  58. ((GpioHandler*)arg)->gpioInterrupt(&gpioResult);
  59. }
  60. }
  61. vTaskDelay(pdMS_TO_TICKS(1000));
  62. }
  63. }
  64. void GpioPin::gpioInterrupt(bool value) {
  65. if (_mqttTopic != "") {
  66. ESP_LOGD(TAG_SERVERGPIO, "gpioInterrupt %s %d", _mqttTopic.c_str(), value);
  67. MQTTPublish(_mqttTopic, value ? "true" : "false");
  68. }
  69. }
  70. void GpioPin::init()
  71. {
  72. gpio_config_t io_conf;
  73. //set interrupt
  74. io_conf.intr_type = _interruptType;
  75. //set as output mode
  76. 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;
  77. //bit mask of the pins that you want to set,e.g.GPIO18/19
  78. io_conf.pin_bit_mask = (1ULL << _gpio);
  79. //set pull-down mode
  80. io_conf.pull_down_en = _mode == GPIO_PIN_MODE_INPUT_PULLDOWN ? gpio_pulldown_t::GPIO_PULLDOWN_ENABLE : gpio_pulldown_t::GPIO_PULLDOWN_DISABLE;
  81. //set pull-up mode
  82. io_conf.pull_up_en = _mode == GPIO_PIN_MODE_INPUT_PULLDOWN ? gpio_pullup_t::GPIO_PULLUP_ENABLE : gpio_pullup_t::GPIO_PULLUP_DISABLE;
  83. //configure GPIO with the given settings
  84. gpio_config(&io_conf);
  85. if (_interruptType != GPIO_INTR_DISABLE) {
  86. //hook isr handler for specific gpio pin
  87. gpio_isr_handler_add(_gpio, gpio_isr_handler, (void*)&_gpio);
  88. }
  89. if ((_mqttTopic != "") && ((_mode == GPIO_PIN_MODE_OUTPUT) || (_mode == GPIO_PIN_MODE_OUTPUT_PWM) || (_mode == GPIO_PIN_MODE_BUILT_IN_FLASH_LED))) {
  90. std::function<bool(std::string, char*, int)> f = std::bind(&GpioPin::handleMQTT, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
  91. MQTTregisterSubscribeFunction(_mqttTopic, f);
  92. }
  93. }
  94. bool GpioPin::getValue(std::string* errorText)
  95. {
  96. if ((_mode != GPIO_PIN_MODE_INPUT) && (_mode != GPIO_PIN_MODE_INPUT_PULLUP) && (_mode != GPIO_PIN_MODE_INPUT_PULLDOWN)) {
  97. (*errorText) = "GPIO is not in input mode";
  98. }
  99. return gpio_get_level(_gpio) == 1;
  100. }
  101. void GpioPin::setValue(bool value, gpio_set_source setSource, std::string* errorText)
  102. {
  103. ESP_LOGD(TAG_SERVERGPIO, "GpioPin::setValue %d\r\n", value);
  104. if ((_mode != GPIO_PIN_MODE_OUTPUT) && (_mode != GPIO_PIN_MODE_OUTPUT_PWM) && (_mode != GPIO_PIN_MODE_BUILT_IN_FLASH_LED)) {
  105. (*errorText) = "GPIO is not in output mode";
  106. } else {
  107. gpio_set_level(_gpio, value);
  108. if ((_mqttTopic != "") && (setSource != GPIO_SET_SOURCE_MQTT)) {
  109. MQTTPublish(_mqttTopic, value ? "true" : "false");
  110. }
  111. }
  112. }
  113. bool GpioPin::handleMQTT(std::string, char* data, int data_len) {
  114. ESP_LOGD(TAG_SERVERGPIO, "GpioPin::handleMQTT data %.*s\r\n", data_len, data);
  115. std::string dataStr(data, data_len);
  116. dataStr = toLower(dataStr);
  117. std::string errorText = "";
  118. if ((dataStr == "true") || (dataStr == "1")) {
  119. setValue(true, GPIO_SET_SOURCE_MQTT, &errorText);
  120. } else if ((dataStr == "false") || (dataStr == "0")) {
  121. setValue(false, GPIO_SET_SOURCE_MQTT, &errorText);
  122. } else {
  123. errorText = "wrong value ";
  124. errorText.append(data, data_len);
  125. }
  126. if (errorText != "") {
  127. ESP_LOGE(TAG_SERVERGPIO, "%s", errorText.c_str());
  128. }
  129. return (errorText == "");
  130. }
  131. esp_err_t callHandleHttpRequest(httpd_req_t *req)
  132. {
  133. ESP_LOGD(TAG_SERVERGPIO,"callHandleHttpRequest");
  134. GpioHandler *gpioHandler = (GpioHandler*)req->user_ctx;
  135. return gpioHandler->handleHttpRequest(req);
  136. }
  137. void taskGpioHandler(void *pvParameter)
  138. {
  139. ESP_LOGD(TAG_SERVERGPIO,"taskGpioHandler");
  140. ((GpioHandler*)pvParameter)->init();
  141. }
  142. GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer)
  143. {
  144. ESP_LOGI(TAG_SERVERGPIO,"start GpioHandler");
  145. _configFile = configFile;
  146. _httpServer = httpServer;
  147. ESP_LOGI(TAG_SERVERGPIO, "register GPIO Uri");
  148. registerGpioUri();
  149. //xTaskCreate((TaskFunction_t)&taskGpioHandler, "taskGpioHandler", configMINIMAL_STACK_SIZE * 64, this, tskIDLE_PRIORITY+1, &xHandletaskGpioHandler);
  150. }
  151. GpioHandler::~GpioHandler() {
  152. if (gpioMap != NULL) {
  153. clear();
  154. delete gpioMap;
  155. }
  156. }
  157. void GpioHandler::init()
  158. {
  159. // TickType_t xDelay = 60000 / portTICK_PERIOD_MS;
  160. // printf("wait before start %ldms\r\n", (long) xDelay);
  161. // vTaskDelay( xDelay );
  162. if (gpioMap == NULL) {
  163. gpioMap = new std::map<gpio_num_t, GpioPin*>();
  164. } else {
  165. clear();
  166. }
  167. ESP_LOGI(TAG_SERVERGPIO, "read GPIO config and init GPIO");
  168. readConfig();
  169. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  170. it->second->init();
  171. if ((it->second->getInterruptType() != GPIO_INTR_DISABLE) && (gpio_queue_handle == NULL)) {
  172. gpio_queue_handle = xQueueCreate(10,sizeof(GpioResult));
  173. xTaskCreate(gpioInterruptTask, "GPIO Task", configMINIMAL_STACK_SIZE * 64, (void *)this, 10, NULL);
  174. }
  175. }
  176. ESP_LOGI(TAG_SERVERGPIO, "GPIO init comleted");
  177. }
  178. void GpioHandler::deinit() {
  179. clear();
  180. }
  181. void GpioHandler::gpioInterrupt(GpioResult* gpioResult) {
  182. if ((gpioMap != NULL) && (gpioMap->find(gpioResult->gpio) != gpioMap->end())) {
  183. (*gpioMap)[gpioResult->gpio]->gpioInterrupt(gpioResult->value);
  184. }
  185. }
  186. bool GpioHandler::readConfig()
  187. {
  188. if (!gpioMap->empty())
  189. clear();
  190. ConfigFile configFile = ConfigFile(_configFile);
  191. std::vector<std::string> zerlegt;
  192. std::string line = "";
  193. bool disabledLine = false;
  194. bool eof = false;
  195. while ((!configFile.GetNextParagraph(line, disabledLine, eof) || (line.compare("[GPIO]") != 0)) && !disabledLine && !eof) {}
  196. if (eof)
  197. return false;
  198. _isEnabled = true;
  199. std::string mainTopicMQTT = "";
  200. bool registerISR = false;
  201. while (configFile.getNextLine(&line, disabledLine, eof) && !configFile.isNewParagraph(line))
  202. {
  203. zerlegt = configFile.ZerlegeZeile(line);
  204. // const std::regex pieces_regex("IO([0-9]{1,2})");
  205. // std::smatch pieces_match;
  206. // if (std::regex_match(zerlegt[0], pieces_match, pieces_regex) && (pieces_match.size() == 2))
  207. // {
  208. // std::string gpioStr = pieces_match[1];
  209. ESP_LOGD(TAG_SERVERGPIO, "conf param %s\r\n", toUpper(zerlegt[0]).c_str());
  210. if (toUpper(zerlegt[0]) == "MAINTOPICMQTT") {
  211. ESP_LOGD(TAG_SERVERGPIO, "MAINTOPICMQTT found\r\n");
  212. mainTopicMQTT = zerlegt[1];
  213. } else if ((zerlegt[0].rfind("IO", 0) == 0) && (zerlegt.size() >= 6))
  214. {
  215. ESP_LOGI(TAG_SERVERGPIO,"Enable GP%s in %s mode", zerlegt[0].c_str(), zerlegt[1].c_str());
  216. std::string gpioStr = zerlegt[0].substr(2, 2);
  217. gpio_num_t gpioNr = (gpio_num_t)atoi(gpioStr.c_str());
  218. gpio_pin_mode_t pinMode = resolvePinMode(toLower(zerlegt[1]));
  219. gpio_int_type_t intType = resolveIntType(toLower(zerlegt[2]));
  220. uint16_t dutyResolution = (uint8_t)atoi(zerlegt[3].c_str());
  221. bool mqttEnabled = toLower(zerlegt[4]) == "true";
  222. bool httpEnabled = toLower(zerlegt[5]) == "true";
  223. char gpioName[100];
  224. if (zerlegt.size() >= 7) {
  225. strcpy(gpioName, trim(zerlegt[6]).c_str());
  226. } else {
  227. sprintf(gpioName, "GPIO%d", gpioNr);
  228. }
  229. std::string mqttTopic = mqttEnabled ? (mainTopicMQTT + "/" + gpioName) : "";
  230. GpioPin* gpioPin = new GpioPin(gpioNr, gpioName, pinMode, intType,dutyResolution, mqttTopic, httpEnabled);
  231. (*gpioMap)[gpioNr] = gpioPin;
  232. if (intType != GPIO_INTR_DISABLE) {
  233. registerISR = true;
  234. }
  235. }
  236. }
  237. if (registerISR) {
  238. //install gpio isr service
  239. gpio_install_isr_service(ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM);
  240. }
  241. return true;
  242. }
  243. void GpioHandler::clear()
  244. {
  245. ESP_LOGD(TAG_SERVERGPIO, "GpioHandler::clear\r\n");
  246. if (gpioMap != NULL) {
  247. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  248. delete it->second;
  249. }
  250. gpioMap->clear();
  251. }
  252. // gpio_uninstall_isr_service(); can't uninstall, isr service is used by camera
  253. }
  254. void GpioHandler::registerGpioUri()
  255. {
  256. ESP_LOGI(TAG_SERVERGPIO, "server_GPIO - Registering URI handlers");
  257. httpd_uri_t camuri = { };
  258. camuri.method = HTTP_GET;
  259. camuri.uri = "/GPIO";
  260. camuri.handler = callHandleHttpRequest;
  261. camuri.user_ctx = (void*)this;
  262. httpd_register_uri_handler(_httpServer, &camuri);
  263. }
  264. esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
  265. {
  266. ESP_LOGD(TAG_SERVERGPIO, "handleHttpRequest");
  267. if (gpioMap == NULL) {
  268. std::string resp_str = "GPIO handler not initialized";
  269. httpd_resp_send(req, resp_str.c_str(), resp_str.length());
  270. return ESP_OK;
  271. }
  272. #ifdef DEBUG_DETAIL_ON
  273. LogFile.WriteHeapInfo("handler_switch_GPIO - Start");
  274. #endif
  275. LogFile.WriteToFile("handler_switch_GPIO");
  276. char _query[200];
  277. char _valueGPIO[30];
  278. char _valueStatus[30];
  279. std::string gpio, status;
  280. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK) {
  281. ESP_LOGD(TAG_SERVERGPIO, "Query: %s", _query);
  282. if (httpd_query_key_value(_query, "GPIO", _valueGPIO, 30) == ESP_OK)
  283. {
  284. ESP_LOGD(TAG_SERVERGPIO, "GPIO is found %s", _valueGPIO);
  285. gpio = std::string(_valueGPIO);
  286. } else {
  287. std::string resp_str = "GPIO No is not defined";
  288. httpd_resp_send(req, resp_str.c_str(), resp_str.length());
  289. return ESP_OK;
  290. }
  291. if (httpd_query_key_value(_query, "Status", _valueStatus, 30) == ESP_OK)
  292. {
  293. ESP_LOGD(TAG_SERVERGPIO, "Status is found %s", _valueStatus);
  294. status = std::string(_valueStatus);
  295. }
  296. } else {
  297. const char* resp_str = "Error in call. Use /GPIO?GPIO=12&Status=high";
  298. httpd_resp_send(req, resp_str, strlen(resp_str));
  299. return ESP_OK;
  300. }
  301. status = toUpper(status);
  302. if ((status != "HIGH") && (status != "LOW") && (status != "TRUE") && (status != "FALSE") && (status != "0") && (status != "1") && (status != ""))
  303. {
  304. std::string zw = "Status not valid: " + status;
  305. httpd_resp_sendstr_chunk(req, zw.c_str());
  306. httpd_resp_sendstr_chunk(req, NULL);
  307. return ESP_OK;
  308. }
  309. int gpionum = stoi(gpio);
  310. // frei: 16; 12-15; 2; 4 // nur 12 und 13 funktionieren 2: reboot, 4: BlitzLED, 15: PSRAM, 14/15: DMA für SDKarte ???
  311. gpio_num_t gpio_num = resolvePinNr(gpionum);
  312. if (gpio_num == GPIO_NUM_NC)
  313. {
  314. std::string zw = "GPIO" + std::to_string(gpionum) + " not support - only 12 & 13 free";
  315. httpd_resp_sendstr_chunk(req, zw.c_str());
  316. httpd_resp_sendstr_chunk(req, NULL);
  317. return ESP_OK;
  318. }
  319. if (gpioMap->count(gpio_num) == 0) {
  320. char resp_str [30];
  321. sprintf(resp_str, "GPIO%d is not registred", gpio_num);
  322. httpd_resp_send(req, resp_str, strlen(resp_str));
  323. return ESP_OK;
  324. }
  325. if (status == "")
  326. {
  327. std::string resp_str = "";
  328. status = (*gpioMap)[gpio_num]->getValue(&resp_str) ? "HIGH" : "LOW";
  329. if (resp_str == "") {
  330. resp_str = status;
  331. }
  332. httpd_resp_sendstr_chunk(req, resp_str.c_str());
  333. httpd_resp_sendstr_chunk(req, NULL);
  334. }
  335. else
  336. {
  337. std::string resp_str = "";
  338. (*gpioMap)[gpio_num]->setValue((status == "HIGH") || (status == "TRUE") || (status == "1"), GPIO_SET_SOURCE_HTTP, &resp_str);
  339. if (resp_str == "") {
  340. resp_str = "GPIO" + std::to_string(gpionum) + " switched to " + status;
  341. }
  342. httpd_resp_sendstr_chunk(req, resp_str.c_str());
  343. httpd_resp_sendstr_chunk(req, NULL);
  344. }
  345. return ESP_OK;
  346. };
  347. void GpioHandler::flashLightEnable(bool value)
  348. {
  349. ESP_LOGD(TAG_SERVERGPIO, "GpioHandler::flashLightEnable %s\r\n", value ? "true" : "false");
  350. if (gpioMap != NULL) {
  351. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it)
  352. {
  353. 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))
  354. {
  355. std::string resp_str = "";
  356. it->second->setValue(value, GPIO_SET_SOURCE_INTERNAL, &resp_str);
  357. if (resp_str == "") {
  358. ESP_LOGD(TAG_SERVERGPIO, "Flash light pin GPIO %d switched to %s\r\n", (int)it->first, (value ? "on" : "off"));
  359. } else {
  360. ESP_LOGE(TAG_SERVERGPIO, "Can't set flash light pin GPIO %d. Error: %s\r\n", (int)it->first, resp_str.c_str());
  361. }
  362. }
  363. }
  364. }
  365. }
  366. gpio_num_t GpioHandler::resolvePinNr(uint8_t pinNr)
  367. {
  368. switch(pinNr) {
  369. case 0:
  370. return GPIO_NUM_0;
  371. case 1:
  372. return GPIO_NUM_1;
  373. case 3:
  374. return GPIO_NUM_3;
  375. case 4:
  376. return GPIO_NUM_4;
  377. case 12:
  378. return GPIO_NUM_12;
  379. case 13:
  380. return GPIO_NUM_13;
  381. default:
  382. return GPIO_NUM_NC;
  383. }
  384. }
  385. gpio_pin_mode_t GpioHandler::resolvePinMode(std::string input)
  386. {
  387. if( input == "disabled" ) return GPIO_PIN_MODE_DISABLED;
  388. if( input == "input" ) return GPIO_PIN_MODE_INPUT;
  389. if( input == "input-pullup" ) return GPIO_PIN_MODE_INPUT_PULLUP;
  390. if( input == "input-pulldown" ) return GPIO_PIN_MODE_INPUT_PULLDOWN;
  391. if( input == "output" ) return GPIO_PIN_MODE_OUTPUT;
  392. if( input == "built-in-led" ) return GPIO_PIN_MODE_BUILT_IN_FLASH_LED;
  393. if( input == "output-pwm" ) return GPIO_PIN_MODE_OUTPUT_PWM;
  394. if( input == "external-flash-pwm" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_PWM;
  395. if( input == "external-flash-ws281x" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X;
  396. return GPIO_PIN_MODE_DISABLED;
  397. }
  398. gpio_int_type_t GpioHandler::resolveIntType(std::string input)
  399. {
  400. if( input == "disabled" ) return GPIO_INTR_DISABLE;
  401. if( input == "rising-edge" ) return GPIO_INTR_POSEDGE;
  402. if( input == "falling-edge" ) return GPIO_INTR_NEGEDGE;
  403. if( input == "rising-and-falling" ) return GPIO_INTR_ANYEDGE ;
  404. if( input == "low-level-trigger" ) return GPIO_INTR_LOW_LEVEL;
  405. if( input == "high-level-trigger" ) return GPIO_INTR_HIGH_LEVEL;
  406. return GPIO_INTR_DISABLE;
  407. }