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.

208 lines
5.6 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. // Not API request
  97. String url = request->url();
  98. if (!url.startsWith("/api/")) return false;
  99. for (unsigned char i=0; i < _apis.size(); i++) {
  100. // Search API url
  101. web_api_t api = _apis[i];
  102. if (!url.endsWith(api.key)) continue;
  103. // Log and check credentials
  104. webLog(request);
  105. if (!_authAPI(request)) return false;
  106. // Check if its a PUT
  107. if (api.putFn != NULL) {
  108. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  109. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  110. (api.putFn)((p->value()).c_str());
  111. }
  112. }
  113. // Get response from callback
  114. char value[API_BUFFER_SIZE] = {0};
  115. (api.getFn)(value, API_BUFFER_SIZE);
  116. // The response will be a 404 NOT FOUND if the resource is not available
  117. if (0 == value[0]) {
  118. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  119. request->send(404);
  120. return false;
  121. }
  122. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  123. // Format response according to the Accept header
  124. if (_asJson(request)) {
  125. char buffer[64];
  126. if (isNumber(value)) {
  127. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  128. } else {
  129. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": \"%s\" }"), api.key, value);
  130. }
  131. request->send(200, "application/json", buffer);
  132. } else {
  133. request->send(200, "text/plain", value);
  134. }
  135. return true;
  136. }
  137. return false;
  138. }
  139. // -----------------------------------------------------------------------------
  140. void apiRegister(const char * key, api_get_callback_f getFn, api_put_callback_f putFn) {
  141. // Store it
  142. web_api_t api;
  143. api.key = strdup(key);
  144. api.getFn = getFn;
  145. api.putFn = putFn;
  146. _apis.push_back(api);
  147. }
  148. void apiSetup() {
  149. webServer()->on("/apis", HTTP_GET, _onAPIs);
  150. webServer()->on("/rpc", HTTP_GET, _onRPC);
  151. wsOnSendRegister(_apiWebSocketOnSend);
  152. wsOnReceiveRegister(_apiWebSocketOnReceive);
  153. webRequestRegister(_apiRequestCallback);
  154. }
  155. #endif // WEB_SUPPORT