Skip to content

Instantly share code, notes, and snippets.

@bbx10
Last active March 3, 2023 22:13
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 26 You must be signed in to fork a gist
  • Save bbx10/667e3d4f5f2c0831d00b to your computer and use it in GitHub Desktop.
Save bbx10/667e3d4f5f2c0831d00b to your computer and use it in GitHub Desktop.
ESP8266 Web server with Web Socket to control an LED
/*
* ESP8266 Web server with Web Socket to control an LED.
*
* The web server keeps all clients' LED status up to date and any client may
* turn the LED on or off.
*
* For example, clientA connects and turns the LED on. This changes the word
* "LED" on the web page to the color red. When clientB connects, the word
* "LED" will be red since the server knows the LED is on. When clientB turns
* the LED off, the word LED changes color to black on clientA and clientB web
* pages.
*
* References:
*
* https://github.com/Links2004/arduinoWebSockets
*
*/
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
static const char ssid[] = "********";
static const char password[] = "***************";
MDNSResponder mdns;
static void writeLED(bool);
ESP8266WiFiMulti 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>ESP8266 WebSocket Demo</title>
<style>
"body { background-color: #808080; 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('ledstatus');
if (evt.data === 'ledon') {
e.style.color = 'red';
}
else if (evt.data === 'ledoff') {
e.style.color = 'black';
}
else {
console.log('unknown event');
}
};
}
function buttonclick(e) {
websock.send(e.id);
}
</script>
</head>
<body onload="javascript:start();">
<h1>ESP8266 WebSocket Demo</h1>
<div id="ledstatus"><b>LED</b></div>
<button id="ledon" type="button" onclick="buttonclick(this);">On</button>
<button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
</body>
</html>
)rawliteral";
// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 0;
// Current LED status
bool LEDStatus;
// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
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);
// Send the current LED status
if (LEDStatus) {
webSocket.sendTXT(num, LEDON, strlen(LEDON));
}
else {
webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
}
}
break;
case WStype_TEXT:
Serial.printf("[%u] get Text: %s\r\n", num, payload);
if (strcmp(LEDON, (const char *)payload) == 0) {
writeLED(true);
}
else if (strcmp(LEDOFF, (const char *)payload) == 0) {
writeLED(false);
}
else {
Serial.println("Unknown command");
}
// 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()
{
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
static void writeLED(bool LEDon)
{
LEDStatus = LEDon;
// Note inverted logic for Adafruit HUZZAH board
if (LEDon) {
digitalWrite(LEDPIN, 0);
}
else {
digitalWrite(LEDPIN, 1);
}
}
void setup()
{
pinMode(LEDPIN, OUTPUT);
writeLED(false);
Serial.begin(115200);
//Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
for(uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password);
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("espWebSock", WiFi.localIP())) {
Serial.println("MDNS responder started");
mdns.addService("http", "tcp", 80);
mdns.addService("ws", "tcp", 81);
}
else {
Serial.println("MDNS.begin failed");
}
Serial.print("Connect to http://espWebSock.local or http://");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop()
{
webSocket.loop();
server.handleClient();
}
@dianamichel
Copy link

sorry I need help with de code, this work but no is actualizer, sorry I no speeck english so much.
arduino y nodemcu esp8266
#include <esp8266wifi.h>
#include <wificlient.h>
#include <esp8266webserver.h>
#include <websocketsserver.h>
#include <hash.h>
#include <fs.h>

const char *ssid = "Diana michel";
const char *password = "020587270572";

bool StatusComedor;

const char COMEDOR_ON[]= "1";
const char COMEDOR_OFF[]="0";

int16_t thisRead = 0;
int16_t lastRead = 0;
uint8_t counter = 0;

WebSocketsServer webSocket = WebSocketsServer(81);
ESP8266WebServer server(80);

void setup(void){
delay(1000);

Serial.begin(115200);

pinMode(16, OUTPUT);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
pinMode(0, OUTPUT);
pinMode(2, OUTPUT);
pinMode(12, OUTPUT);
pinMode(15, OUTPUT);
pinMode(3, OUTPUT);

WiFi.begin(ssid, password);
Serial.println("Iniciando conexión a modem infinitum");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
IPAddress myIP = WiFi.localIP();
Serial.println("");
Serial.print("Direccion IP: ");
Serial.println(myIP);

SPIFFS.begin();

webSocket.begin();
webSocket.onEvent(webSocketEvent);

server.onNotFound({
if(!handleFileRead(server.uri()))
server.send(404, "text/plain", "FileNotFound");
});
server.begin();
Serial.println("Servidor web iniciado");
}
void loop() {
webSocket.loop();
server.handleClient();

counter++;
if(counter == 255) {
counter=0;
thisRead = map(analogRead(A0), 900, 20, 0, 100);

if (thisRead > 100) thisRead = 100;
if(thisRead < 0) thisRead = 0;

if (thisRead != lastRead){
String message = String(thisRead);
webSocket.broadcastTXT(message);
}
lastRead = thisRead;
}
}
//FUNCION PROPIA DEL OBJETO WEBSOCKET
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
switch(type) {
// CASO CUANDO SE DESCONECTA UN USUARIO DEL WEBSOCKET
case WStype_DISCONNECTED: {
Serial.printf("Usuario #%u - Desconectado!\n", num);
break;
}
case WStype_CONNECTED: {
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("Conexión establecida desde la IP: %d.%d.%d.%d Nombre: %s url: %u\n", ip[0], ip[1], ip[2], ip[3], payload, num);
if(StatusComedor==true){
webSocket.sendTXT(num, COMEDOR_ON, strlen(COMEDOR_ON));
}else if(StatusComedor==false){
webSocket.sendTXT(num, COMEDOR_OFF, strlen(COMEDOR_OFF));
}

String message = String(lastRead);
webSocket.broadcastTXT(message);
break;
}
case WStype_TEXT: {
String incoming = "";
for (int i = 0; i < lenght; i++) {
incoming.concat((char)payload[i]);
}
Serial.print(incoming);
Serial.println("");
uint8_t valor = incoming.toInt();
if(valor==1){
digitalWrite(16, HIGH);
StatusComedor=true;
}else if(valor==0){
digitalWrite(16, LOW);
StatusComedor=false;
}

uint8_t valor2 = incoming.toInt();
if(valor2==3){
digitalWrite(5, HIGH);
}else if(valor2==2){
digitalWrite(5, LOW);
}

uint8_t valor3 = incoming.toInt();
if(valor3==5){
digitalWrite(4, HIGH);
}else if(valor3==4){
digitalWrite(4, LOW);
}

uint8_t valor4 = incoming.toInt();
if(valor4==7){
digitalWrite(0, HIGH);
}else if(valor4==6){
digitalWrite(0, LOW);
}

uint8_t valor5 = incoming.toInt();
if(valor5==9){
digitalWrite(2, HIGH);
}else if(valor5==8){
digitalWrite(2, LOW);
}

uint8_t valor6 = incoming.toInt();
if(valor6==11){
digitalWrite(14, HIGH);
}else if(valor6==10){
digitalWrite(14, LOW);
}

uint8_t valor7 = incoming.toInt();
if(valor7==13){
digitalWrite(12, HIGH);
}else if(valor7==12){
digitalWrite(12, LOW);
}

uint8_t valor8 = incoming.toInt();
if(valor8==15){
digitalWrite(15, HIGH);
}else if(valor8==14){
digitalWrite(15, LOW);
}

uint8_t valor9 = incoming.toInt();
if(valor9==17){
digitalWrite(3, HIGH);
}else if(valor9==16){
digitalWrite(3, LOW);
}
break;
}
}
}

