Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- https://www.youtube.com/watch?v=aX6vp91kF9I youtube=v12345vtm
- basic concept of telnet session to peha domotics stm module
- send a XML request or a http request and print out the respons to peha STM
- skectch for simulating peha inputs on esp12e
- todo accespoit to setup peha ip ...wifi...
- */
- #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
- #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 = "peha-inputsimulatie7 -accespoint";
- String lanssid = "WiFi";
- String lanpassphrase = "passwoord";
- const char* ssid = "pehacontrol";//voor de accespoint
- const char* passphrase = "integratorpasword";//voor de accespoint
- String XMLcommand = ""; //XMLcommand to peha stm
- //int LEDPIN = 0; //1 is de ingebouwde blauwe led op de esp-01 //2 is pin2 //0 is pin1
- //output pinout on ESP12E
- const char* host = "192.168.1.2"; //peha STM adress
- const int PehaXMLport = 6680; //xml telnet port fixed adres by peha
- const int PehaHTTPport = 80; //browser port http://192.168.1.2/modulestates.html
- // 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";
- String stm = "0" ; // stm(0-7)
- String module = "0"; // (0-31) inputmodules mogelijk
- String kanaalnr = "0"; // (0-15)
- String gedrag = "2"; //(aan>0 = 2 ) (uit <1 = 3 )(aan>1 = 4) (uit>1= 5) (aan >2 = 6)
- 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 to PehaSTM</title>
- <style>
- body { background-color: #f4ca41; 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" />';
- document.getElementById('espvariabele').innerHTML = (evt.data);
- }
- };
- }
- ////////////////////////////////
- // Send a XML message when the form is submitted.
- function jsInputSimXml(){
- // Get references to elements on the page.
- var stm = document.forms["myForm"]["stm"].value;
- var module = document.forms["myForm"]["module"].value;
- var kanaalnr = document.forms["myForm"]["kanaalnr"].value;
- var gedrag = document.forms["myForm"]["gedrag"].value;
- var XLMinputcommand = "<methodCall><methodName>service.stm.simInputEvent</methodName><params><param><value><i4>";
- XLMinputcommand += stm + "</i4></value></param><param><value><i4>";
- XLMinputcommand += module + "</i4></value></param><param><value><i4>";
- XLMinputcommand += kanaalnr + "</i4></value></param><param><value><i4>";
- XLMinputcommand += gedrag + "</i4></value></param><param><value><i4>";
- XLMinputcommand += "4" + "</i4></value></param></params></methodCall>";
- alert(XLMinputcommand);
- websock.send(XLMinputcommand); //gans het xml commando zit eerst in de socket , de esp zal dan gans het commando doorsturen via telnet(PehaXMLport , );
- //als je een verkeerd of ongekend commando stuurt naar peha blijft de poort open tot de timeout de connectie sluit
- return false;
- };
- //////////////////////////////
- ////////////////////////////////
- // Send a HTTP message when the form is submitted.on port80 ,zoals
- //postEvent.html?action=input&STM=0&MOD=2&CHA=8&EVT=2
- function jsInputSimHTTP(){
- // Get references to elements on the page.
- var stm2 = document.forms["myForm2"]["stm2"].value;
- var module2 = document.forms["myForm2"]["module2"].value;
- var kanaalnr2 = document.forms["myForm2"]["kanaalnr2"].value;
- var gedrag2 = document.forms["myForm2"]["gedrag2"].value;
- var HTTPinputcommand = "postEvent.html?action=input&STM=";
- HTTPinputcommand += stm2 + "&MOD=";
- HTTPinputcommand += module2 + "&CHA=";
- HTTPinputcommand += kanaalnr2 + "&EVT=";
- HTTPinputcommand += gedrag2 ;
- alert(HTTPinputcommand);
- websock.send(HTTPinputcommand); //gans het http commando zit eerst in de socket , de esp zal dan gans het commando doorsturen via telnet(PehaXMLport , );
- //als je een verkeerd of ongekend commando stuurt naar peha blijft de poort open tot de timeout de connectie sluit
- return false;
- };
- //////////////////////////////
- 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>client to client to server by v12345vtm</h1>
- <h3>browsersocket81 to esp to peha6680</h3>
- <div id="espvariabele">variabelen from esp to browser</div>
- <form id="myForm" action="" onsubmit="jsInputSimXml()">
- </br> stm(0-7) <input name="stm" type="text" id="stm" value="0" />
- </br>module (0-31)<input name="module" type="text" id="mod" value="2" />
- </br>kanaalnr (0-15 <input name="kanaalnr" type="text" id="kanaalnr" value="8" />
- </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)
- <input type="submit" value="CreatePehaXMLHeaderforPort6680">
- </form>
- <hr>
- <form id="myForm2" action="" onsubmit="jsInputSimHTTP()">
- </br> stm(0-7) <input name="stm2" type="text" id="stm2" value="0" />
- </br>module (0-31)<input name="module2" type="text" id="mod2" value="2" />
- </br>kanaalnr (0-15 <input name="kanaalnr2" type="text" id="kanaalnr2" value="8" />
- </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)
- <input type="submit" value="CreatePehaHTTPHeaderforPort80">
- </form>
- </br>
- http://PEHA*IP*ADRESS:80/postEvent.html?action=input&STM=0&MOD=2&CHA=8&EVT=2 </br>
- </br>
- <hr>
- <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>
- <hr>
- <h1><a href='https://www.youtube.com/user/v12345vtm'>Subscribe for more peha esp updates</a></h1>
- </body>
- </html>
- )rawliteral";
- //const int D1 = 5;
- // Current LED status
- void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
- {
- String StrPayload = (char*)payload;
- // 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
- webSocket.sendTXT(num, versie);
- 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
- webSocket.sendTXT(num, "ledon");
- }
- else if (digitalRead(D1)==0){
- webSocket.sendTXT(num, "ledoff");
- }
- }
- break;
- case WStype_TEXT:
- // Serial.printf("[%u] get Text: %s\r\n", num, payload); // [0] get Text: ledoff
- Serial.println(StrPayload);//payload als string werkt makkelijker
- if (StrPayload.startsWith("postEvent.html")) {
- //we kregen van javascript een xml command , dus we sturen door naar 80
- // Serial.println(StrPayload);//
- //postEvent.html?action=input&STM=0&MOD=2&CHA=8&EVT=2
- // echter we moeten nu de http standaart volgen en een get aanvragen
- // Serial.println("javascript een htptpsocket omzetten naar GET http");//
- telnet(PehaHTTPport , ("GET /"+ StrPayload +" HTTP/1.0"));//nr port 80naar telnet in GET formaat
- }
- else
- if (StrPayload.startsWith("<methodCall>")) {
- //we kregen van javascript een xml command , dus we sturen door naar 6680
- //Serial.println(StrPayload);//
- // Serial.println("javascript een xmlsocket");//
- telnet(PehaXMLport , StrPayload);//nr port 6680 telnet
- }
- else if (StrPayload.startsWith("ledon")) {
- //als string "ledon" gelijk is met de payload "ledon" dan de output sturen
- digitalWrite(D1, 1);
- }
- else if (StrPayload.startsWith("ledoff")) {
- digitalWrite(D1, 0);
- }
- else {
- Serial.print("browser stuur payload die we niet geleerd hebben \nmaar we forwarden het naar telnet: " );
- Serial.printf("%s", payload);
- // telnet(PehaXMLport , StrPayload);//stuur maar wat je kreeg van javascript door naar telnet
- }
- // 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()
- {
- 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("verbinden met lan %d...\r\n", t);
- Serial.flush();
- yield();
- delay(1000);
- }
- bestandsysteem() ; //toon in serialport alle SPIFFS in het bestandsysteem
- Serial.println("SPIFFS server ok");
- Serial.println(versie);
- 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);
- }
- if (mdns.begin("esp8266", WiFi.localIP())) {
- Serial.println("MdnsUrl=esp8266.local");
- mdns.addService("http", "tcp", 80);
- mdns.addService("ws", "tcp", 81);
- }
- else {
- Serial.println("MDNSfailed");
- }
- 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);
- //accespoint oprichten
- delay(100);
- WiFi.softAP(ssid, passphrase, 6);//straal je accespoint ssid uit
- Serial.print("Local IP: ");
- Serial.println(WiFi.localIP());
- Serial.print("SoftAP IP: ");
- Serial.println(WiFi.softAPIP());
- Serial.print("ready for send data to peha STM ip ");
- Serial.println(host);
- Serial.print(" at port 80 and/or 6680 \n END OF BOOT \n\n");
- }
- void loop()
- {
- webSocket.loop();
- server.handleClient();
- }
- void telnet(int destinationport , String javascriptform) {
- WiFiClient client; //to connect to peha
- if (!client.connect(host, destinationport)) {
- Serial.println("connection failed to port " + destinationport);
- return;
- }
- // This will send the request to the server XMLcommand = is een werkend test bericht naar de peha
- XMLcommand = "<methodCall><methodName>service.stm.simInputEvent</methodName><params><param><value><i4>";
- XMLcommand += stm + "</i4></value></param><param><value><i4>";
- XMLcommand += module + " </i4></value></param><param><value><i4>";
- XMLcommand += kanaalnr + "</i4></value></param><param><value><i4>";
- XMLcommand += gedrag + "</i4></value></param><param><value><i4>4</i4></value></param></params></methodCall>";
- Serial.println( destinationport+ "port data send to peha:\n\n" + javascriptform);
- client.print(javascriptform);
- int connectietimeouthttp= 5000;//default noodstop timeout
- if (destinationport==PehaHTTPport)
- {
- connectietimeouthttp= 500;//we krijgen geen antwoord op imputcommandos van pehaport80
- }
- unsigned long timeout = millis();
- while (client.available() == 0) {
- if (millis() - timeout > connectietimeouthttp) {
- Serial.println(">>> Client Timeout !");
- client.stop();
- return;
- }
- }
- // Read all the lines of the reply from server and print them to Serial
- Serial.println("\n\nstart of peha respons........");
- while (client.available()) {
- String peharespons = client.readStringUntil('\r');
- Serial.print(peharespons);
- }
- Serial.println("end of peha respons........... en we sluiten zelf de connectie");
- client.stop();
- }
- 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>/ als lan device met ipadres en versie als melding</li>";
- filesysteem += "<li>/ root</li>";
- filesysteem += "<ul>";
- Serial.println(filesysteem);
- return filesysteem;
- }
- ///einde check filesystem
Advertisement
Add Comment
Please, Sign In to add comment