OursGenial

Code_2_Sliders

Dec 26th, 2020
20
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. *.js :
  2. var gateway = `ws://${window.location.hostname}/ws`;
  3. var websocket;
  4.  
  5. window.addEventListener('load', onload);
  6.  
  7. function onload(event) {
  8. initWebSocket();
  9. getCurrentValue();
  10. }
  11.  
  12. function initWebSocket() {
  13. console.log('Trying to open a WebSocket connection…');
  14. websocket = new WebSocket(gateway);
  15. websocket.onopen = onOpen;
  16. websocket.onclose = onClose;
  17. websocket.onmessage = onMessage;
  18. }
  19.  
  20. function onOpen(event) {
  21. console.log('Connection opened');
  22. }
  23.  
  24. function onClose(event) {
  25. console.log('Connection closed');
  26. setTimeout(initWebSocket, 2000);
  27. }
  28.  
  29. function onMessage(event) {
  30. console.log(event.data);
  31. }
  32.  
  33. function getCurrentValue(){
  34. var xhr = new XMLHttpRequest();
  35. xhr.onreadystatechange = function() {
  36. if (this.readyState == 4 && this.status == 200) {
  37. document.getElementById("pwmSlider").value = this.responseText;
  38. document.getElementById("textSliderValue").innerHTML = this.responseText;
  39. }
  40. xhr.open("GET", "/currentValue", true);
  41. if (this.readyState == 4 && this.status == 200) {
  42. document.getElementById("pwmSlider4").value = this.responseText;
  43. document.getElementById("textSliderValue4").innerHTML = this.responseText;
  44. }
  45. };
  46. xhr.open("GET", "/currentValue4", true);
  47. xhr.send();
  48. }
  49.  
  50. function updateSliderPWM(element) {
  51. var sliderValue = document.getElementById("pwmSlider").value;
  52. document.getElementById("textSliderValue").innerHTML = sliderValue;
  53. console.log(sliderValue);
  54. websocket.send(sliderValue);
  55. }
  56.  
  57. function updateSliderPWM4(element) {
  58. var sliderValue4 = document.getElementById("pwmSlider4").value;
  59. document.getElementById("textSliderValue4").innerHTML = sliderValue4;
  60. console.log(sliderValue4);
  61. websocket.send(sliderValue4);
  62. }
  63.  
  64. *.html:
  65. <!DOCTYPE html>
  66. <html>
  67. <head>
  68. <title>ESP IOT DASHBOARD</title>
  69. <meta name="viewport" content="width=device-width, initial-scale=1">
  70. <link rel="icon" type="image/png" href="favicon.png">
  71. <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  72. <link rel="stylesheet" type="text/css" href="style.css">
  73. </head>
  74. <body>
  75. <div class="topnav">
  76. <h1>ESP WEB SERVER</h1>
  77. </div>
  78. <div class="content">
  79. <div class="card-grid">
  80. <div class="card">
  81. <p class="card-title"><i class="fas fa-lightbulb"></i> GPIO 2</p>
  82. <p class="switch">
  83. <input type="range" oninput="updateSliderPWM(this)" id="pwmSlider" min="0" max="100" step="1" value ="0" class="slider">
  84. </p>
  85. <p class="state">Brightness: <span id="textSliderValue"></span> &percnt;</p>
  86. <p class="card-title"><i class="fas fa-lightbulb"></i> GPIO 4</p>
  87. <p class="switch">
  88. <input type="range" oninput="updateSliderPWM4(this)" id="pwmSlider4" min="0" max="100" step="1" value ="0" class="slider">
  89. </p>
  90. <p class="state">Brightness: <span id="textSliderValue4"></span> &percnt;</p>
  91. </div>
  92. </div>
  93. </div>
  94. <script src="script.js"></script>
  95. </body>
  96. </html>
  97.  
  98. *.ino
  99. /*********
  100. Rui Santos
  101. Complete instructions at https://RandomNerdTutorials.com/build-web-servers-ebook/
  102.  
  103. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  104. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  105.  
  106.  
  107. *********/
  108.  
  109. #include <Arduino.h>
  110. #include <WiFi.h>
  111. #include <AsyncTCP.h>
  112. #include <ESPAsyncWebServer.h>
  113. #include "SPIFFS.h"
  114.  
  115. // Replace with your network credentials
  116. const char* ssid = "XXXX";
  117. const char* password = "XXXX";
  118.  
  119. // Create AsyncWebServer object on port 80
  120. AsyncWebServer server(80);
  121.  
  122. // Create a WebSocket object
  123. AsyncWebSocket ws("/ws");
  124.  
  125. // Set LED GPIO
  126. const int ledPin = 2;
  127. const int ledPin4 = 4;
  128.  
  129. // setting PWM properties
  130. const int freq = 5000;
  131. const int ledChannel = 0;
  132. const int resolution = 8;
  133. const int ledChannel4 = 0;
  134.  
  135.  
  136. String sliderValue = "0";
  137. String sliderValue4 = "0";
  138. int dutyCycle,dutyCycle4;
  139.  
  140. // Initialize SPIFFS
  141. void initSPIFFS() {
  142. if (!SPIFFS.begin(true)) {
  143. Serial.println("An error has occurred while mounting SPIFFS");
  144. }
  145. Serial.println("SPIFFS mounted successfully");
  146. }
  147.  
  148. // Initialize WiFi
  149. void initWiFi() {
  150. WiFi.mode(WIFI_STA);
  151. WiFi.begin(ssid, password);
  152. Serial.print("Connecting to WiFi ..");
  153. while (WiFi.status() != WL_CONNECTED) {
  154. Serial.print('.');
  155. delay(1000);
  156. }
  157. Serial.println(WiFi.localIP());
  158. }
  159.  
  160. void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
  161. AwsFrameInfo *info = (AwsFrameInfo*)arg;
  162. if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
  163. data[len] = 0;
  164. sliderValue = (char*)data;
  165. dutyCycle = map(sliderValue.toInt(), 0, 100, 0, 255);
  166. dutyCycle4 = map(sliderValue4.toInt(), 0, 100, 0, 255);
  167. Serial.print("dutyCycle Led 2:");
  168. Serial.println(dutyCycle);
  169. Serial.print("dutyCycle Led 4:");
  170. Serial.println(dutyCycle4);
  171. }
  172. }
  173.  
  174. void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
  175. void *arg, uint8_t *data, size_t len) {
  176. switch (type) {
  177. case WS_EVT_CONNECT:
  178. Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
  179. break;
  180. case WS_EVT_DISCONNECT:
  181. Serial.printf("WebSocket client #%u disconnected\n", client->id());
  182. break;
  183. case WS_EVT_DATA:
  184. handleWebSocketMessage(arg, data, len);
  185. break;
  186. case WS_EVT_PONG:
  187. case WS_EVT_ERROR:
  188. break;
  189. }
  190. }
  191.  
  192. void initWebSocket() {
  193. ws.onEvent(onEvent);
  194. server.addHandler(&ws);
  195. }
  196.  
  197. void setup() {
  198. Serial.begin(115200);
  199. pinMode(ledPin, OUTPUT);
  200. pinMode(ledPin4, OUTPUT);
  201.  
  202. initSPIFFS();
  203. initWiFi();
  204.  
  205. // configure LED PWM functionalitites
  206. ledcSetup(ledChannel, freq, resolution);
  207. ledcSetup(ledChannel4, freq, resolution);
  208. // attach the channel to the GPIO to be controlled
  209. ledcAttachPin(ledPin, ledChannel);
  210. ledcAttachPin(ledPin4, ledChannel4);
  211.  
  212. initWebSocket();
  213.  
  214. // Web Server Root URL
  215. server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
  216. request->send(SPIFFS, "/index.html", "text/html");
  217. });
  218.  
  219. server.serveStatic("/", SPIFFS, "/");
  220.  
  221. server.on("/currentValue", HTTP_GET, [](AsyncWebServerRequest *request) {
  222. request->send(200, "/text/plain", String(sliderValue).c_str());
  223. });
  224.  
  225. server.on("/currentValue4", HTTP_GET, [](AsyncWebServerRequest *request) {
  226. request->send(200, "/text/plain", String(sliderValue4).c_str());
  227. });
  228.  
  229. // Start server
  230. server.begin();
  231. }
  232.  
  233. void loop() {
  234. ledcWrite(ledChannel, dutyCycle);
  235. ledcWrite(ledChannel4, dutyCycle);
  236.  
  237. ws.cleanupClients();
  238. }
RAW Paste Data