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();
}
@moelect
Copy link

moelect commented Jun 15, 2016

bbx10, This bit of code works extremely well. I have been using it to control a large pump remotely. I have been hacking on it to no avail because I want to add a GPIO input that will control the web page status. For instance if the PSI gets too low the pump will shut down. Also I would like the web page to indicate whether the remote input is high or not. Any help would be greatly appreciated.
Thanks and good job.

@AnumSheraz
Copy link

Can we use " webSocket.sendTXT(num, "sometext..."); " on the basis of external interrupts i.e. gpio interrupts, internal variable state change ?. Because according to my observation, this code working procedure is similar to AJAX technique, where we are sending "ledon" or "ledoff" to server, and the server then responds back to all of the connected clients "line 123: webSocket.broadcastTXT(payload, length);". And yes I can see that initially when the new client is connected, a message is send indicating the initial state of the LED. but I want to sent random stuff to client when ever I want, How can I do that ? I've tried to use the webSocket.sendTXT from outside of the " case WStype_CONNECTED:", but it throws errors.

@winduajiprasetiyo
Copy link

thanks bbx10, ur code work but please help, i cant Access http://espWebSock.local, only esp8266 local IP that can connected.
and how we know wich esp8266 that controlled if we have more than 10 esp8266

@silbo
Copy link

silbo commented Dec 27, 2016

typo on line #156 ?
just send instead of send_P ?

@boblasure
Copy link

Is there a way to use a slider input and control the brightness of led with pwm?

@ChromiumPosphate
Copy link

ignore me but, an LED ?

@bbx10
Copy link
Author

bbx10 commented Jan 23, 2017

@Silps you are correct. send_P is needed when sending INDEX.HTML because it is in PROGMEM. But it is not needed to send a normal string constant.

@mega-hz
Copy link

mega-hz commented Jan 23, 2017

I had running a IO-Webserver on an Arduino Uno with Ethernet, now i have to translate it to an ESP8266 Node Mcu Board.
My first try, replaceing all Ethernetxxxxx to WiFiClient was nearly NOT running, only sometimes and very slow.
So i tryed the ESP Webserver wich runs much better.
I need help to make this Routine work with the <ESP8266WebServer.h>:

**`void loop()
{
EthernetClient client = server.available(); // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {

digitalWrite(9,HIGH);
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
// limit the size of the stored received HTTP request
// buffer first part of HTTP request in HTTP_req array (string)
// leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
if (req_index < (REQ_BUF_SZ - 1)) {
HTTP_req[req_index] = c; // save HTTP request character
req_index++;
}
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
// remainder of header follows below, depending on if
// web page or XML page is requested
// Ajax request - send XML file
if (StrContains(HTTP_req, "ajax_inputs")) {
// send rest of HTTP header
Serial.print("ajax_inputs");
client.println("Content-Type: text/xml");
client.println("Connection: keep-alive");
client.println();
SetLEDs();
// send XML file containing input states
XML_response(client);
}
else { // web page request
// send rest of HTTP header
Serial.print("text/html");
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
// send web page
webFile = SD.open("web-io.htm"); // open web page file
if (webFile) {
while(webFile.available()) {
client.write(webFile.read()); // send web page to client
}
webFile.close();
}
}
// display received HTTP request on serial port
Serial.print(HTTP_req);
// reset buffer index and all buffer elements to 0
req_index = 0;
StrClear(HTTP_req, REQ_BUF_SZ);

                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            } 
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(5);      // give the web browser time to receive the data
    client.stop(); // close the connection

digitalWrite(9,LOW);
} // end if (client)
}

// checks if received HTTP request is switching on/off LEDs
// also saves the state of the LEDs
void SetLEDs(void)
{
char str_on[12] = {0};
char str_off[12] = {0};
unsigned char i;
unsigned int j;
int LED_num = 0;

for (i = 0; i < 4; i++) {
    for (j = 1; j <= 0x80; j <<= 1) {
        sprintf(str_on,  "LED%d=%d", LED_num, 1);
        sprintf(str_off, "LED%d=%d", LED_num, 0);
        if (StrContains(HTTP_req, str_on)) {
            LED_state[i] |= (unsigned char)j;  // save LED state
            bitSet(Outputs,LED_num);
            shiftOut32(Outputs);
        }
        else if (StrContains(HTTP_req, str_off)) {
            LED_state[i] &= (unsigned char)(~j);  // save LED state
            bitClear(Outputs,LED_num);
            shiftOut32(Outputs);
        }
        LED_num++;
    }
}

}

// send the XML file with analog values, switch status
// and LED status
void XML_response(EthernetClient cl)
{
unsigned char i;
unsigned int j;
unsigned analog_val;

cl.print("<?xml version = \"1.0\" ?>");
cl.print("<inputs>");
for (i = 0; i < 4; i++) {
    for (j = 1; j <= 0x80; j <<= 1) {
        cl.print("<LED>");
        if ((unsigned char)LED_state[i] & j) {
            cl.print("checked");
        }
        else {
            cl.print("unchecked");
        }
        cl.println("</LED>");
    }
}

shiftIn32();

for( uint8_t i = 0; i<32; i++ )
{
cl.print("");
if (Input[i])
{
cl.print("checked");
}
else {
cl.print("unchecked");
}
cl.println("");
}

cl.print("</inputs>");

}

// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
for (int i = 0; i < length; i++) {
str[i] = 0;
}
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
char found = 0;
char index = 0;
char len;

len = strlen(str);

if (strlen(sfind) > len) {
    return 0;
}
while (index < len) {
    if (str[index] == sfind[found]) {
        found++;
        if (strlen(sfind) == found) {
            return 1;
        }
    }
    else {
        found = 0;
    }
    index++;
}

return 0;

}**
`
can anyone help me getting this running?

