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.

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