server_GPIO.cpp 13 KB

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