v12345vtm

peha-feedback5.ino

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