v12345vtm

esp-websocket-image

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