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-ledopD1metfotoSPIFFS-pulse";
- String lanssid = "WiFi";
- String lanpassphrase = "pass";
- //int LEDPIN = 0; //1 is de ingebouwde blauwe led op de esp-01 //2 is pin2 //0 is pin1
- //output pinout on ESP12E
- #define D0 16 //input flash via knop
- #define D1 5
- #define D2 4
- #define D3 0
- #define D4 2
- #define D5 14
- #define D6 12
- #define D7 13
- #define D8 15
- #define D9 3 //RX
- #define D10 1 //TX
- unsigned long previousMillis = 0;
- bool pulsebitd1 = false ; //test om na interval een uitgang op 0 te zetten
- 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)
- MDNSResponder mdns;
- ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called '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>v12345vtm ESP8266</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="img/light_1.png" />';
- }
- else if (evt.data === 'ledoff') {
- e.style.color = 'black';
- efoto.innerHTML = '<img src="img/light_0.png" />';
- }
- else {
- console.log('unknown event');
- efoto.innerHTML= '<img src="img/werk.png" />';
- }
- };
- }
- function myPulserelaisFunction(tegenactie) {
- function saysomething(){
- // alert(tegenactie);
- websock.send(tegenactie);
- }
- setTimeout(function() { saysomething() }, 3000);
- }
- function buttonclick(e) {
- ////filtern PULSE commando
- // alert(e.id);//debug javascript en toont de buttonid : voorbeeld "ledon"
- // var knopid = e.id ; //"ledonPulse";
- // var jaIsmetPulse = knopid.endsWith("Pulse"); //var n is true als er pulse in id staat
- if (e.id.endsWith("Pulse")) {
- // alert("ja teller starten");
- var knopidkort = e.id.replace("Pulse", "");//niet zomaar veranderen voor 2e keer
- // alert(e.id); //debug
- websock.send(knopidkort);
- myPulserelaisFunction("ledoff"); //start de klok en geef mee wat er moet gebeuren
- }
- // alert("done");
- /////einde filteren PULSE commando
- else
- {
- websock.send(e.id);
- }
- }
- </script>
- </head>
- <body onload="javascript:start();">
- <h1>ESP8266 WebSocket ESP12-E PULSE Demo for garage door</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>
- <button id="ledonPulse" type="button" onclick="buttonclick(this);">Onpuls timed via javascript</button>
- </br>
- <button id="esppuls" type="button" onclick="buttonclick(this);">Timer via ESP millies()</button>
- </br>
- <a href="img/schema.jpg" target="_blank">schema esp in filsysyem SPIFFS</a> </br>
- </br>
- <img src="img/schema.jpg" alt="SPIFFS foto schema" width="200" height="100">
- </br>
- ESP8266 WebSocket Demo Relais Puls gestuurd monoflop</br>
- </body>
- </html>
- )rawliteral";
- //const int D1 = 5;
- // Current LED status
- // lijst van argumenten die de browser ons zal aanleveren , sent through Web Socket
- const char LEDON[] = "ledon";//hier worden de button-id's van javascript opgelijst in de ESP-woordenlijst
- const char LEDOFF[] = "ledoff";
- const char ESPPULS[] = "esppuls";//trigger timer op esp via de browser
- 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);
- // resultaat op de compoort = [0] Connected from 192.168.1.27 url: /
- // Send the current LED status feedback van de esp opvragen
- Serial.printf("ledje is nu = >");
- Serial.print(String(digitalRead(D1)));
- Serial.printf("< \n");
- if (digitalRead(D1)==1) {
- webSocket.sendTXT(num, LEDON, strlen(LEDON));//hier vullen we payload nr de browser , namelijk
- }
- else if (digitalRead(D1)==0){
- webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
- }
- }
- break;
- case WStype_TEXT:
- Serial.printf("[%u] get Text: %s\r\n", num, payload); // [0] get Text: ledoff
- //als de payload van de browser gelijk is iets dat we kennen
- if (strcmp(ESPPULS, (const char *)payload) == 0) {
- //als string "ledon" gelijk is met de payload "ledon" dan de output sturen
- pulsebitd1= true;//test pulse op d1
- }
- else
- if (strcmp(LEDON, (const char *)payload) == 0) {
- //als string "ledon" gelijk is met de payload "ledon" dan de output sturen
- digitalWrite(D1, 1);
- }
- else if (strcmp(LEDOFF, (const char *)payload) == 0) {
- // writeLED(false);
- digitalWrite(D1, 0);
- }
- else {
- Serial.print("browser stuur payload die we niet geleerd hebben: " );
- Serial.printf("%s", payload);
- }
- // 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()
- {
- previousMillis = millis(); //prevois millies mag niet null zijn,anders zal de browser button de 1e keer niet werken
- yield();
- //Onboard LED port Direction output
- // pinMode(D0 , INPUT);//5 = LEd D1 op ESP12E
- pinMode(D1, OUTPUT);//5 = LEd D1 op ESP12E
- pinMode(D2, OUTPUT);//5 = LEd D1 op ESP12E
- pinMode(D3, OUTPUT);//5 = LEd D1 op ESP12E
- pinMode(D4, OUTPUT);//5 = LEd D1 op ESP12E
- pinMode(D5, OUTPUT);//14op ESP12E
- pinMode(D6, OUTPUT);//5 = LEd D1 op ESP12E
- pinMode(D7, OUTPUT);//5 = LEd D1 op ESP12E
- pinMode(D8, OUTPUT);//5 = LEd D1 op ESP12E
- Serial.begin(115200);
- SPIFFS.begin(); // Start the SPI Flash Files
- 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
- char ssidchar[lanssid.length()+1];
- lanssid.toCharArray(ssidchar, lanssid.length()+1);
- char lanpassphrasechar[lanpassphrase.length()+1];
- lanpassphrase.toCharArray(lanpassphrasechar, lanpassphrase.length()+1);
- Serial.println(ssidchar);
- Serial.println(lanpassphrasechar);
- wifiMulti.addAP(ssidchar, lanpassphrasechar); // add Wi-Fi networks you want to connect to
- while(wifiMulti.run() != WL_CONNECTED) {
- Serial.print(".");
- delay(100);
- }
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- if (mdns.begin("esp8266", WiFi.localIP())) {
- Serial.println("MDNS started- Connect IOS esp8266.local");
- mdns.addService("http", "tcp", 80);
- mdns.addService("ws", "tcp", 81);
- }
- else {
- Serial.println("MDNS.begin failed");
- }
- 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();
- unsigned long currentMillis = millis();
- // previousMillis = millis();
- ///////////////*************
- ///////////////////////////////////
- if (pulsebitd1 == true) {
- // previousMillis = millis();
- Serial.print ("esp timer");
- digitalWrite(D5, HIGH);
- Serial.print ((currentMillis - previousMillis)/1000);
- Serial.println ("sec");
- if(currentMillis - previousMillis >= 3000) {
- digitalWrite(D5, LOW);
- pulsebitd1 = false;//reset
- }
- }
- else{
- // we moeten zorgen dat de vorige tijdmerker niet te ver in het verleden ligt
- // Serial.println("verleden verdichten");
- previousMillis = currentMillis;
- }
- ///////////////**********
- }
- 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
- }
- //////////
- /////
- 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>/wifiscan</li>";
- filesysteem += "<li>/test</li>";
- filesysteem += "<li>/cleareeprom</li>";
- filesysteem += "<li>/setting</li>";
- filesysteem += "<li>/test2</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(filesysteem);
- return filesysteem;
- }
- ///einde check filesystem
Advertisement
Add Comment
Please, Sign In to add comment