Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- *.js :
- var gateway = `ws://${window.location.hostname}/ws`;
- var websocket;
- window.addEventListener('load', onload);
- function onload(event) {
- initWebSocket();
- getCurrentValue();
- }
- function initWebSocket() {
- console.log('Trying to open a WebSocket connection…');
- websocket = new WebSocket(gateway);
- websocket.onopen = onOpen;
- websocket.onclose = onClose;
- websocket.onmessage = onMessage;
- }
- function onOpen(event) {
- console.log('Connection opened');
- }
- function onClose(event) {
- console.log('Connection closed');
- setTimeout(initWebSocket, 2000);
- }
- function onMessage(event) {
- console.log(event.data);
- }
- function getCurrentValue(){
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("pwmSlider").value = this.responseText;
- document.getElementById("textSliderValue").innerHTML = this.responseText;
- }
- xhr.open("GET", "/currentValue", true);
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById("pwmSlider4").value = this.responseText;
- document.getElementById("textSliderValue4").innerHTML = this.responseText;
- }
- };
- xhr.open("GET", "/currentValue4", true);
- xhr.send();
- }
- function updateSliderPWM(element) {
- var sliderValue = document.getElementById("pwmSlider").value;
- document.getElementById("textSliderValue").innerHTML = sliderValue;
- console.log(sliderValue);
- websocket.send(sliderValue);
- }
- function updateSliderPWM4(element) {
- var sliderValue4 = document.getElementById("pwmSlider4").value;
- document.getElementById("textSliderValue4").innerHTML = sliderValue4;
- console.log(sliderValue4);
- websocket.send(sliderValue4);
- }
- *.html:
- <!DOCTYPE html>
- <html>
- <head>
- <title>ESP IOT DASHBOARD</title>
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/png" href="favicon.png">
- <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
- <link rel="stylesheet" type="text/css" href="style.css">
- </head>
- <body>
- <div class="topnav">
- <h1>ESP WEB SERVER</h1>
- </div>
- <div class="content">
- <div class="card-grid">
- <div class="card">
- <p class="card-title"><i class="fas fa-lightbulb"></i> GPIO 2</p>
- <p class="switch">
- <input type="range" oninput="updateSliderPWM(this)" id="pwmSlider" min="0" max="100" step="1" value ="0" class="slider">
- </p>
- <p class="state">Brightness: <span id="textSliderValue"></span> %</p>
- <p class="card-title"><i class="fas fa-lightbulb"></i> GPIO 4</p>
- <p class="switch">
- <input type="range" oninput="updateSliderPWM4(this)" id="pwmSlider4" min="0" max="100" step="1" value ="0" class="slider">
- </p>
- <p class="state">Brightness: <span id="textSliderValue4"></span> %</p>
- </div>
- </div>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
- *.ino
- /*********
- Rui Santos
- Complete instructions at https://RandomNerdTutorials.com/build-web-servers-ebook/
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
- *********/
- #include <Arduino.h>
- #include <WiFi.h>
- #include <AsyncTCP.h>
- #include <ESPAsyncWebServer.h>
- #include "SPIFFS.h"
- // Replace with your network credentials
- const char* ssid = "XXXX";
- const char* password = "XXXX";
- // Create AsyncWebServer object on port 80
- AsyncWebServer server(80);
- // Create a WebSocket object
- AsyncWebSocket ws("/ws");
- // Set LED GPIO
- const int ledPin = 2;
- const int ledPin4 = 4;
- // setting PWM properties
- const int freq = 5000;
- const int ledChannel = 0;
- const int resolution = 8;
- const int ledChannel4 = 0;
- String sliderValue = "0";
- String sliderValue4 = "0";
- int dutyCycle,dutyCycle4;
- // Initialize SPIFFS
- void initSPIFFS() {
- if (!SPIFFS.begin(true)) {
- Serial.println("An error has occurred while mounting SPIFFS");
- }
- Serial.println("SPIFFS mounted successfully");
- }
- // Initialize WiFi
- void initWiFi() {
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- Serial.print("Connecting to WiFi ..");
- while (WiFi.status() != WL_CONNECTED) {
- Serial.print('.');
- delay(1000);
- }
- Serial.println(WiFi.localIP());
- }
- void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
- AwsFrameInfo *info = (AwsFrameInfo*)arg;
- if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
- data[len] = 0;
- sliderValue = (char*)data;
- dutyCycle = map(sliderValue.toInt(), 0, 100, 0, 255);
- dutyCycle4 = map(sliderValue4.toInt(), 0, 100, 0, 255);
- Serial.print("dutyCycle Led 2:");
- Serial.println(dutyCycle);
- Serial.print("dutyCycle Led 4:");
- Serial.println(dutyCycle4);
- }
- }
- void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
- void *arg, uint8_t *data, size_t len) {
- switch (type) {
- case WS_EVT_CONNECT:
- Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
- break;
- case WS_EVT_DISCONNECT:
- Serial.printf("WebSocket client #%u disconnected\n", client->id());
- break;
- case WS_EVT_DATA:
- handleWebSocketMessage(arg, data, len);
- break;
- case WS_EVT_PONG:
- case WS_EVT_ERROR:
- break;
- }
- }
- void initWebSocket() {
- ws.onEvent(onEvent);
- server.addHandler(&ws);
- }
- void setup() {
- Serial.begin(115200);
- pinMode(ledPin, OUTPUT);
- pinMode(ledPin4, OUTPUT);
- initSPIFFS();
- initWiFi();
- // configure LED PWM functionalitites
- ledcSetup(ledChannel, freq, resolution);
- ledcSetup(ledChannel4, freq, resolution);
- // attach the channel to the GPIO to be controlled
- ledcAttachPin(ledPin, ledChannel);
- ledcAttachPin(ledPin4, ledChannel4);
- initWebSocket();
- // Web Server Root URL
- server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
- request->send(SPIFFS, "/index.html", "text/html");
- });
- server.serveStatic("/", SPIFFS, "/");
- server.on("/currentValue", HTTP_GET, [](AsyncWebServerRequest *request) {
- request->send(200, "/text/plain", String(sliderValue).c_str());
- });
- server.on("/currentValue4", HTTP_GET, [](AsyncWebServerRequest *request) {
- request->send(200, "/text/plain", String(sliderValue4).c_str());
- });
- // Start server
- server.begin();
- }
- void loop() {
- ledcWrite(ledChannel, dutyCycle);
- ledcWrite(ledChannel4, dutyCycle);
- ws.cleanupClients();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement