Last active
January 6, 2023 14:08
-
-
Save iddar/90ecd3c3d54bd028aa97 to your computer and use it in GitHub Desktop.
Prueba de socket.io + serialport para la lectura de sensores en tiempo real.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
var http = require('http').Server(app); | |
var io = require('socket.io')(http); | |
var serialport = require("serialport"); | |
var SerialPort = serialport.SerialPort; | |
// Constantes | |
// el valor SERIALPORT varia puedes usar como referencia el puerto | |
// que selecionaste al programar tu arduino, | |
// en windows solo deves indicar COM y el numero en el que se listo ej: COM3 | |
var SERIALPORT = '/dev/tty.usbserial-A9007WoZ'; // PATH del puerto serial | |
var WEBPORT = 3000; // Puerto en el que escucha el servidor web | |
// Inicializa la conexión con el puerto serial | |
var SerialPort = new SerialPort(SERIALPORT, { | |
baudrate: 9600, | |
parser: serialport.parsers.readline("\n") | |
}); | |
// onDataCallback: Emite el evento 'sensor' y adjunta el valor del sensor | |
// params: | |
// serialLine: buffer | |
function onDataCallback (serialLine){ | |
// convierte el serialLine en un objeto JSON | |
var data = JSON.parse(serialLine.toString()); | |
console.log(data.sensor); | |
io.emit('sensor', data.sensor); | |
} | |
// Event onData | |
SerialPort.on('data', onDataCallback); | |
// getRootCallback: Envia el archivo index.html al usuario | |
// params: | |
// req: request object | |
// res: response object | |
function getRootCallback(req, res){ | |
res.sendfile('index.html'); | |
} | |
// GET /: Crea la ruta '/' y lanza un callback | |
app.get('/', getRootCallback); | |
// Event onConnection: Crea el eventListener y nos indica cuando un | |
// usuario se conecta o desconecta | |
io.on('connection', function onConnection(socket) { | |
console.log('Se a conectado un usuario :)'); | |
// Event onDisconnect | |
socket.on('disconnect', function onDisconnect() { | |
console.log('El usuario se desconecto :('); | |
}); | |
}); | |
// Crea el servidor y define el puerto en el que escucha | |
http.listen(WEBPORT, function serverStart() { | |
console.log(WEBPORT); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Domotic Panel</title> | |
<style> | |
* { | |
border: 0; | |
margin: 0; | |
padding: 0; | |
font-family: helvetica, monospace; | |
color: #FF794D; | |
font-size: 1.2em; | |
} | |
body { | |
background: #FFFF9D; | |
} | |
.graph { | |
height: 85vh; | |
background: #79BD8F; | |
width: 30%; | |
} | |
.button { | |
display: table-cell; | |
height: 15vh; | |
text-decoration: none; | |
background: #FFFF9D; | |
text-align: center; | |
vertical-align: middle; | |
width: 100vw; | |
transition: background .5s; | |
} | |
.button:hover { | |
background: #BEEB9F; | |
} | |
</style> | |
<script src="/socket.io/socket.io.js"></script> | |
</head> | |
<body> | |
<a href="#" class="button">No te atreves a tocarme</i></a> | |
<div class="graph"></div> | |
<script> | |
var socket = io(); // Creamos la conexion con el servidor | |
// Selecciona los elementos del DOM | |
var $graph = document.querySelector('.graph'); | |
var $button = document.querySelector('.button'); | |
// Evento onSensor: Crea el eventListener y nos indica cuando un | |
socket.on('sensor', function onSensorCallback(width) { | |
// var width = (value * 100) / 1023; | |
$graph.style.width= width + "%"; | |
}); | |
$button.addEventListener("click", function (){ | |
socket.emit('buttonpress', 'bu!'); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int valorActual; | |
int valorAnterior = 0; | |
void setup() { | |
Serial.begin(9600); | |
} | |
void loop() { | |
//Lee el valor del puerto analogo | |
valorActual = analogRead(A2); | |
// Mapea el valor leido a un intervalo de 0 a 100 | |
valorActual = map(valorActual, 0, 1023, 0, 100); | |
// lomita el rango del resultado | |
valorActual = constrain(valorActual, 0, 100); | |
// Se envian los datos solo cuando la lectura es diferente | |
if(valorActual != valorAnterior){ | |
if( valorActual > valorAnterior + 1 || valorActual < valorAnterior - 1 ){ | |
// Imprimo una cadena con formato JSON | |
Serial.print("{\"sensor\":"); | |
Serial.print( valorActual ); | |
Serial.print("}\n"); | |
valorAnterior = valorActual; | |
} | |
} | |
delay(10); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "Test-Socket.io", | |
"version": "0.0.1", | |
"description": "my first socket.io app", | |
"dependencies": { | |
"express": "4.9.5", | |
"serialport": "1.4.6", | |
"socket.io": "1.1.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment