v12345vtm

socketvith-ok-ESP12E-ledopD1metfotoSPIFFS-pulse

May 7th, 2018
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.16 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-pulse";
  17. String lanssid = "WiFi";
  18. String lanpassphrase = "pass";
  19.  
  20. //int LEDPIN = 0; //1 is de ingebouwde blauwe led op de esp-01 //2 is pin2 //0 is pin1
  21. //output pinout on ESP12E
  22.  
  23. #define D0 16 //input flash via knop
  24. #define D1 5
  25. #define D2 4
  26. #define D3 0
  27. #define D4 2
  28. #define D5 14
  29. #define D6 12
  30. #define D7 13
  31. #define D8 15
  32. #define D9 3 //RX
  33. #define D10 1 //TX
  34.  
  35. unsigned long previousMillis = 0;
  36.  
  37. bool pulsebitd1 = false ; //test om na interval een uitgang op 0 te zetten
  38.  
  39. String getContentType(String filename); // convert the file extension to the MIME type
  40. bool handleFileRead(String path); // send the right file to the client (if it exists)
  41.  
  42.  
  43.  
  44. MDNSResponder mdns;
  45.  
  46.  
  47. ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
  48.  
  49.  
  50.  
  51. ESP8266WebServer server(80);
  52. WebSocketsServer webSocket = WebSocketsServer(81);
  53.  
  54.  
  55.  
  56.  
  57. static const char PROGMEM INDEX_HTML[] = R"rawliteral(
  58. <!DOCTYPE html>
  59. <html>
  60. <head>
  61. <meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
  62. <title>v12345vtm ESP8266</title>
  63. <style>
  64. body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }
  65. </style>
  66. <script>
  67. var websock;
  68. function start() {
  69. websock = new WebSocket('ws://' + window.location.hostname + ':81/');
  70. websock.onopen = function(evt) { console.log('websock open'); };
  71. websock.onclose = function(evt) { console.log('websock close'); };
  72. websock.onerror = function(evt) { console.log(evt); };
  73. websock.onmessage = function(evt) {
  74. console.log(evt);
  75. var e = document.getElementById('ledA');
  76. var efoto = document.getElementById('ledAfoto');
  77.  
  78. if (evt.data === 'ledon') {
  79. e.style.color = 'red';
  80. efoto.innerHTML = '<img src="img/light_1.png" />';
  81. }
  82. else if (evt.data === 'ledoff') {
  83. e.style.color = 'black';
  84. efoto.innerHTML = '<img src="img/light_0.png" />';
  85. }
  86. else {
  87. console.log('unknown event');
  88. efoto.innerHTML= '<img src="img/werk.png" />';
  89. }
  90. };
  91. }
  92.  
  93. function myPulserelaisFunction(tegenactie) {
  94. function saysomething(){
  95. // alert(tegenactie);
  96. websock.send(tegenactie);
  97. }
  98. setTimeout(function() { saysomething() }, 3000);
  99. }
  100.  
  101.  
  102.  
  103.  
  104. function buttonclick(e) {
  105. ////filtern PULSE commando
  106. // alert(e.id);//debug javascript en toont de buttonid : voorbeeld "ledon"
  107. // var knopid = e.id ; //"ledonPulse";
  108. // var jaIsmetPulse = knopid.endsWith("Pulse"); //var n is true als er pulse in id staat
  109. if (e.id.endsWith("Pulse")) {
  110. // alert("ja teller starten");
  111. var knopidkort = e.id.replace("Pulse", "");//niet zomaar veranderen voor 2e keer
  112. // alert(e.id); //debug
  113. websock.send(knopidkort);
  114. myPulserelaisFunction("ledoff"); //start de klok en geef mee wat er moet gebeuren
  115. }
  116.  
  117. // alert("done");
  118. /////einde filteren PULSE commando
  119. else
  120. {
  121. websock.send(e.id);
  122. }
  123.  
  124. }
  125. </script>
  126. </head>
  127. <body onload="javascript:start();">
  128. <h1>ESP8266 WebSocket ESP12-E PULSE Demo for garage door</h1>
  129.  
  130. <h3>connect a led to ESP12-E : kathode on output D1 , anode to GND</h3>
  131. <div id="ledA"><b>ESP-D1-5</b></div>
  132. <div id="ledAfoto">jvascript zet hier foto</div>
  133.  
  134.  
  135. <button id="ledon" type="button" onclick="buttonclick(this);">On</button>
  136. <button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
  137. <button id="ledonPulse" type="button" onclick="buttonclick(this);">Onpuls timed via javascript</button>
  138.  
  139.  
  140. </br>
  141. <button id="esppuls" type="button" onclick="buttonclick(this);">Timer via ESP millies()</button>
  142. </br>
  143. <a href="img/schema.jpg" target="_blank">schema esp in filsysyem SPIFFS</a> </br>
  144. </br>
  145. <img src="img/schema.jpg" alt="SPIFFS foto schema" width="200" height="100">
  146.  
  147. </br>
  148.  
  149. ESP8266 WebSocket Demo Relais Puls gestuurd monoflop</br>
  150. </body>
  151. </html>
  152. )rawliteral";
  153.  
  154. //const int D1 = 5;
  155. // Current LED status
  156.  
  157.  
  158. // lijst van argumenten die de browser ons zal aanleveren , sent through Web Socket
  159. const char LEDON[] = "ledon";//hier worden de button-id's van javascript opgelijst in de ESP-woordenlijst
  160. const char LEDOFF[] = "ledoff";
  161. const char ESPPULS[] = "esppuls";//trigger timer op esp via de browser
  162.  
  163.  
  164.  
  165.  
  166.  
  167.  
  168.  
  169.  
  170.  
  171. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
  172. {
  173. Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
  174. switch(type) {
  175. case WStype_DISCONNECTED:
  176. Serial.printf("[%u] Disconnected!\r\n", num);
  177. break;
  178. case WStype_CONNECTED:
  179. {
  180. IPAddress ip = webSocket.remoteIP(num);
  181. Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
  182. // resultaat op de compoort = [0] Connected from 192.168.1.27 url: /
  183.  
  184.  
  185. // Send the current LED status feedback van de esp opvragen
  186.  
  187. Serial.printf("ledje is nu = >");
  188. Serial.print(String(digitalRead(D1)));
  189. Serial.printf("< \n");
  190. if (digitalRead(D1)==1) {
  191. webSocket.sendTXT(num, LEDON, strlen(LEDON));//hier vullen we payload nr de browser , namelijk
  192. }
  193. else if (digitalRead(D1)==0){
  194. webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
  195. }
  196. }
  197. break;
  198.  
  199.  
  200. case WStype_TEXT:
  201. Serial.printf("[%u] get Text: %s\r\n", num, payload); // [0] get Text: ledoff
  202.  
  203. //als de payload van de browser gelijk is iets dat we kennen
  204. if (strcmp(ESPPULS, (const char *)payload) == 0) {
  205. //als string "ledon" gelijk is met de payload "ledon" dan de output sturen
  206. pulsebitd1= true;//test pulse op d1
  207. }
  208. else
  209.  
  210.  
  211.  
  212. if (strcmp(LEDON, (const char *)payload) == 0) {
  213. //als string "ledon" gelijk is met de payload "ledon" dan de output sturen
  214. digitalWrite(D1, 1);
  215. }
  216. else if (strcmp(LEDOFF, (const char *)payload) == 0) {
  217. // writeLED(false);
  218. digitalWrite(D1, 0);
  219.  
  220. }
  221. else {
  222. Serial.print("browser stuur payload die we niet geleerd hebben: " );
  223. Serial.printf("%s", payload);
  224.  
  225. }
  226.  
  227. // send data to all connected clients
  228. webSocket.broadcastTXT(payload, length);
  229. break;
  230. case WStype_BIN:
  231. Serial.printf("[%u] get binary length: %u\r\n", num, length);
  232. hexdump(payload, length);
  233.  
  234. // echo data back to browser
  235. webSocket.sendBIN(num, payload, length);
  236. break;
  237. default:
  238. Serial.printf("Invalid WStype [%d]\r\n", type);
  239. break;
  240. }
  241. }
  242.  
  243. void handleRoot()
  244. {
  245. server.send_P(200, "text/html", INDEX_HTML);
  246. }
  247.  
  248. void handleNotFound()
  249. {
  250.  
  251. }
  252.  
  253.  
  254.  
  255. void setup()
  256. {
  257. previousMillis = millis(); //prevois millies mag niet null zijn,anders zal de browser button de 1e keer niet werken
  258.  
  259. yield();
  260.  
  261. //Onboard LED port Direction output
  262. // pinMode(D0 , INPUT);//5 = LEd D1 op ESP12E
  263. pinMode(D1, OUTPUT);//5 = LEd D1 op ESP12E
  264. pinMode(D2, OUTPUT);//5 = LEd D1 op ESP12E
  265. pinMode(D3, OUTPUT);//5 = LEd D1 op ESP12E
  266. pinMode(D4, OUTPUT);//5 = LEd D1 op ESP12E
  267. pinMode(D5, OUTPUT);//14op ESP12E
  268. pinMode(D6, OUTPUT);//5 = LEd D1 op ESP12E
  269. pinMode(D7, OUTPUT);//5 = LEd D1 op ESP12E
  270. pinMode(D8, OUTPUT);//5 = LEd D1 op ESP12E
  271.  
  272. Serial.begin(115200);
  273. SPIFFS.begin(); // Start the SPI Flash Files
  274.  
  275. for(uint8_t t = 4; t > 0; t--) {
  276. Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
  277. Serial.println(versie);
  278. Serial.flush();
  279. yield();
  280. delay(1000);
  281. }
  282. Serial.println("SPIFFS server ok");
  283. bestandsysteem() ; //toon in serialport alle SPIFFS in het bestandsysteem
  284.  
  285. char ssidchar[lanssid.length()+1];
  286. lanssid.toCharArray(ssidchar, lanssid.length()+1);
  287. char lanpassphrasechar[lanpassphrase.length()+1];
  288. lanpassphrase.toCharArray(lanpassphrasechar, lanpassphrase.length()+1);
  289.  
  290. Serial.println(ssidchar);
  291. Serial.println(lanpassphrasechar);
  292.  
  293. wifiMulti.addAP(ssidchar, lanpassphrasechar); // add Wi-Fi networks you want to connect to
  294.  
  295. while(wifiMulti.run() != WL_CONNECTED) {
  296. Serial.print(".");
  297. delay(100);
  298. }
  299.  
  300. Serial.print("IP address: ");
  301. Serial.println(WiFi.localIP());
  302.  
  303. if (mdns.begin("esp8266", WiFi.localIP())) {
  304. Serial.println("MDNS started- Connect IOS esp8266.local");
  305. mdns.addService("http", "tcp", 80);
  306. mdns.addService("ws", "tcp", 81);
  307. }
  308. else {
  309. Serial.println("MDNS.begin failed");
  310. }
  311.  
  312. server.on("/", handleRoot);
  313.  
  314. server.onNotFound([]() { // If the client requests any URI
  315. if (!handleFileRead(server.uri())) // send it if it exists
  316. // server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  317. // String message = "File Not Found\n\n";
  318. server.send(404, "text/plain", "File Not Found\n\n");
  319. });
  320.  
  321. server.begin();
  322.  
  323. webSocket.begin();
  324. webSocket.onEvent(webSocketEvent);
  325.  
  326.  
  327. }
  328.  
  329. void loop()
  330. {
  331. webSocket.loop();
  332. server.handleClient();
  333. unsigned long currentMillis = millis();
  334. // previousMillis = millis();
  335. ///////////////*************
  336.  
  337. ///////////////////////////////////
  338. if (pulsebitd1 == true) {
  339. // previousMillis = millis();
  340. Serial.print ("esp timer");
  341. digitalWrite(D5, HIGH);
  342. Serial.print ((currentMillis - previousMillis)/1000);
  343. Serial.println ("sec");
  344. if(currentMillis - previousMillis >= 3000) {
  345. digitalWrite(D5, LOW);
  346. pulsebitd1 = false;//reset
  347. }
  348. }
  349. else{
  350. // we moeten zorgen dat de vorige tijdmerker niet te ver in het verleden ligt
  351. // Serial.println("verleden verdichten");
  352. previousMillis = currentMillis;
  353.  
  354. }
  355.  
  356. ///////////////**********
  357. }
  358.  
  359.  
  360.  
  361.  
  362.  
  363.  
  364. String getContentType(String filename) { // convert the file extension to the MIME type
  365. if (filename.endsWith(".html")) return "text/html";
  366. else if (filename.endsWith(".css")) return "text/css";
  367. else if (filename.endsWith(".js")) return "application/javascript";
  368. else if (filename.endsWith(".ico")) return "image/x-icon";
  369. else if (filename.endsWith(".png")) return "image/x-icon";
  370. else if (filename.endsWith(".jpg")) return "image/x-icon";
  371. return "text/plain";
  372. }
  373.  
  374. bool handleFileRead(String path) { // send the right file to the client (if it exists)
  375. Serial.println("handleFileRead: " + path);
  376. if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
  377. String contentType = getContentType(path); // Get the MIME type
  378. if (SPIFFS.exists(path)) { // If the file exists
  379. File file = SPIFFS.open(path, "r"); // Open it
  380. size_t sent = server.streamFile(file, contentType); // And send it to the client
  381. file.close(); // Then close the file again
  382. return true;
  383. }
  384. Serial.println("\tFile Not Found");
  385. return false; // If the file doesn't exist, return false
  386. }
  387.  
  388.  
  389.  
  390. //////////
  391. /////
  392. String bestandsysteem()
  393. {
  394. /////check filesystem
  395. String filesysteem = "<ul>";
  396. Dir dir = SPIFFS.openDir("/");
  397. while (dir.next()) {
  398. filesysteem += "<li>";
  399. filesysteem += dir.fileName();
  400. filesysteem += " ";
  401. filesysteem += dir.fileSize();
  402. filesysteem += "kb</li>";
  403. }
  404. filesysteem += "<ul>";
  405. /////interne webpaginas
  406. filesysteem += "<ul>";
  407. filesysteem += "<li>/wifiscan</li>";
  408. filesysteem += "<li>/test</li>";
  409. filesysteem += "<li>/cleareeprom</li>";
  410. filesysteem += "<li>/setting</li>";
  411. filesysteem += "<li>/test2</li>";
  412. // filesysteem += "<li>/ als lan device met ipadres en versie als melding</li>";
  413. filesysteem += "<li>/ als accespoint schakkelt spiffs , index.html in</li>";
  414. filesysteem += "<ul>";
  415. Serial.println(filesysteem);
  416. return filesysteem;
  417. }
  418. ///einde check filesystem
Advertisement
Add Comment
Please, Sign In to add comment