v12345vtm

peha-inputsimulatie7.ino

May 10th, 2018
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.98 KB | None | 0 0
  1. /*
  2. https://www.youtube.com/watch?v=aX6vp91kF9I youtube=v12345vtm
  3.  
  4.  
  5. basic concept of telnet session to peha domotics stm module
  6. send a XML request or a http request and print out the respons to peha STM
  7.  
  8. skectch for simulating peha inputs on esp12e
  9.  
  10. todo accespoit to setup peha ip ...wifi...
  11.  
  12. */
  13.  
  14. #define D0 16 //input flash via knop
  15. #define D1 5
  16. #define D2 4
  17. #define D3 0
  18. #define D4 2
  19. #define D5 14
  20. #define D6 12
  21. #define D7 13
  22. #define D8 15
  23. #define D9 3 //RX
  24. #define D10 1 //TX
  25.  
  26.  
  27. #include <ESP8266WiFi.h>
  28. #include <ESP8266WiFiMulti.h>
  29. #include <WebSocketsServer.h>
  30. #include <Hash.h>
  31. #include <ESP8266WebServer.h>
  32. #include <ESP8266mDNS.h>
  33. #include <FS.h> // Include the SPIFFS library
  34.  
  35. String versie = "peha-inputsimulatie7 -accespoint";
  36. String lanssid = "WiFi";
  37. String lanpassphrase = "passwoord";
  38.  
  39. const char* ssid = "pehacontrol";//voor de accespoint
  40. const char* passphrase = "integratorpasword";//voor de accespoint
  41.  
  42.  
  43. String XMLcommand = ""; //XMLcommand to peha stm
  44.  
  45.  
  46. //int LEDPIN = 0; //1 is de ingebouwde blauwe led op de esp-01 //2 is pin2 //0 is pin1
  47. //output pinout on ESP12E
  48.  
  49.  
  50.  
  51.  
  52. const char* host = "192.168.1.2"; //peha STM adress
  53. const int PehaXMLport = 6680; //xml telnet port fixed adres by peha
  54. const int PehaHTTPport = 80; //browser port http://192.168.1.2/modulestates.html
  55.  
  56.  
  57. // lijst van argumenten die de browser ons zal aanleveren , sent through Web Socket
  58. //const char LEDON[] = "ledon";//hier worden de button-id's van javascript opgelijst in de ESP-woordenlijst
  59. //const char LEDOFF[] = "ledoff";
  60.  
  61. String stm = "0" ; // stm(0-7)
  62. String module = "0"; // (0-31) inputmodules mogelijk
  63. String kanaalnr = "0"; // (0-15)
  64. String gedrag = "2"; //(aan>0 = 2 ) (uit <1 = 3 )(aan>1 = 4) (uit>1= 5) (aan >2 = 6)
  65.  
  66.  
  67. String getContentType(String filename); // convert the file extension to the MIME type
  68. bool handleFileRead(String path); // send the right file to the client (if it exists)
  69.  
  70.  
  71.  
  72. MDNSResponder mdns;
  73.  
  74.  
  75. ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
  76.  
  77.  
  78.  
  79. ESP8266WebServer server(80);
  80. WebSocketsServer webSocket = WebSocketsServer(81);
  81.  
  82.  
  83.  
  84.  
  85. static const char PROGMEM INDEX_HTML[] = R"rawliteral(
  86. <!DOCTYPE html>
  87. <html>
  88. <head>
  89. <meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
  90. <title>v12345vtm ESP8266 to PehaSTM</title>
  91. <style>
  92. body { background-color: #f4ca41; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }
  93. </style>
  94. <script>
  95. var websock;
  96. function start() {
  97. websock = new WebSocket('ws://' + window.location.hostname + ':81/');
  98. websock.onopen = function(evt) { console.log('websock open'); };
  99. websock.onclose = function(evt) { console.log('websock close'); };
  100. websock.onerror = function(evt) { console.log(evt); };
  101. websock.onmessage = function(evt) {
  102. console.log(evt);
  103. var e = document.getElementById('ledA');
  104. var efoto = document.getElementById('ledAfoto');
  105.  
  106.  
  107.  
  108. if (evt.data === 'ledon') {
  109. e.style.color = 'red';
  110. efoto.innerHTML = '<img src="img/light_1.png" />';
  111. }
  112. else if (evt.data === 'ledoff') {
  113. e.style.color = 'black';
  114. efoto.innerHTML = '<img src="img/light_0.png" />';
  115. }
  116. else {
  117. console.log('unknown event');
  118. // efoto.innerHTML= '<img src="img/werk.png" />';
  119. document.getElementById('espvariabele').innerHTML = (evt.data);
  120. }
  121. };
  122. }
  123.  
  124. ////////////////////////////////
  125. // Send a XML message when the form is submitted.
  126. function jsInputSimXml(){
  127. // Get references to elements on the page.
  128. var stm = document.forms["myForm"]["stm"].value;
  129. var module = document.forms["myForm"]["module"].value;
  130. var kanaalnr = document.forms["myForm"]["kanaalnr"].value;
  131. var gedrag = document.forms["myForm"]["gedrag"].value;
  132. var XLMinputcommand = "<methodCall><methodName>service.stm.simInputEvent</methodName><params><param><value><i4>";
  133. XLMinputcommand += stm + "</i4></value></param><param><value><i4>";
  134. XLMinputcommand += module + "</i4></value></param><param><value><i4>";
  135. XLMinputcommand += kanaalnr + "</i4></value></param><param><value><i4>";
  136. XLMinputcommand += gedrag + "</i4></value></param><param><value><i4>";
  137. XLMinputcommand += "4" + "</i4></value></param></params></methodCall>";
  138. alert(XLMinputcommand);
  139. websock.send(XLMinputcommand); //gans het xml commando zit eerst in de socket , de esp zal dan gans het commando doorsturen via telnet(PehaXMLport , );
  140. //als je een verkeerd of ongekend commando stuurt naar peha blijft de poort open tot de timeout de connectie sluit
  141. return false;
  142. };
  143. //////////////////////////////
  144.  
  145. ////////////////////////////////
  146. // Send a HTTP message when the form is submitted.on port80 ,zoals
  147. //postEvent.html?action=input&STM=0&MOD=2&CHA=8&EVT=2
  148. function jsInputSimHTTP(){
  149. // Get references to elements on the page.
  150.  
  151. var stm2 = document.forms["myForm2"]["stm2"].value;
  152. var module2 = document.forms["myForm2"]["module2"].value;
  153. var kanaalnr2 = document.forms["myForm2"]["kanaalnr2"].value;
  154. var gedrag2 = document.forms["myForm2"]["gedrag2"].value;
  155.  
  156.  
  157. var HTTPinputcommand = "postEvent.html?action=input&STM=";
  158. HTTPinputcommand += stm2 + "&MOD=";
  159. HTTPinputcommand += module2 + "&CHA=";
  160. HTTPinputcommand += kanaalnr2 + "&EVT=";
  161. HTTPinputcommand += gedrag2 ;
  162.  
  163. alert(HTTPinputcommand);
  164. websock.send(HTTPinputcommand); //gans het http commando zit eerst in de socket , de esp zal dan gans het commando doorsturen via telnet(PehaXMLport , );
  165. //als je een verkeerd of ongekend commando stuurt naar peha blijft de poort open tot de timeout de connectie sluit
  166. return false;
  167. };
  168. //////////////////////////////
  169.  
  170.  
  171.  
  172.  
  173.  
  174.  
  175. function myPulserelaisFunction(tegenactie) {
  176. function saysomething(){
  177. // alert(tegenactie);
  178. websock.send(tegenactie);
  179. }
  180. setTimeout(function() { saysomething() }, 3000);
  181. }
  182.  
  183.  
  184.  
  185.  
  186. function buttonclick(e) {
  187. ////filtern PULSE commando
  188. // alert(e.id);//debug javascript en toont de buttonid : voorbeeld "ledon"
  189. // var knopid = e.id ; //"ledonPulse";
  190. // var jaIsmetPulse = knopid.endsWith("Pulse"); //var n is true als er pulse in id staat
  191. if (e.id.endsWith("Pulse")) {
  192. // alert("ja teller starten");
  193. var knopidkort = e.id.replace("Pulse", "");//niet zomaar veranderen voor 2e keer
  194. // alert(e.id); //debug
  195. websock.send(knopidkort);
  196. myPulserelaisFunction("ledoff"); //start de klok en geef mee wat er moet gebeuren
  197. }
  198.  
  199. // alert("done");
  200. /////einde filteren PULSE commando
  201. else
  202. {
  203. websock.send(e.id);
  204. }
  205.  
  206. }
  207. </script>
  208. </head>
  209. <body onload="javascript:start();">
  210. <h1>client to client to server by v12345vtm</h1>
  211. <h3>browsersocket81 to esp to peha6680</h3>
  212. <div id="espvariabele">variabelen from esp to browser</div>
  213.  
  214. <form id="myForm" action="" onsubmit="jsInputSimXml()">
  215. </br> stm(0-7) <input name="stm" type="text" id="stm" value="0" />
  216. </br>module (0-31)<input name="module" type="text" id="mod" value="2" />
  217. </br>kanaalnr (0-15 <input name="kanaalnr" type="text" id="kanaalnr" value="8" />
  218. </br> gedrag (2-6 )<input name="gedrag" type="text" id="gedrag" value="2" />(aan>0 = 2 ) (uit <1 = 3 )(aan>1 = 4) (uit>1= 5) (aan >2 = 6)
  219. <input type="submit" value="CreatePehaXMLHeaderforPort6680">
  220. </form>
  221. <hr>
  222.  
  223. <form id="myForm2" action="" onsubmit="jsInputSimHTTP()">
  224. </br> stm(0-7) <input name="stm2" type="text" id="stm2" value="0" />
  225. </br>module (0-31)<input name="module2" type="text" id="mod2" value="2" />
  226. </br>kanaalnr (0-15 <input name="kanaalnr2" type="text" id="kanaalnr2" value="8" />
  227. </br> gedrag (2-6 )<input name="gedrag2" type="text" id="gedrag2" value="2" />(aan>0 = 2 ) (uit <1 = 3 )(aan>1 = 4) (uit>1= 5) (aan >2 = 6)
  228. <input type="submit" value="CreatePehaHTTPHeaderforPort80">
  229. </form>
  230. </br>
  231. http://PEHA*IP*ADRESS:80/postEvent.html?action=input&STM=0&MOD=2&CHA=8&EVT=2 </br>
  232. </br>
  233. <hr>
  234.  
  235.  
  236. <div id="ledA"><b>ESP-D1-5</b></div>
  237. <div id="ledAfoto">jvascript zet hier foto</div>
  238.  
  239. <button id="ledon" type="button" onclick="buttonclick(this);">On</button>
  240. <button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
  241. <button id="ledonPulse" type="button" onclick="buttonclick(this);">Onpuls timed via javascript</button>
  242. <hr>
  243.  
  244.  
  245.  
  246. <h1><a href='https://www.youtube.com/user/v12345vtm'>Subscribe for more peha esp updates</a></h1>
  247.  
  248. </body>
  249. </html>
  250. )rawliteral";
  251.  
  252. //const int D1 = 5;
  253. // Current LED status
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.  
  266. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
  267. {
  268.  
  269. String StrPayload = (char*)payload;
  270.  
  271. // Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
  272. switch(type) {
  273. case WStype_DISCONNECTED:
  274. Serial.printf("[%u] Disconnected!\r\n", num);
  275. break;
  276. case WStype_CONNECTED:
  277. {
  278. IPAddress ip = webSocket.remoteIP(num);
  279. Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
  280. // resultaat op de compoort = [0] Connected from 192.168.1.27 url: /
  281.  
  282.  
  283. // Send the current LED status feedback van de esp opvragen
  284. webSocket.sendTXT(num, versie);
  285.  
  286.  
  287. Serial.printf("ledje is nu = >");
  288. Serial.print(String(digitalRead(D1)));
  289. Serial.printf("< \n");
  290. if (digitalRead(D1)==1) {
  291. // webSocket.sendTXT(num, "ledon", strlen(LEDON));//hier vullen we payload nr de browser , namelijk
  292. webSocket.sendTXT(num, "ledon");
  293. }
  294. else if (digitalRead(D1)==0){
  295. webSocket.sendTXT(num, "ledoff");
  296. }
  297. }
  298. break;
  299.  
  300.  
  301. case WStype_TEXT:
  302. // Serial.printf("[%u] get Text: %s\r\n", num, payload); // [0] get Text: ledoff
  303. Serial.println(StrPayload);//payload als string werkt makkelijker
  304.  
  305. if (StrPayload.startsWith("postEvent.html")) {
  306. //we kregen van javascript een xml command , dus we sturen door naar 80
  307. // Serial.println(StrPayload);//
  308. //postEvent.html?action=input&STM=0&MOD=2&CHA=8&EVT=2
  309.  
  310. // echter we moeten nu de http standaart volgen en een get aanvragen
  311.  
  312.  
  313. // Serial.println("javascript een htptpsocket omzetten naar GET http");//
  314. telnet(PehaHTTPport , ("GET /"+ StrPayload +" HTTP/1.0"));//nr port 80naar telnet in GET formaat
  315. }
  316.  
  317. else
  318.  
  319. if (StrPayload.startsWith("<methodCall>")) {
  320. //we kregen van javascript een xml command , dus we sturen door naar 6680
  321. //Serial.println(StrPayload);//
  322. // Serial.println("javascript een xmlsocket");//
  323. telnet(PehaXMLport , StrPayload);//nr port 6680 telnet
  324. }
  325.  
  326. else if (StrPayload.startsWith("ledon")) {
  327. //als string "ledon" gelijk is met de payload "ledon" dan de output sturen
  328. digitalWrite(D1, 1);
  329.  
  330.  
  331. }
  332. else if (StrPayload.startsWith("ledoff")) {
  333.  
  334. digitalWrite(D1, 0);
  335.  
  336.  
  337. }
  338. else {
  339. Serial.print("browser stuur payload die we niet geleerd hebben \nmaar we forwarden het naar telnet: " );
  340. Serial.printf("%s", payload);
  341. // telnet(PehaXMLport , StrPayload);//stuur maar wat je kreeg van javascript door naar telnet
  342. }
  343.  
  344. // send data to all connected clients
  345. webSocket.broadcastTXT(payload, length);
  346. break;
  347. case WStype_BIN:
  348. Serial.printf("[%u] get binary length: %u\r\n", num, length);
  349. hexdump(payload, length);
  350.  
  351. // echo data back to browser
  352. webSocket.sendBIN(num, payload, length);
  353. break;
  354. default:
  355. Serial.printf("Invalid WStype [%d]\r\n", type);
  356. break;
  357. }
  358. }
  359.  
  360. void handleRoot()
  361. {
  362. server.send_P(200, "text/html", INDEX_HTML);
  363. }
  364.  
  365. void handleNotFound()
  366. {
  367.  
  368. }
  369.  
  370.  
  371.  
  372. void setup()
  373. {
  374.  
  375. yield();
  376.  
  377. //Onboard LED port Direction output
  378. // pinMode(D0 , INPUT);//5 = LEd D1 op ESP12E
  379. pinMode(D1, OUTPUT);//5 = LEd D1 op ESP12E
  380. pinMode(D2, OUTPUT);//5 = LEd D1 op ESP12E
  381. pinMode(D3, OUTPUT);//5 = LEd D1 op ESP12E
  382. pinMode(D4, OUTPUT);//5 = LEd D1 op ESP12E
  383. pinMode(D5, OUTPUT);//14op ESP12E
  384. pinMode(D6, OUTPUT);//5 = LEd D1 op ESP12E
  385. pinMode(D7, OUTPUT);//5 = LEd D1 op ESP12E
  386. pinMode(D8, OUTPUT);//5 = LEd D1 op ESP12E
  387.  
  388. Serial.begin(115200);
  389. SPIFFS.begin(); // Start the SPI Flash Files
  390.  
  391. for(uint8_t t = 4; t > 0; t--) {
  392. Serial.printf("verbinden met lan %d...\r\n", t);
  393.  
  394. Serial.flush();
  395. yield();
  396. delay(1000);
  397. }
  398.  
  399. bestandsysteem() ; //toon in serialport alle SPIFFS in het bestandsysteem
  400. Serial.println("SPIFFS server ok");
  401. Serial.println(versie);
  402.  
  403. char ssidchar[lanssid.length()+1];
  404. lanssid.toCharArray(ssidchar, lanssid.length()+1);
  405. char lanpassphrasechar[lanpassphrase.length()+1];
  406. lanpassphrase.toCharArray(lanpassphrasechar, lanpassphrase.length()+1);
  407.  
  408. // Serial.println(ssidchar);
  409. // Serial.println(lanpassphrasechar);
  410.  
  411. wifiMulti.addAP(ssidchar, lanpassphrasechar); // add Wi-Fi networks you want to connect to
  412.  
  413. while(wifiMulti.run() != WL_CONNECTED) {
  414. Serial.print(".");
  415. delay(100);
  416. }
  417.  
  418.  
  419.  
  420. if (mdns.begin("esp8266", WiFi.localIP())) {
  421. Serial.println("MdnsUrl=esp8266.local");
  422. mdns.addService("http", "tcp", 80);
  423. mdns.addService("ws", "tcp", 81);
  424. }
  425. else {
  426. Serial.println("MDNSfailed");
  427. }
  428.  
  429. server.on("/", handleRoot);
  430.  
  431. server.onNotFound([]() { // If the client requests any URI
  432. if (!handleFileRead(server.uri())) // send it if it exists
  433. // server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  434. // String message = "File Not Found\n\n";
  435. server.send(404, "text/plain", "File Not Found\n\n");
  436. });
  437.  
  438. server.begin();
  439.  
  440.  
  441.  
  442.  
  443. webSocket.begin();
  444. webSocket.onEvent(webSocketEvent);
  445.  
  446.  
  447. //accespoint oprichten
  448.  
  449.  
  450. delay(100);
  451. WiFi.softAP(ssid, passphrase, 6);//straal je accespoint ssid uit
  452.  
  453. Serial.print("Local IP: ");
  454. Serial.println(WiFi.localIP());
  455. Serial.print("SoftAP IP: ");
  456. Serial.println(WiFi.softAPIP());
  457.  
  458. Serial.print("ready for send data to peha STM ip ");
  459. Serial.println(host);
  460. Serial.print(" at port 80 and/or 6680 \n END OF BOOT \n\n");
  461.  
  462.  
  463.  
  464. }
  465.  
  466. void loop()
  467. {
  468. webSocket.loop();
  469. server.handleClient();
  470.  
  471. }
  472.  
  473.  
  474.  
  475.  
  476. void telnet(int destinationport , String javascriptform) {
  477. WiFiClient client; //to connect to peha
  478.  
  479.  
  480. if (!client.connect(host, destinationport)) {
  481. Serial.println("connection failed to port " + destinationport);
  482. return;
  483. }
  484.  
  485.  
  486.  
  487. // This will send the request to the server XMLcommand = is een werkend test bericht naar de peha
  488. XMLcommand = "<methodCall><methodName>service.stm.simInputEvent</methodName><params><param><value><i4>";
  489. XMLcommand += stm + "</i4></value></param><param><value><i4>";
  490. XMLcommand += module + " </i4></value></param><param><value><i4>";
  491. XMLcommand += kanaalnr + "</i4></value></param><param><value><i4>";
  492. XMLcommand += gedrag + "</i4></value></param><param><value><i4>4</i4></value></param></params></methodCall>";
  493.  
  494. Serial.println( destinationport+ "port data send to peha:\n\n" + javascriptform);
  495.  
  496. client.print(javascriptform);
  497. int connectietimeouthttp= 5000;//default noodstop timeout
  498. if (destinationport==PehaHTTPport)
  499. {
  500. connectietimeouthttp= 500;//we krijgen geen antwoord op imputcommandos van pehaport80
  501. }
  502.  
  503.  
  504.  
  505.  
  506. unsigned long timeout = millis();
  507. while (client.available() == 0) {
  508. if (millis() - timeout > connectietimeouthttp) {
  509. Serial.println(">>> Client Timeout !");
  510. client.stop();
  511. return;
  512. }
  513. }
  514.  
  515. // Read all the lines of the reply from server and print them to Serial
  516. Serial.println("\n\nstart of peha respons........");
  517. while (client.available()) {
  518. String peharespons = client.readStringUntil('\r');
  519. Serial.print(peharespons);
  520. }
  521.  
  522.  
  523. Serial.println("end of peha respons........... en we sluiten zelf de connectie");
  524. client.stop();
  525.  
  526.  
  527.  
  528.  
  529.  
  530.  
  531. }
  532.  
  533.  
  534. String getContentType(String filename) { // convert the file extension to the MIME type
  535. if (filename.endsWith(".html")) return "text/html";
  536. else if (filename.endsWith(".css")) return "text/css";
  537. else if (filename.endsWith(".js")) return "application/javascript";
  538. else if (filename.endsWith(".ico")) return "image/x-icon";
  539. else if (filename.endsWith(".png")) return "image/x-icon";
  540. else if (filename.endsWith(".jpg")) return "image/x-icon";
  541. return "text/plain";
  542. }
  543.  
  544. bool handleFileRead(String path) { // send the right file to the client (if it exists)
  545. Serial.println("handleFileRead: " + path);
  546. if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
  547. String contentType = getContentType(path); // Get the MIME type
  548. if (SPIFFS.exists(path)) { // If the file exists
  549. File file = SPIFFS.open(path, "r"); // Open it
  550. size_t sent = server.streamFile(file, contentType); // And send it to the client
  551. file.close(); // Then close the file again
  552. return true;
  553. }
  554. Serial.println("\tFile Not Found");
  555. return false; // If the file doesn't exist, return false
  556. }
  557.  
  558.  
  559.  
  560. //////////
  561. /////
  562. String bestandsysteem()
  563. {
  564. /////check filesystem
  565. String filesysteem = "<ul>";
  566. Dir dir = SPIFFS.openDir("/");
  567. while (dir.next()) {
  568. filesysteem += "<li>";
  569. filesysteem += dir.fileName();
  570. filesysteem += " ";
  571. filesysteem += dir.fileSize();
  572. filesysteem += "kb</li>";
  573. }
  574. filesysteem += "<ul>";
  575. /////interne webpaginas
  576. filesysteem += "<ul>";
  577.  
  578. // filesysteem += "<li>/ als lan device met ipadres en versie als melding</li>";
  579. filesysteem += "<li>/ root</li>";
  580. filesysteem += "<ul>";
  581. Serial.println(filesysteem);
  582. return filesysteem;
  583. }
  584. ///einde check filesystem
Advertisement
Add Comment
Please, Sign In to add comment