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.

197 lines
5.4 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. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  81. request->send(200, "application/json", buffer);
  82. } else {
  83. request->send(200, "text/plain", value);
  84. }
  85. };
  86. }
  87. void _onAPIs(AsyncWebServerRequest *request) {
  88. webLog(request);
  89. if (!_authAPI(request)) return;
  90. bool asJson = _asJson(request);
  91. char buffer[40];
  92. String output;
  93. if (asJson) {
  94. DynamicJsonBuffer jsonBuffer;
  95. JsonObject& root = jsonBuffer.createObject();
  96. for (unsigned int i=0; i < _apis.size(); i++) {
  97. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), _apis[i].key);
  98. root[_apis[i].key] = String(buffer);
  99. }
  100. root.printTo(output);
  101. request->send(200, "application/json", output);
  102. } else {
  103. for (unsigned int i=0; i < _apis.size(); i++) {
  104. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), _apis[i].key);
  105. output += _apis[i].key + String(" -> ") + String(buffer) + String("\n");
  106. }
  107. request->send(200, "text/plain", output);
  108. }
  109. }
  110. void _onRPC(AsyncWebServerRequest *request) {
  111. webLog(request);
  112. if (!_authAPI(request)) return;
  113. //bool asJson = _asJson(request);
  114. int response = 404;
  115. if (request->hasParam("action")) {
  116. AsyncWebParameter* p = request->getParam("action");
  117. String action = p->value();
  118. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  119. if (action.equals("reboot")) {
  120. response = 200;
  121. deferredReset(100, CUSTOM_RESET_RPC);
  122. }
  123. }
  124. request->send(response);
  125. }
  126. // -----------------------------------------------------------------------------
  127. void apiRegister(const char * key, api_get_callback_f getFn, api_put_callback_f putFn) {
  128. // Store it
  129. web_api_t api;
  130. char buffer[40];
  131. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), key);
  132. api.key = strdup(key);
  133. api.getFn = getFn;
  134. api.putFn = putFn;
  135. _apis.push_back(api);
  136. // Bind call
  137. unsigned int methods = HTTP_GET;
  138. if (putFn != NULL) methods += HTTP_PUT;
  139. webServer()->on(buffer, methods, _bindAPI(_apis.size() - 1));
  140. }
  141. void apiSetup() {
  142. webServer()->on("/apis", HTTP_GET, _onAPIs);
  143. webServer()->on("/rpc", HTTP_GET, _onRPC);
  144. wsOnSendRegister(_apiWebSocketOnSend);
  145. wsOnReceiveRegister(_apiWebSocketOnReceive);
  146. }
  147. #endif // WEB_SUPPORT