WebSocket communica...
 
Notifications
Clear all

WebSocket communication with an ESP8266 or Arduino in Python. Test with the ws4py library on Raspberry Pi


christophe
Posts: 251
Admin
Topic starter
(@chris)
Member
Joined: 4 years ago
wpf-cross-image

The Websocket is a much faster communication protocol than the REST protocol that uses standard HTTP requests. The Websocket allows to open a bi-directional communication channel between two devices. In this case, it will be between an ES8266 (but it could also be an Arduino or ESP32) and a Raspberry Pi 3. In this tutorial,…

2 Replies
0a4c3440c2ba5bf423de629c26bbc7c8?s=80&d=mm&r=g
Posts: 1
 Anthony Barnett
Guest
(@Anthony Barnett)
Joined: 3 years ago

Great tutorial and works even though I am a complete novice to all of this. Working on a Nodemcu apart from I have an exception error I need to track down - Exception (28):

Just to let you know a couple of your prints are missing the ( )

Reply
ce566c12b83abf723a1a9386a8d7c763?s=80&d=mm&r=g
Posts: 1
 Mayck Bernales
Guest
(@Mayck Bernales)
Joined: 3 years ago

I'm sure you can help me, this code is a small control of my house, it is supposed to turn on lights of my house is more works, but the problem is that when updating the page the color of the label is red again , but the led is still on, in addition to the other clients my son and wife, they can not see when I turn on or off the lights, they do not receive the data that I send to the webSocket, but if they can use it, I need the labels to be updated and all of us who are connected can see what someone else does, thank you very much for the help.

pleace help me, from chile.

ByR Hogar

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 &copy 2018 ¡Todos los derechos son para uso personal.!

http://javascript/reloj.js
http://javascript/index.js

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');
}
}

css----------------------------------------------------------------------------------

body {
display: flex;
background: rgba(186, 186, 199,.6);
margin: auto;
justify-content: center;
text-align: center;
max-width: 600px;
font-family: sans-serif;
}
h1{
margin: 5px;
display: flex;
flex-wrap: wrap;
justify-content: center;
color: #020972;
}
h3{
color: #781123;
font-weight: 600;
margin-bottom: 2px;
}
.contenedor{
width: 85%;
background: #E4A5A0;
padding: 3px;
}
hr{
height: 5px;
}
.enlaces{
width: 100%;
margin-bottom: -14px;
display: inline-block;
flex-wrap: wrap;
flex-flow:
}
a{
transition: all .2s;
float: right;
width: 52px;
margin-top: -4px;
margin-right: 2px;
height: auto;
color: #050C5D;
display: inline-block;
text-decoration: none;
text-align: center;
font-size: 14px;
font-weight: 600;
flex-direction: row;
flex-wrap: wrap;
border-radius: 3px;
padding: 8px;
}
a:hover{
background: rgba(231, 58, 137,.7);
}
.wrap{
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.accesorios{
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
width: 90%;
}
.accesorios h3{
width: 100%;
margin-bottom: 5px;
}
.temperatura{
width: 77%;
height: 85px;
margin: auto;
display: flex;
justify-content: space-around;
}
.temperatura label{
width: 75px;
height: 53px;
font-size: 24px;
background: #FFBAE3;
color: darkgreen;
margin-top: -12px;
padding: 0 2px;
border-top-left-radius: 55%;
border-top-right-radius: 55%;
}
.temperatura h3{
font-size: 13px;
margin-bottom: 20px;
}
.temp label{
margin-left: 7px;
}
input{
display: none;
}
label{
display: inline-block;
background: red;
color: #FDE4E4;
text-align: center;
border-radius: 5px;
cursor: pointer;
width: 80px;
height: 60px;
margin: 2px;
font-size: 70%;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
input[type="checkbox"]:checked + label{
background: rgba(48, 242, 0,.9);
color: black;
transition: all .1s;
}

h4{
color: #045508;
text-decoration-line: underline;
margin-top: 8px;
margin-bottom: 20px;
font-size: 14px;
}
p{
font-size: 11px;
color: rgba(0, 0, 0,.7);
justify-content: center;
margin-bottom: -5px;
}
footer{
font-size: 12px;
font-weight: 600;
margin-top: 25px;
}

arduino ide --esp8266------------------------------------------------

#include
#include
#include
#include
#include
#include

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, ...)rn", 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: %un", 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;
}

Reply
Share:
Join Us!
Recent Posts
Last Articles
DIY Projects
DIY Projects