Wolfram.

@DIYman
Copy link

DIYman commented Jan 24, 2017

That really helped me a lot thanks
Also if you want to use your esp as Access Point (when you connect to esp itself instead of a working wifi) you should modify the code a little.
I got a working copy down here
As you can see after you build and upload the code you will connect to the device (tunc5555) using 123456789 as password of course you can change the name and password

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#define USE_SERIAL Serial

static const char ssid[] = "tunc5555";
static const char password[] = "123456789";
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 = 4;
// 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)
{
	USE_SERIAL.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
	switch (type) {
	case WStype_DISCONNECTED:
		USE_SERIAL.printf("[%u] Disconnected!\r\n", num);
		break;
	case WStype_CONNECTED:
	{
							 IPAddress ip = webSocket.remoteIP(num);
							 USE_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:
		USE_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 {
			USE_SERIAL.println("Unknown command");
		}
		// send data to all connected clients
		webSocket.broadcastTXT(payload, length);
		break;
	case WStype_BIN:
		USE_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:
		USE_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);

	USE_SERIAL.begin(115200);

	//Serial.setDebugOutput(true);

	USE_SERIAL.println();
	USE_SERIAL.println();
	USE_SERIAL.println();

	for (uint8_t t = 4; t > 0; t--) {
		USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\r\n", t);
		USE_SERIAL.flush();
		delay(1000);
	}

//	WiFiMulti.addAP(ssid, password);
//
//	while (WiFiMulti.run() != WL_CONNECTED) {
//		Serial.print(".");
//		delay(100);
//	}

	WiFi.softAP(ssid, password);
	IPAddress myIP = WiFi.softAPIP();
	USE_SERIAL.print("AP IP address: ");
	USE_SERIAL.println(myIP);

	USE_SERIAL.println("");
	USE_SERIAL.print("Connected to ");
	USE_SERIAL.println(ssid);
	USE_SERIAL.print("IP address: ");
	USE_SERIAL.println(WiFi.localIP());

	if (mdns.begin("espWebSock", WiFi.localIP())) {
		USE_SERIAL.println("MDNS responder started");
		mdns.addService("http", "tcp", 80);
		mdns.addService("ws", "tcp", 81);
	}
	else {
		USE_SERIAL.println("MDNS.begin failed");
	}
	USE_SERIAL.print("Connect to http://espWebSock.local or http://");
	USE_SERIAL.println(WiFi.localIP());

	server.on("/", handleRoot);
	server.onNotFound(handleNotFound);

	server.begin();

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

void loop()
{
	webSocket.loop();
	server.handleClient();
}

@romuye123
Copy link

This code works but has limitations of number of clients connecting to it depending on the memory of ESP8266

@jeancode
Copy link

= R"rawliteral es verdad que esto se puede usar en esp8266?

@fl164
Copy link

fl164 commented Feb 4, 2018

Hello,

Thank you very much for this code from wich I learnt a lot.

If you replace the 2 buttons by only one and a blink function with a "delay" (millis) : do you think it's possible to get the status "ledon" only during the blinking (and so the text going to red then black) without any button action ?

I did it but i'm not able to "force" the status back without clic on the button.

Thanks in advance for your help

@bfdacosta
Copy link

I`m doing some three-way switching.
So actually, I wanna send to all my client that the light has changed it state due some interrupt on gpio.
I Think AnumSheraz already asked that (2 years ago).

So is there a way of sending like ledoff to a websocket when a I turn a GPIO interrupt occours, instead of using the web browser.

I thinkl somehow I would start an event or somthing like that.

I appreciate the help.

Thanks,
Bruno Costa

@jbaben
Copy link

jbaben commented Feb 16, 2018

Hello,
when compiling the sketch, I get the following message: Arduino\libraries\Arduino-Websocket-master\sha1.cpp:2:20: fatal error: avr/io.h: No such file or directory #include <avr/io.h>
Io.h does not exist in Path: c: \ Arduino \ hardware \ tools \ avr
Which library must I install ?

Kind Regards
Juergen B.

@mbenitez01
Copy link

flies like a charm!!! thanks for this awesome -compact- piece of software!!!

@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