basic_rest_api.ino 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #define DEBUG_SERIAL //uncomment for Serial debugging statements
  2. #ifdef DEBUG_SERIAL
  3. #define DEBUG_BEGIN Serial.begin(115200)
  4. #define DEBUG_PRINT(x) Serial.println(x)
  5. #else
  6. #define DEBUG_PRINT(x)
  7. #define DEBUG_BEGIN
  8. #endif
  9. //includes
  10. #include <PersWiFiManager.h>
  11. #include <ArduinoJson.h>
  12. #if defined(ESP8266)
  13. #include <ESP8266WiFi.h>
  14. #include <ESP8266SSDP.h>
  15. #include <ESP8266WebServer.h>
  16. #include <FS.h>
  17. #elif defined(ESP32)
  18. #include <WiFi.h>
  19. #include <ESP32SSDP.h>
  20. #include <WebServer.h>
  21. #include <SPIFFS.h>
  22. #else
  23. #error "Unsupported board class"
  24. #endif
  25. #include <DNSServer.h>
  26. #if defined(ESP8266)
  27. #define DEVICE_NAME "ESP8266 DEVICE"
  28. #elif defined(ESP32)
  29. #define DEVICE_NAME "ESP32 DEVICE"
  30. #endif
  31. //const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"1; url=/\" /></head><body><a href=\"/\">redirecting...</a></body>";
  32. const char *metaRefreshStr = "<script>window.location='/'</script><a href='/'>redirecting...</a>";
  33. //server objects
  34. #if defined(ESP8266)
  35. ESP8266WebServer server(80);
  36. #elif defined(ESP32)
  37. WebServer server(80);
  38. #endif
  39. DNSServer dnsServer;
  40. PersWiFiManager persWM(server, dnsServer);
  41. ////// Sample program data
  42. int x;
  43. String y;
  44. //code from fsbrowser example, consolidated.
  45. bool handleFileRead(String path) {
  46. DEBUG_PRINT("handlefileread" + path);
  47. if (path.endsWith("/")) path += "index.htm";
  48. String contentType;
  49. if (path.endsWith(".htm") || path.endsWith(".html")) contentType = "text/html";
  50. else if (path.endsWith(".css")) contentType = "text/css";
  51. else if (path.endsWith(".js")) contentType = "application/javascript";
  52. else if (path.endsWith(".png")) contentType = "image/png";
  53. else if (path.endsWith(".gif")) contentType = "image/gif";
  54. else if (path.endsWith(".jpg")) contentType = "image/jpeg";
  55. else if (path.endsWith(".ico")) contentType = "image/x-icon";
  56. else if (path.endsWith(".xml")) contentType = "text/xml";
  57. else if (path.endsWith(".pdf")) contentType = "application/x-pdf";
  58. else if (path.endsWith(".zip")) contentType = "application/x-zip";
  59. else if (path.endsWith(".gz")) contentType = "application/x-gzip";
  60. else if (path.endsWith(".json")) contentType = "application/json";
  61. else contentType = "text/plain";
  62. //split filepath and extension
  63. String prefix = path, ext = "";
  64. int lastPeriod = path.lastIndexOf('.');
  65. if (lastPeriod >= 0) {
  66. prefix = path.substring(0, lastPeriod);
  67. ext = path.substring(lastPeriod);
  68. }
  69. //look for smaller versions of file
  70. //minified file, good (myscript.min.js)
  71. if (SPIFFS.exists(prefix + ".min" + ext)) path = prefix + ".min" + ext;
  72. //gzipped file, better (myscript.js.gz)
  73. if (SPIFFS.exists(prefix + ext + ".gz")) path = prefix + ext + ".gz";
  74. //min and gzipped file, best (myscript.min.js.gz)
  75. if (SPIFFS.exists(prefix + ".min" + ext + ".gz")) path = prefix + ".min" + ext + ".gz";
  76. if (SPIFFS.exists(path)) {
  77. DEBUG_PRINT("sending file " + path);
  78. File file = SPIFFS.open(path, "r");
  79. if (server.hasArg("download"))
  80. server.sendHeader("Content-Disposition", " attachment;");
  81. if (server.uri().indexOf("nocache") < 0)
  82. server.sendHeader("Cache-Control", " max-age=172800");
  83. //optional alt arg (encoded url), server sends redirect to file on the web
  84. if (WiFi.status() == WL_CONNECTED && server.hasArg("alt")) {
  85. server.sendHeader("Location", server.arg("alt"), true);
  86. server.send ( 302, "text/plain", "");
  87. } else {
  88. //server sends file
  89. size_t sent = server.streamFile(file, contentType);
  90. }
  91. file.close();
  92. return true;
  93. } //if SPIFFS.exists
  94. return false;
  95. } //bool handleFileRead
  96. void setup() {
  97. DEBUG_BEGIN; //for terminal debugging
  98. DEBUG_PRINT();
  99. //allows serving of files from SPIFFS
  100. SPIFFS.begin();
  101. persWM.begin();
  102. //reset saved settings, clears WiFi credentials e.g. for testing
  103. //persWM.resetSettings();
  104. //serve files from SPIFFS
  105. server.onNotFound([]() {
  106. if (!handleFileRead(server.uri())) {
  107. server.sendHeader("Cache-Control", " max-age=172800");
  108. server.send(302, "text/html", metaRefreshStr);
  109. }
  110. }); //server.onNotFound
  111. //handles commands from webpage, sends live data in JSON format
  112. server.on("/api", []() {
  113. DEBUG_PRINT("server.on /api");
  114. if (server.hasArg("x")) {
  115. x = server.arg("x").toInt();
  116. DEBUG_PRINT(String("x: ")+x);
  117. } //if
  118. if (server.hasArg("y")) {
  119. y = server.arg("y");
  120. DEBUG_PRINT("y: "+y);
  121. } //if
  122. //build json object of program data
  123. StaticJsonBuffer<200> jsonBuffer;
  124. JsonObject &json = jsonBuffer.createObject();
  125. json["x"] = x;
  126. json["y"] = y;
  127. char jsonchar[200];
  128. json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
  129. server.send(200, "application/json", jsonchar);
  130. }); //server.on api
  131. //SSDP makes device visible on windows network
  132. server.on("/description.xml", HTTP_GET, []() {
  133. SSDP.schema(server.client());
  134. });
  135. SSDP.setSchemaURL("description.xml");
  136. SSDP.setHTTPPort(80);
  137. SSDP.setName(DEVICE_NAME);
  138. SSDP.setURL("/");
  139. SSDP.setDeviceType("upnp:rootdevice");
  140. SSDP.begin();
  141. server.begin();
  142. DEBUG_PRINT("setup complete.");
  143. } //void setup
  144. void loop() {
  145. dnsServer.processNextRequest();
  146. server.handleClient();
  147. // do stuff with x and y
  148. } //void loop