v12345vtm

socketesp-spiffs

May 6th, 2018
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.40 KB | None | 0 0
  1. /*
  2. ESP8266 Web server with Web Socket to control an LED. and SPIFFS filesytem
  3.  
  4. youtube : v12345vtm
  5.  
  6. */
  7.  
  8. #include <ESP8266WiFi.h>
  9. #include <ESP8266WiFiMulti.h>
  10. #include <WebSocketsServer.h>
  11. #include <Hash.h>
  12. #include <ESP8266WebServer.h>
  13. #include <ESP8266mDNS.h>
  14. #include <FS.h> // Include the SPIFFS library
  15.  
  16. String versie ="socketvith-ok-ESP12E-ledopD1metfotoSPIFFS";
  17.  
  18. String getContentType(String filename); // convert the file extension to the MIME type
  19. bool handleFileRead(String path); // send the right file to the client (if it exists)
  20.  
  21.  
  22. static const char ssid[] = "********";
  23. static const char password[] = "***************";
  24. MDNSResponder mdns;
  25.  
  26.  
  27. ESP8266WiFiMulti WiFiMulti;
  28.  
  29. ESP8266WebServer server(80);
  30. WebSocketsServer webSocket = WebSocketsServer(81);
  31.  
  32. static const char PROGMEM INDEX_HTML[] = R"rawliteral(
  33. <!DOCTYPE html>
  34. <html>
  35. <head>
  36. <meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
  37. <title>ESP8266 WebSocket Demo</title>
  38. <style>
  39. body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }
  40. </style>
  41. <script>
  42. var websock;
  43. function start() {
  44. websock = new WebSocket('ws://' + window.location.hostname + ':81/');
  45. websock.onopen = function(evt) { console.log('websock open'); };
  46. websock.onclose = function(evt) { console.log('websock close'); };
  47. websock.onerror = function(evt) { console.log(evt); };
  48. websock.onmessage = function(evt) {
  49. console.log(evt);
  50. var e = document.getElementById('ledA');
  51. if (evt.data === 'ledon') {
  52. e.style.color = 'red';
  53. }
  54. else if (evt.data === 'ledoff') {
  55. e.style.color = 'black';
  56. }
  57. else {
  58. console.log('unknown event');
  59. }
  60. };
  61. }
  62. function buttonclick(e) {
  63. websock.send(e.id);
  64. }
  65. </script>
  66. </head>
  67. <body onload="javascript:start();">
  68. <h1>ESP8266 WebSocket ESP12-E Demo</h1>
  69.  
  70. <h3>connect a led to ESP12-E : kathode on output D1 , anode to GND</h3>
  71. <div id="ledA"><b>ESP-D1-5</b></div>
  72.  
  73.  
  74. <button id="ledon" type="button" onclick="buttonclick(this);">On</button>
  75. <button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
  76.  
  77.  
  78. </br>
  79. </br>
  80. </br>
  81. <a href="schema.jpg" target="_blank">schema esp in filsysyem SPIFFS</a> </br>
  82. </br>
  83. <img src="schema.jpg" alt="SPIFFS foto schema" width="200" height="100">
  84.  
  85. </body>
  86. </html>
  87. )rawliteral";
  88.  
  89. const int LEDPIN = 5;
  90. // Current LED status
  91.  
  92.  
  93. // Commands sent through Web Socket
  94. const char LEDON[] = "ledon";//hier worden de button-id's van javascript opgevangen in de ESP-woordenlijst
  95. const char LEDOFF[] = "ledoff";
  96.  
  97.  
  98. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
  99. {
  100. Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
  101. switch(type) {
  102. case WStype_DISCONNECTED:
  103. Serial.printf("[%u] Disconnected!\r\n", num);
  104. break;
  105. case WStype_CONNECTED:
  106. {
  107. IPAddress ip = webSocket.remoteIP(num);
  108. Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
  109. // Send the current LED status feedback van de esp opvragen
  110.  
  111. Serial.printf("ledje is nu = >");
  112. Serial.print(String(digitalRead(5)));
  113. Serial.printf("< \n");
  114. if (digitalRead(5)==1) {
  115. webSocket.sendTXT(num, LEDON, strlen(LEDON));//hier vullen we payload nr de browser
  116. }
  117. else if (digitalRead(5)==0){
  118. webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
  119. }
  120.  
  121. }
  122. break;
  123.  
  124.  
  125.  
  126.  
  127. case WStype_TEXT:
  128. Serial.printf("[%u] get Text: %s\r\n", num, payload);
  129.  
  130.  
  131. if (strcmp(LEDON, (const char *)payload) == 0) {
  132. // writeLED(true);//output sturen
  133. digitalWrite(LEDPIN, 1);
  134. }
  135. else if (strcmp(LEDOFF, (const char *)payload) == 0) {
  136. // writeLED(false);
  137. digitalWrite(LEDPIN, 0);
  138. }
  139. else {
  140. Serial.println("Unknown command");
  141. }
  142.  
  143. // send data to all connected clients
  144. webSocket.broadcastTXT(payload, length);
  145. break;
  146. case WStype_BIN:
  147. Serial.printf("[%u] get binary length: %u\r\n", num, length);
  148. hexdump(payload, length);
  149.  
  150. // echo data back to browser
  151. webSocket.sendBIN(num, payload, length);
  152. break;
  153. default:
  154. Serial.printf("Invalid WStype [%d]\r\n", type);
  155. break;
  156. }
  157. }
  158.  
  159. void handleRoot()
  160. {
  161. server.send_P(200, "text/html", INDEX_HTML);
  162. }
  163.  
  164. void handleNotFound()
  165. {
  166.  
  167. }
  168.  
  169.  
  170.  
  171. void setup()
  172. {
  173. pinMode(LEDPIN, OUTPUT);
  174. yield();
  175.  
  176. //Onboard LED port Direction output
  177. pinMode(5, OUTPUT);//5 = LEd D1 op ESP12E
  178.  
  179. Serial.begin(115200);
  180.  
  181. SPIFFS.begin(); // Start the SPI Flash Files
  182.  
  183. Serial.println();
  184. Serial.println();
  185. Serial.println();
  186.  
  187. for(uint8_t t = 4; t > 0; t--) {
  188. Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
  189. Serial.println(versie);
  190. Serial.flush();
  191. yield();
  192. delay(1000);
  193. }
  194.  
  195. Serial.println("SPIFFS server ok");
  196.  
  197. bestandsysteem(); //toon in serialport alle SPIFFS in het bestandsysteem
  198.  
  199. WiFiMulti.addAP(ssid, password);
  200. // add Wi-Fi networks you want to connect to
  201.  
  202.  
  203. while(WiFiMulti.run() != WL_CONNECTED) {
  204. Serial.print(".");
  205. delay(100);
  206. }
  207.  
  208. Serial.println("");
  209. Serial.print("Connected to ");
  210. Serial.println(ssid);
  211. Serial.print("IP address: ");
  212. Serial.println(WiFi.localIP());
  213.  
  214. if (mdns.begin("espWebSock", WiFi.localIP())) {
  215. Serial.println("MDNS responder started");
  216. mdns.addService("http", "tcp", 80);
  217. mdns.addService("ws", "tcp", 81);
  218. }
  219. else {
  220. Serial.println("MDNS.begin failed");
  221. }
  222. Serial.print("Connect to http://espWebSock.local or http://");
  223. Serial.println(WiFi.localIP());
  224.  
  225. server.on("/", handleRoot);
  226.  
  227. server.onNotFound([]() { // If the client requests any URI
  228. if (!handleFileRead(server.uri())) // send it if it exists
  229. // server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  230. // String message = "File Not Found\n\n";
  231.  
  232. server.send(404, "text/plain", "File Not Found\n\n");
  233.  
  234. });
  235.  
  236.  
  237. //
  238.  
  239.  
  240. //
  241.  
  242. server.begin();
  243.  
  244. webSocket.begin();
  245. webSocket.onEvent(webSocketEvent);
  246. }
  247.  
  248. void loop()
  249. {
  250. webSocket.loop();
  251. server.handleClient();
  252. }
  253.  
  254.  
  255.  
  256.  
  257. ////////
  258. String bestandsysteem()
  259. {
  260. /////check filesystem
  261. String filesysteem = "<ul>";
  262. Dir dir = SPIFFS.openDir("/");
  263. while (dir.next()) {
  264. filesysteem += "<li>";
  265. filesysteem += dir.fileName();
  266. filesysteem += " ";
  267. filesysteem += dir.fileSize();
  268. filesysteem += "kb</li>";
  269. }
  270. filesysteem += "<ul>";
  271. /////interne webpaginas
  272. filesysteem += "<ul>";
  273. filesysteem += "<li>/ INDEX_HTML[] =root harcoded</li>";
  274.  
  275. // filesysteem += "<li>/ als lan device met ipadres en versie als melding</li>";
  276. filesysteem += "<li>/ als accespoint schakkelt spiffs , index.html in</li>";
  277. filesysteem += "<ul>";
  278. Serial.println("files SPIFFS :");
  279. Serial.println(filesysteem);
  280. return filesysteem;
  281. }
  282. ///einde check filesystem
  283.  
  284.  
  285.  
  286.  
  287.  
  288. String getContentType(String filename) { // convert the file extension to the MIME type
  289. if (filename.endsWith(".html")) return "text/html";
  290. else if (filename.endsWith(".css")) return "text/css";
  291. else if (filename.endsWith(".js")) return "application/javascript";
  292. else if (filename.endsWith(".ico")) return "image/x-icon";
  293. else if (filename.endsWith(".png")) return "image/x-icon";
  294. else if (filename.endsWith(".jpg")) return "image/x-icon";
  295. return "text/plain";
  296. }
  297.  
  298. bool handleFileRead(String path) { // send the right file to the client (if it exists)
  299. Serial.println("handleFileRead: " + path);
  300. if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
  301. String contentType = getContentType(path); // Get the MIME type
  302. if (SPIFFS.exists(path)) { // If the file exists
  303. File file = SPIFFS.open(path, "r"); // Open it
  304. size_t sent = server.streamFile(file, contentType); // And send it to the client
  305. file.close(); // Then close the file again
  306. return true;
  307. }
  308. Serial.println("\tFile Not Found");
  309. return false; // If the file doesn't exist, return false
  310. }
Advertisement
Add Comment
Please, Sign In to add comment