Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
5.8 KiB

  1. /*
  2. API MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. Module key prefix: api
  5. */
  6. #if API_SUPPORT
  7. #include <ESPAsyncTCP.h>
  8. #include <ESPAsyncWebServer.h>
  9. #include <ArduinoJson.h>
  10. #include <vector>
  11. typedef struct {
  12. char * key;
  13. api_get_callback_f getFn = NULL;
  14. api_put_callback_f putFn = NULL;
  15. } web_api_t;
  16. std::vector<web_api_t> _apis;
  17. // -----------------------------------------------------------------------------
  18. bool _apiKeyCheck(const char * key) {
  19. return (strncmp(key, "api", 3) == 0);
  20. }
  21. void _apiWebSocketOnSend(JsonObject& root) {
  22. root["apiVisible"] = 1;
  23. root["apiEnabled"] = getSetting("apiEnabled", API_ENABLED).toInt() == 1;
  24. root["apiKey"] = getSetting("apiKey");
  25. root["apiRealTime"] = apiRealTime();
  26. }
  27. // -----------------------------------------------------------------------------
  28. // API
  29. // -----------------------------------------------------------------------------
  30. bool _authAPI(AsyncWebServerRequest *request) {
  31. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  32. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  33. request->send(403);
  34. return false;
  35. }
  36. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  37. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  38. request->send(403);
  39. return false;
  40. }
  41. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  42. if (!p->value().equals(getSetting("apiKey"))) {
  43. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  44. request->send(403);
  45. return false;
  46. }
  47. return true;
  48. }
  49. bool _asJson(AsyncWebServerRequest *request) {
  50. bool asJson = false;
  51. if (request->hasHeader("Accept")) {
  52. AsyncWebHeader* h = request->getHeader("Accept");
  53. asJson = h->value().equals("application/json");
  54. }
  55. return asJson;
  56. }
  57. void _onAPIs(AsyncWebServerRequest *request) {
  58. webLog(request);
  59. if (!_authAPI(request)) return;
  60. bool asJson = _asJson(request);
  61. char buffer[40];
  62. String output;
  63. if (asJson) {
  64. DynamicJsonBuffer jsonBuffer;
  65. JsonObject& root = jsonBuffer.createObject();
  66. for (unsigned int i=0; i < _apis.size(); i++) {
  67. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), _apis[i].key);
  68. root[_apis[i].key] = String(buffer);
  69. }
  70. root.printTo(output);
  71. jsonBuffer.clear();
  72. request->send(200, "application/json", output);
  73. } else {
  74. for (unsigned int i=0; i < _apis.size(); i++) {
  75. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), _apis[i].key);
  76. output += _apis[i].key + String(" -> ") + String(buffer) + String("\n");
  77. }
  78. request->send(200, "text/plain", output);
  79. }
  80. }
  81. void _onRPC(AsyncWebServerRequest *request) {
  82. webLog(request);
  83. if (!_authAPI(request)) return;
  84. //bool asJson = _asJson(request);
  85. int response = 404;
  86. if (request->hasParam("action")) {
  87. AsyncWebParameter* p = request->getParam("action");
  88. String action = p->value();
  89. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  90. if (action.equals("reboot")) {
  91. response = 200;
  92. deferredReset(100, CUSTOM_RESET_RPC);
  93. }
  94. }
  95. request->send(response);
  96. }
  97. bool _apiRequestCallback(AsyncWebServerRequest *request) {
  98. String url = request->url();
  99. // Main API entry point
  100. if (url.equals("/api") || url.equals("/apis")) {
  101. _onAPIs(request);
  102. return true;
  103. }
  104. // Main RPC entry point
  105. if (url.equals("/rpc")) {
  106. _onRPC(request);
  107. return true;
  108. }
  109. // Not API request
  110. if (!url.startsWith("/api/")) return false;
  111. for (unsigned char i=0; i < _apis.size(); i++) {
  112. // Search API url
  113. web_api_t api = _apis[i];
  114. if (!url.endsWith(api.key)) continue;
  115. // Log and check credentials
  116. webLog(request);
  117. if (!_authAPI(request)) return false;
  118. // Check if its a PUT
  119. if (api.putFn != NULL) {
  120. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  121. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  122. (api.putFn)((p->value()).c_str());
  123. }
  124. }
  125. // Get response from callback
  126. char value[API_BUFFER_SIZE] = {0};
  127. (api.getFn)(value, API_BUFFER_SIZE);
  128. // The response will be a 404 NOT FOUND if the resource is not available
  129. if (0 == value[0]) {
  130. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  131. request->send(404);
  132. return false;
  133. }
  134. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  135. // Format response according to the Accept header
  136. if (_asJson(request)) {
  137. char buffer[64];
  138. if (isNumber(value)) {
  139. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  140. } else {
  141. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": \"%s\" }"), api.key, value);
  142. }
  143. request->send(200, "application/json", buffer);
  144. } else {
  145. request->send(200, "text/plain", value);
  146. }
  147. return true;
  148. }
  149. return false;
  150. }
  151. // -----------------------------------------------------------------------------
  152. void apiRegister(const char * key, api_get_callback_f getFn, api_put_callback_f putFn) {
  153. // Store it
  154. web_api_t api;
  155. api.key = strdup(key);
  156. api.getFn = getFn;
  157. api.putFn = putFn;
  158. _apis.push_back(api);
  159. }
  160. bool apiRealTime() {
  161. return getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  162. }
  163. void apiSetup() {
  164. settingsRegisterKeyCheck(_apiKeyCheck);
  165. webRequestRegister(_apiRequestCallback);
  166. wsOnSendRegister(_apiWebSocketOnSend);
  167. }
  168. #endif // API_SUPPORT