spiffs_rest_api.ino 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. #include <ESP8266WiFi.h>
  13. #include <ESP8266SSDP.h>
  14. //extension of ESP8266WebServer with SPIFFS handlers built in
  15. #include <SPIFFSReadServer.h> // https://github.com/r-downing/SPIFFSReadServer
  16. // upload data folder to chip with Arduino ESP8266 filesystem uploader
  17. // https://github.com/esp8266/arduino-esp8266fs-plugin
  18. #include <DNSServer.h>
  19. #include <FS.h>
  20. #define DEVICE_NAME "ESP8266 DEVICE"
  21. //server objects
  22. SPIFFSReadServer server(80);
  23. DNSServer dnsServer;
  24. PersWiFiManager persWM(server, dnsServer);
  25. ////// Sample program data
  26. int x;
  27. String y;
  28. void setup() {
  29. DEBUG_BEGIN; //for terminal debugging
  30. DEBUG_PRINT();
  31. //allows serving of files from SPIFFS
  32. SPIFFS.begin();
  33. //sets network name for AP mode
  34. persWM.setApCredentials(DEVICE_NAME);
  35. //persWM.setApCredentials(DEVICE_NAME, "password"); optional password
  36. persWM.begin();
  37. //handles commands from webpage, sends live data in JSON format
  38. server.on("/api", []() {
  39. DEBUG_PRINT("server.on /api");
  40. if (server.hasArg("x")) {
  41. x = server.arg("x").toInt();
  42. DEBUG_PRINT(String("x: ")+x);
  43. } //if
  44. if (server.hasArg("y")) {
  45. y = server.arg("y");
  46. DEBUG_PRINT("y: "+y);
  47. } //if
  48. //build json object of program data
  49. StaticJsonBuffer<200> jsonBuffer;
  50. JsonObject &json = jsonBuffer.createObject();
  51. json["x"] = x;
  52. json["y"] = y;
  53. char jsonchar[200];
  54. json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
  55. server.send(200, "application/json", jsonchar);
  56. }); //server.on api
  57. //SSDP makes device visible on windows network
  58. server.on("/description.xml", HTTP_GET, []() {
  59. SSDP.schema(server.client());
  60. });
  61. SSDP.setSchemaURL("description.xml");
  62. SSDP.setHTTPPort(80);
  63. SSDP.setName(DEVICE_NAME);
  64. SSDP.setURL("/");
  65. SSDP.begin();
  66. SSDP.setDeviceType("upnp:rootdevice");
  67. server.begin();
  68. DEBUG_PRINT("setup complete.");
  69. } //void setup
  70. void loop() {
  71. dnsServer.processNextRequest();
  72. server.handleClient();
  73. // do stuff with x and y
  74. } //void loop