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.

251 lines
6.6 KiB

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