// A function we use to get the content type for our HTTP responses
String getContentType(String filename){
if(server.hasArg("download")) return "application/octet-stream";
else if(filename.endsWith(".htm")) return "text/html";
else 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(".png")) return "image/png";
else if(filename.endsWith(".gif")) return "image/gif";
else if(filename.endsWith(".jpg")) return "image/jpeg";
else if(filename.endsWith(".ico")) return "image/x-icon";
else if(filename.endsWith(".xml")) return "text/xml";
else if(filename.endsWith(".pdf")) return "application/x-pdf";
else if(filename.endsWith(".zip")) return "application/x-zip";
else if(filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
// Takes a URL (for example /index.html) and looks up the file in our file system,
// Then sends it off via the HTTP server!
bool handleFileRead(String path){
#ifdef DEBUG
Serial.println("handleFileRead: " + path);
#endif
if(path.endsWith("/")) path += "index.html";
if(SPIFFS.exists(path)){
File file = SPIFFS.open(path, "r");
size_t sent = server.streamFile(file, getContentType(path));
file.close();
return true;
}
return false;
}
html......

<title>ByR Hogar</title>

ByR Control Hogar


RADIO TV Camara

CONTROL DE LUCES

COMEDOR
ALACENA
DORMITORIO LAMPARA
BAÑO TOCADOR

CONTROL DE ACCESORIOS

CALEFACTOR
PUERTA
VENTILADOR

TEMPERATURA

24°C

HUMEDAD

28 %

TECNOLOGIA Y HOGAR

Gracias a la tecnología cada uno de nuestros artefactos eléctricos y electrónicos, en la actualidad los podemos controlar de manera inalámbrica, ya sea por "Control remoto, Bluetooth, Wifi", y hoy lo podemos hacer via internet; Gracias al "Internet de las cosas(IOT)", y una tecnología muy indispensable, como lo es "WebSocket". Diseñado por Michel Bernales © 2018 ¡Todos los derechos son para uso personal.!
<script type="text/javascript" src="javascript/reloj.js"></script> <script type="text/javascript" src="javascript/index.js"></script>

javascript.....

var Socket = new WebSocket('ws://' + window.location.hostname + ':81');
Socket.onopen = function(evt) {
console.log('Conexión abierta' + new Date());
};
Socket.onclose = function(evt) {
console.log('Conexión cerrada');
};
Socket.onerror = function(evt) {
console.log(evt.data);
};
Socket.onmessage = function(evt){
console.log(evt);

var c=document.getElementById('StatusComedor');
if (StatusComedor==true) {
c.style.background='#2DB30B';
}else if(StatusComedor==false){
c.style.background='red';
}
};

function enviarComedor(c){
Socket.send(c.id);
}
function enviarComedor() {
var e=document.getElementById('comedor');
if(e.checked==true){
Socket.send('1');
}else if(e.checked==false){
Socket.send('0');
}
}
function enviarAlacena(){
var e=document.getElementById('alacena');
if(e.checked==true){
Socket.send('3');
}else if(e.checked==false){
Socket.send('2');
}
}
function enviarDormitorio(){
e=document.getElementById('dormitorio');
if(e.checked==true){
Socket.send('5');
}else if(e.checked==false){
Socket.send('4');
}
}
function enviarLampara(){
e=document.getElementById('lampara');
if(e.checked==true){
Socket.send('7');
}else if(e.checked==false){
Socket.send('6');
}
}
function enviarBaño(){
e=document.getElementById('baño');
if(e.checked==true){
Socket.send('9');
}else if(e.checked==false){
Socket.send('8');
}
}
function enviarTocador(){
e=document.getElementById('tocador');
if(e.checked==true){
Socket.send('11');
}else if(e.checked==false){
Socket.send('10');
}
}
function enviarCalefactor(){
e=document.getElementById('calefactor');
if(e.checked==true){
Socket.send('13');
}else if(e.checked==false){
Socket.send('12');
}
}
function enviarPuerta(){
e=document.getElementById('puerta');
if(e.checked==true){
Socket.send('15');
}else if(e.checked==false){
Socket.send('14');
}
}
function enviarVentilador(){
e=document.getElementById('ventilador');
if(e.checked===true){
Socket.send('17');
}else if(e.checked==false){
Socket.send('16');
}
}
como veras el codigo, te comento q funciona pero al momento de cargar la pag, vuelve al estado de apagado el boton y color rojo
los demas clientes no ven el estado q otro ejecuta, necesito ayuda soy novato, muchas gracias amigo en lo que me puedas ayudar.

@wlvish22
Copy link

Hello,

Thanks for the websocket program to control the LED.

I have used same code to control the LED, but faced issues when two command are sent immediately one after the other. We noticed the second command gets executed first and first command later. For example, if client sent LED_ON and LED-OFF command then led remains ON till we fire any next command. We are using same 'strcmp' function to compare the text with the payload.
If we send single command everything works fine.
Any help relative to above would be highly appreciated.

Thanks,
VishP

@r0n0x
Copy link

r0n0x commented Feb 28, 2020

hi, your code causes errors, i think you might have accientally made a mistake during a revision, across all browsers the javascript locks out because "SyntaxError: An invalid or illegal string was specified" reffering to line 12 websock = new WebSocket('ws://' + window.location.hostname + ':81/');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment