Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ESP8266 Web server with Web Socket to control an LED. and SPIFFS filesytem
- youtube : v12345vtm
- */
- #include <ESP8266WiFi.h>
- #include <ESP8266WiFiMulti.h>
- #include <WebSocketsServer.h>
- #include <Hash.h>
- #include <ESP8266WebServer.h>
- #include <ESP8266mDNS.h>
- #include <FS.h> // Include the SPIFFS library
- String versie ="socketvith-ok-ESP12E-ledopD1metfotoSPIFFSelementbyID";
- String getContentType(String filename); // convert the file extension to the MIME type
- bool handleFileRead(String path); // send the right file to the client (if it exists)
- static const char ssid[] = "********";
- static const char password[] = "***************";
- MDNSResponder mdns;
- ESP8266WiFiMulti WiFiMulti;
- ESP8266WebServer server(80);
- WebSocketsServer webSocket = WebSocketsServer(81);
- static const char PROGMEM INDEX_HTML[] = R"rawliteral(
- <!DOCTYPE html>
- <html>
- <head>
- <meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
- <title>ESP8266 WebSocket Demo</title>
- <style>
- body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }
- </style>
- <script>
- var websock;
- function start() {
- websock = new WebSocket('ws://' + window.location.hostname + ':81/');
- websock.onopen = function(evt) { console.log('websock open'); };
- websock.onclose = function(evt) { console.log('websock close'); };
- websock.onerror = function(evt) { console.log(evt); };
- websock.onmessage = function(evt) {
- console.log(evt);
- var e = document.getElementById('ledA');
- var efoto = document.getElementById('ledAfoto');
- if (evt.data === 'ledon') {
- e.style.color = 'red';
- efoto.innerHTML = '<img src="light_1.png" />';
- }
- else if (evt.data === 'ledoff') {
- e.style.color = 'black';
- efoto.innerHTML = '<img src="light_0.png" />';
- }
- else {
- console.log('unknown event');
- efoto.innerHTML= '<img src="schema.jpg" />';
- }
- };
- }
- function buttonclick(e) {
- websock.send(e.id);
- }
- </script>
- </head>
- <body onload="javascript:start();">
- <h1>ESP8266 WebSocket ESP12-E Demo</h1>
- <h3>connect a led to ESP12-E : kathode on output D1 , anode to GND</h3>
- <div id="ledA"><b>ESP-D1-5</b></div>
- <div id="ledAfoto">jvascript zet hier foto</div>
- <button id="ledon" type="button" onclick="buttonclick(this);">On</button>
- <button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
- </br>
- </br>
- </br>
- <a href="schema.jpg" target="_blank">schema esp in filsysyem SPIFFS</a> </br>
- </br>
- <img src="schema.jpg" alt="SPIFFS foto schema" width="200" height="100">
- </body>
- </html>
- )rawliteral";
- const int LEDPIN = 5;
- // Current LED status
- // Commands sent through Web Socket
- const char LEDON[] = "ledon";//hier worden de button-id's van javascript opgevangen in de ESP-woordenlijst
- const char LEDOFF[] = "ledoff";
- void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
- {
- Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
- switch(type) {
- case WStype_DISCONNECTED:
- Serial.printf("[%u] Disconnected!\r\n", num);
- break;
- case WStype_CONNECTED:
- {
- IPAddress ip = webSocket.remoteIP(num);
- Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
- // Send the current LED status feedback van de esp opvragen
- Serial.printf("ledje is nu = >");
- Serial.print(String(digitalRead(5)));
- Serial.printf("< \n");
- if (digitalRead(5)==1) {
- webSocket.sendTXT(num, LEDON, strlen(LEDON));//hier vullen we payload nr de browser
- }
- else if (digitalRead(5)==0){
- webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
- }
- }
- break;
- case WStype_TEXT:
- Serial.printf("[%u] get Text: %s\r\n", num, payload);
- if (strcmp(LEDON, (const char *)payload) == 0) {
- // writeLED(true);//output sturen
- digitalWrite(LEDPIN, 1);
- }
- else if (strcmp(LEDOFF, (const char *)payload) == 0) {
- // writeLED(false);
- digitalWrite(LEDPIN, 0);
- }
- else {
- Serial.println("Unknown command");
- }
- // send data to all connected clients
- webSocket.broadcastTXT(payload, length);
- break;
- case WStype_BIN:
- Serial.printf("[%u] get binary length: %u\r\n", num, length);
- hexdump(payload, length);
- // echo data back to browser
- webSocket.sendBIN(num, payload, length);
- break;
- default:
- Serial.printf("Invalid WStype [%d]\r\n", type);
- break;
- }
- }
- void handleRoot()
- {
- server.send_P(200, "text/html", INDEX_HTML);
- }
- void handleNotFound()
- {
- }
- void setup()
- {
- pinMode(LEDPIN, OUTPUT);
- yield();
- //Onboard LED port Direction output
- pinMode(5, OUTPUT);//5 = LEd D1 op ESP12E
- Serial.begin(115200);
- SPIFFS.begin(); // Start the SPI Flash Files
- Serial.println();
- Serial.println();
- Serial.println();
- for(uint8_t t = 4; t > 0; t--) {
- Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
- Serial.println(versie);
- Serial.flush();
- yield();
- delay(1000);
- }
- Serial.println("SPIFFS server ok");
- bestandsysteem(); //toon in serialport alle SPIFFS in het bestandsysteem
- WiFiMulti.addAP(ssid, password);
- // add Wi-Fi networks you want to connect to
- while(WiFiMulti.run() != WL_CONNECTED) {
- Serial.print(".");
- delay(100);
- }
- Serial.println("");
- Serial.print("Connected to ");
- Serial.println(ssid);
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- if (mdns.begin("espWebSock", WiFi.localIP())) {
- Serial.println("MDNS responder started");
- mdns.addService("http", "tcp", 80);
- mdns.addService("ws", "tcp", 81);
- }
- else {
- Serial.println("MDNS.begin failed");
- }
- Serial.print("Connect to http://espWebSock.local or http://");
- Serial.println(WiFi.localIP());
- server.on("/", handleRoot);
- server.onNotFound([]() { // If the client requests any URI
- if (!handleFileRead(server.uri())) // send it if it exists
- // server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
- // String message = "File Not Found\n\n";
- server.send(404, "text/plain", "File Not Found\n\n");
- });
- //
- //
- server.begin();
- webSocket.begin();
- webSocket.onEvent(webSocketEvent);
- }
- void loop()
- {
- webSocket.loop();
- server.handleClient();
- }
- ////////
- String bestandsysteem()
- {
- /////check filesystem
- String filesysteem = "<ul>";
- Dir dir = SPIFFS.openDir("/");
- while (dir.next()) {
- filesysteem += "<li>";
- filesysteem += dir.fileName();
- filesysteem += " ";
- filesysteem += dir.fileSize();
- filesysteem += "kb</li>";
- }
- filesysteem += "<ul>";
- /////interne webpaginas
- filesysteem += "<ul>";
- filesysteem += "<li>/ INDEX_HTML[] =root harcoded</li>";
- // filesysteem += "<li>/ als lan device met ipadres en versie als melding</li>";
- filesysteem += "<li>/ als accespoint schakkelt spiffs , index.html in</li>";
- filesysteem += "<ul>";
- Serial.println("files SPIFFS :");
- Serial.println(filesysteem);
- return filesysteem;
- }
- ///einde check filesystem
- String getContentType(String filename) { // convert the file extension to the MIME type
- if (filename.endsWith(".html")) return "text/html";
- else if (filename.endsWith(".css")) return "text/css";
- else if (filename.endsWith(".js")) return "application/javascript";
- else if (filename.endsWith(".ico")) return "image/x-icon";
- else if (filename.endsWith(".png")) return "image/x-icon";
- else if (filename.endsWith(".jpg")) return "image/x-icon";
- return "text/plain";
- }
- bool handleFileRead(String path) { // send the right file to the client (if it exists)
- Serial.println("handleFileRead: " + path);
- if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
- String contentType = getContentType(path); // Get the MIME type
- if (SPIFFS.exists(path)) { // If the file exists
- File file = SPIFFS.open(path, "r"); // Open it
- size_t sent = server.streamFile(file, contentType); // And send it to the client
- file.close(); // Then close the file again
- return true;
- }
- Serial.println("\tFile Not Found");
- return false; // If the file doesn't exist, return false
- }
Advertisement
Add Comment
Please, Sign In to add comment