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.

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