Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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 get all feedback of modules status and lamps peha inputs on esp12e
- todo accespoit to setup peha ip ...wifi...
- <methodCall><methodName>service.stm.sendTelegram</methodName><params><param><value><i4>0</i4></value></param><param><value><i4>64</i4></value></param><param><value><i4>1</i4></value></param></params></methodCall>
- via telnet kan ook naar stm0 naar mod 64
- */
- String versie = "peha-feedback5.ino - socket close";
- #define D0 16 //input flash via knop
- #define D1 5// browser test led
- #define D2 4
- #define D3 0
- #define D4 2
- #define D5 14 //connection to peha telent sessie open
- #define D6 12
- #define D7 13//buzzer telnet open
- #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 lanssid = "WiF";
- String lanpassphrase = "pass";
- const char* ssid = "pehacontrol";//voor de accespoint
- const char* passphrase = "integratorpasword";//voor de accespoint
- String peharespons = ""; //respons
- int teller = 0;
- String xmlParse = "<i4>"; //parse this most inner xml element (no
- int xmlElementlength = 6;// how long is the data you look for maximum lengte?
- String element = "";
- //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 by vith of firefox');};
- websock.onerror = function(evt) { console.log(evt); };
- websock.onmessage = function(evt) {
- console.log(evt);
- if (evt.data.startsWith(document.forms["myForm"]["stm"].value)) {
- //als we feedback zien de al begint met de stm nummer , zetten we het neer in de html placeholder
- console.log(evt.data);
- document.getElementById('htmlmodulestatus').innerHTML = (evt.data);
- }
- else if (evt.data === 'ledon') {
- console.log(evt.data);
- document.getElementById('ledA').style.color = 'red';
- document.getElementById('ledAfoto').innerHTML = '<img src="img/light_1.png" />';
- }
- else if (evt.data === 'ledoff') {
- console.log(evt.data);
- document.getElementById('ledA').style.color = 'black';
- document.getElementById('ledAfoto').innerHTML = '<img src="img/light_0.png" />';
- }
- else {
- console.log('niet opgevangen in javascript event' + evt.data );
- // efoto.innerHTML= '<img src="img/werk.png" />';
- document.getElementById('espvariabele').innerHTML = (evt.data);
- }
- };
- }
- ////////////////////////////
- // Send a XML message when the form is submitted. <?xml version=""1.0"" encoding=""UTF-8""?>
- function jsFeedbackXml(){
- // Get references to elements on the page.
- var stm = document.forms["myForm"]["stm"].value;
- var module = document.forms["myForm"]["module"].value;
- var XLMfeedbackcommand = "<methodCall><methodName>service.stm.sendTelegram</methodName><params><param><value><i4>";
- XLMfeedbackcommand += stm +"</i4></value></param><param><value><i4>";
- XLMfeedbackcommand += module + "</i4></value></param><param><value><i4>";
- XLMfeedbackcommand += "1</i4></value></param></params></methodCall>";
- // alert(XLMfeedbackcommand);
- websock.send(XLMfeedbackcommand); //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;
- };
- ////////
- function myPulserelaisFunction(tegenactie) {
- function saysomething(){
- // alert(tegenactie);
- websock.send(tegenactie);
- }
- setTimeout(function() { saysomething() }, 3000);
- }
- function buttonclick(e) {
- 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
- }
- 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 get modulefeedback from peha</h3>
- <div id="espvariabele">variabelen from esp to browser</div>
- <script>
- function pehametadata(meta) {
- var stm = document.forms["myForm"]["stm"].value;
- var phklok = "<methodCall><methodName>service.stm."+ meta.id +"</methodName><params><param><value><i4>"+ stm +"</i4></value></param></params></methodCall>";
- var phversie = "<methodCall><methodName>service.stm."+ meta.id +"</methodName><params><param><value><i4>"+ stm +"</i4></value></param></params></methodCall>";
- var phvolt = "<methodCall><methodName>service.stm."+ meta.id +"</methodName><params><param><value><i4>"+ stm +"</i4></value></param></params></methodCall>";
- var pffile = "<methodCall><methodName>service.stm."+ meta.id +"</methodName><params><param><value><i4>"+ stm +"</i4></value></param></params></methodCall>";
- var phpor = "<methodCall><methodName>service.stm."+ meta.id +"</methodName><params><param><value><i4>"+ stm +"</i4></value></param><param><value><boolean>0</boolean></value></param></params></methodCall>";
- websock.send(phklok);
- }
- </script>
- <button id='getClock' type="button" onclick="pehametadata(this);">getClock</button>
- <button id='getVersion' type="button" onclick="pehametadata(this);">getVersion</button>
- <button id='getVoltage' type="button" onclick="pehametadata(this);">getVoltage</button>
- <button id='getProgrammerInfo' type="button" onclick="pehametadata(this);">getProgrammerInfo</button>
- <button id='sendPOR' type="button" onclick="nogtedoen(this);">sendPOR todo</button>
- <form id="myForm" action="javascript:void(0);" onsubmit="jsFeedbackXml()">
- </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="64" />
- </br>ingang0 , multi32 , uitgang64 , analoog96 , box128 , dim160</br>
- <input type="submit" value="CreatePehaXMLHeaderforPort6680">
- </form>
- <div id="htmlmodulestatus">module : antwoord : </div>
- <hr>
- </br>
- http://192.168.1.2/modulestates.html =lijst met verbonden modules </br>
- </br>
- <h1><a href='http://192.168.1.2/modulestates.html'>get alle modules via stm zelf</a></h1>
- <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";
- 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);//zende de ino file naam door nr browser ook
- 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 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);
- 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) {
- digitalWrite(D7, 1);//
- digitalWrite(D5, 1);//
- WiFiClient client; //to connect to peha
- if (!client.connect(host, destinationport)) {
- Serial.println("connection failed to port " + destinationport);
- digitalWrite(D7, 0);//
- digitalWrite(D5, 0);//
- return;
- }
- client.print(javascriptform);//send to peha
- int connectietimeouthttp = 4000; //default noodstop timeout voor alle berichten , worst case
- 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(">>> telnet6680 Timeout !");
- client.stop(); //stop client telnet naar peha , stop connectie en poort weer vrijmaken
- webSocket.sendTXT(0, "0> telnet6680 Timeout@4sec !");// parameter nul ingeztet kip tegen muur en naar de brwser gestuurd zie console in firefox inpsect element
- digitalWrite(D7, 0);//
- digitalWrite(D5, 0);//
- return;
- }
- }
- //********************
- // bezig met luisteren naar de peha stm....
- peharespons = ""; //reset de container
- while (client.available()) {
- char c = client.read();
- peharespons += c;
- }
- // Serial.println("\n\nstart of peha respons........");
- //Serial.println(peharespons);
- client.stop();
- String modulestatusdecoded = decodeXML(peharespons);//gedecodeert op xml <i4> tot nuttige dataelementen , indien er inzaten tenminste
- webSocket.sendTXT(0, modulestatusdecoded);// parameter nul ingeztet kip tegen muur en naar de brwser gestuurd zie console in firefox inpsect element
- digitalWrite(D7, 0);//
- digitalWrite(D5, 0);//
- //*****************
- }
- 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
- //////////////////////
- String decodeXML(String peharesponsxml) {
- String ruwedata = "";
- teller = 0;
- String rijvanelementen = ""; //preinitialiseren op worstcase
- if (find_text(xmlParse, peharesponsxml) > 0)
- {
- // Serial.println( xmlParse + "found");
- for (int i = 0; i < peharesponsxml.length(); i++) {
- if (peharesponsxml.substring(i, i + xmlParse.length()) == xmlParse) {
- teller++;
- ruwedata = peharesponsxml.substring(i + xmlParse.length(), i + xmlParse.length() + xmlElementlength);
- for (int i = 0; i < ruwedata.length(); i++) {
- if (ruwedata.substring(i, i + 1) == "<") {
- element = ruwedata.substring(0, i);
- // Serial.println("\t output=" +element); // <i4> element teller
- rijvanelementen += element + ",";
- break;
- }
- }
- }
- }
- // Serial.println(teller);
- }
- else
- {
- // Serial.println( xmlParse + "not found");
- rijvanelementen = peharesponsxml;//pass treugh of respons zonder i4
- }
- Serial.println( rijvanelementen);
- return rijvanelementen;
- }
- /////////////////////
- int find_text(String needle, String haystack) {
- int foundpos = -1;
- for (int i = 0; i <= haystack.length() - needle.length(); i++) {
- if (haystack.substring(i, needle.length() + i) == needle) {
- foundpos = i;
- }
- }
- return foundpos;
- }
Advertisement
Add Comment
Please, Sign In to add comment