Controle de presença com Raspberry – Node js – Mysql – Socket.io – ACR122u

Agora vamos fazer a pagina para exibir o controle de acesso.

O arquivo sv-http.js é servidor http dentro da pasta rfid:

També é responsável por enviar para a pagina principal do nosso projeto o status de cada individuo registrado

sv-http.js

var app = require('http').createServer(handler),
 io = require('socket.io').listen(app),
 fs = require('fs'),
 mysql = require('mysql'),
 connectionsArray = [],
 connection = mysql.createConnection({
 host: 'servidor',
 user: 'root',
 password: '',
 database: 'database',
 port: 3306
 }),
 POLLING_INTERVAL = 50,
 pollingTimer;

//verifica se ha erros ao conectar com db
connection.connect(function(err) {
 // conectado!
 if (err) {
 console.log(err);
 }
});

// criando servidor ( localhost:8000 )
app.listen(8000);

function handler(req, res) {
 fs.readFile(__dirname + '/index.html', function(err, data) {
 if (err) {
 console.log(err);
 res.writeHead(500);
 return res.end('Error loading client.html');
 }
 res.writeHead(200);
 res.end(data);
 });
}

var pollingLoop = function() {
 // Doing the database query
 var datetime = Date.now();
 
 var query = connection.query('SELECT * FROM `grupo` WHERE (`count(``qty``)` % 2) = 0'),
 users = []; // aqui fica o conteudo da consulta
 
 query
 .on('error', function(err) { 
 // Handle error, and 'end' event will be emitted after this as well
 console.log(err);
 updateSockets(err);
 })
 .on('result', function(user) {
 // realizando o looping em cada linha da tabela
 users.push(user);
 })
 ////// Verificando Ausentes ////////
 
 var ausent = connection.query('SELECT * FROM `grupo` WHERE (`count(``qty``)` % 2) > 0'),
 us = []; 
 
 ausent
 .on('error', function(err) { 
 console.log(err);
 updateSockets(err);
 })
 .on('result', function(u) {
 us.push(u);
 })
 
 .on('end', function() {
 // loop on itself only if there are sockets still connected
 if (connectionsArray.length) {

 pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);

 updateSockets({
 users: users,
 us: us
 });
 } else {

 console.log('O servidor está parado pois não há ninguém conectado')

 }
 });
 
}
io.sockets.on('connection', function(socket) {

 console.log('Number of connections:' + connectionsArray.length);
 // começa o loping se alguém tiver conetado
 if (!connectionsArray.length) {
 pollingLoop();
 }
 socket.on('disconnect', function() {
 var socketIndex = connectionsArray.indexOf(socket);
 console.log('socketID = %s got disconnected', socketIndex);
 if (~socketIndex) {
 connectionsArray.splice(socketIndex, 1);
 }
 });

 console.log('A new socket is connected!');
 connectionsArray.push(socket);

});

var updateSockets = function(data) {
 // adding the time of the last update
 var currentdate = new Date(); 
var datetime = "Data: " + currentdate.getDate() + "/"
 + (currentdate.getMonth()+1) + "/" 
 + currentdate.getFullYear() + " Hora: " 
 + currentdate.getHours() + ":" 
 + currentdate.getMinutes() + ":" 
 + currentdate.getSeconds();
data.time = datetime;
 console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
 // envia dados para todos os websockets conectados
 connectionsArray.forEach(function(tmpSocket) {
 tmpSocket.volatile.emit('notification', data);
 });
};

console.log('Acesse o site em http://localhost:8000');

Ctrl + x , y e enter para salvar

Para testar digite dentro da pasta rfid:

~$ node sv-http

Se receber a mensagem “Acesse o site em http://localhost:8000″ é porque tudo esta ok… mas ainda não acabamos!!

7 opiniões sobre “Controle de presença com Raspberry – Node js – Mysql – Socket.io – ACR122u”

  1. То, что вы описываете — это нормальное явление. Вес может постоянно скакать туда-сюда на пару килограмм, например, за счёт воды. В то время, когда я избавлялся от лишнего веса, я постоянно с этим же сталкивался. Это как курс акций — он может колебаться вверх и вниз, но при правильном управлении будет расти. А вес при правильном питании — падать. Поэтому, кстати, часто рекомендуют взвешиваться не чаще, чем раз в месяц, чтобы не нервничать зря.
    fake cartier love bracelet pink

  2. Nice tutorial , but I am not familiar with the language in the tutorial , can you help me to translate into English or give me a source that is used in the project . thanks

    1. Dear Agus Winarta, how are you?
      Thanks for your comment!
      I’ll translate this tutorial (I believe, this tutorial can help more people if I publish in english) but it’s can spend some time. I’ll try start it next weekend and publish a new post in English.
      I’m free to help you if you liked this project. I’m not expert on node-js language, but we can learn more and more together.
      Best Regards,
      Pablo Binotto

      1. Dear Pablo Binotto, im fine
        nice to meet you Pablo, Thank for positive response
        I am interested in the project ACR 122u with rassbpery , if I have a problems I will ask to you , can you send your mail to my email address at aguswinartha@yahoo.com, thanks alot.
        Best Regards,
        Agus Winarta

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *