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.

201 lines
5.5 KiB

6 years ago
6 years ago
  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. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  56. return [apiID](AsyncWebServerRequest *request) {
  57. webLog(request);
  58. if (!_authAPI(request)) return;
  59. web_api_t api = _apis[apiID];
  60. // Check if its a PUT
  61. if (api.putFn != NULL) {
  62. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  63. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  64. (api.putFn)((p->value()).c_str());
  65. }
  66. }
  67. // Get response from callback
  68. char value[API_BUFFER_SIZE] = {0};
  69. (api.getFn)(value, API_BUFFER_SIZE);
  70. // The response will be a 404 NOT FOUND if the resource is not available
  71. if (0 == value[0]) {
  72. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  73. request->send(404);
  74. return;
  75. }
  76. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  77. // Format response according to the Accept header
  78. if (_asJson(request)) {
  79. char buffer[64];
  80. if (isNumber(value)) {
  81. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  82. } else {
  83. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": \"%s\" }"), api.key, value);
  84. }
  85. request->send(200, "application/json", buffer);
  86. } else {
  87. request->send(200, "text/plain", value);
  88. }
  89. };
  90. }
  91. void _onAPIs(AsyncWebServerRequest *request) {
  92. webLog(request);
  93. if (!_authAPI(request)) return;
  94. bool asJson = _asJson(request);
  95. char buffer[40];
  96. String output;
  97. if (asJson) {
  98. DynamicJsonBuffer jsonBuffer;
  99. JsonObject& root = jsonBuffer.createObject();
  100. for (unsigned int i=0; i < _apis.size(); i++) {
  101. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), _apis[i].key);
  102. root[_apis[i].key] = String(buffer);
  103. }
  104. root.printTo(output);
  105. request->send(200, "application/json", output);
  106. } else {
  107. for (unsigned int i=0; i < _apis.size(); i++) {
  108. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), _apis[i].key);
  109. output += _apis[i].key + String(" -> ") + String(buffer) + String("\n");
  110. }
  111. request->send(200, "text/plain", output);
  112. }
  113. }
  114. void _onRPC(AsyncWebServerRequest *request) {
  115. webLog(request);
  116. if (!_authAPI(request)) return;
  117. //bool asJson = _asJson(request);
  118. int response = 404;
  119. if (request->hasParam("action")) {
  120. AsyncWebParameter* p = request->getParam("action");
  121. String action = p->value();
  122. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  123. if (action.equals("reboot")) {
  124. response = 200;
  125. deferredReset(100, CUSTOM_RESET_RPC);
  126. }
  127. }
  128. request->send(response);
  129. }
  130. // -----------------------------------------------------------------------------
  131. void apiRegister(const char * key, api_get_callback_f getFn, api_put_callback_f putFn) {
  132. // Store it
  133. web_api_t api;
  134. char buffer[40];
  135. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), key);
  136. api.key = strdup(key);
  137. api.getFn = getFn;
  138. api.putFn = putFn;
  139. _apis.push_back(api);
  140. // Bind call
  141. unsigned int methods = HTTP_GET;
  142. if (putFn != NULL) methods += HTTP_PUT;
  143. webServer()->on(buffer, methods, _bindAPI(_apis.size() - 1));
  144. }
  145. void apiSetup() {
  146. webServer()->on("/apis", HTTP_GET, _onAPIs);
  147. webServer()->on("/rpc", HTTP_GET, _onRPC);
  148. wsOnSendRegister(_apiWebSocketOnSend);
  149. wsOnReceiveRegister(_apiWebSocketOnReceive);
  150. }
  151. #endif // WEB_SUPPORT