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

Prosseguindo com o nosso projeto crie no mysq o banco de dados database as tabelas usando as configurações abaixo:


CREATE TABLE IF NOT EXISTS `ck` (
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`evento` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`qty` int(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

CREATE TABLE IF NOT EXISTS `event` (
 `nome` varchar(100) DEFAULT NULL,
 `foto` varchar(100) DEFAULT NULL,
 `rfid` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `dept` varchar(20) NOT NULL,
 `turno` varchar(10) NOT NULL,
 `divi` varchar(1) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
 `Qty` int(1) NOT NULL DEFAULT '1',
 `fone` varchar(30) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
 `email` varchar(50) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `coutbyid` AS select `ck`.`evento` AS `evento`,count(`ck`.`qty`) AS `count(``qty``)` from `ck` group by `ck`.`evento`;
 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `grupo` AS select `event`.`rfid` AS `rfid`,`event`.`foto` AS `foto`,`event`.`nome` AS `nome`,`event`.`turno` AS `turno`,`event`.`divi` AS `divi`,`event`.`dept` AS `dept`,`coutbyid`.`count(``qty``)` AS `count(``qty``)` from (`event` join `coutbyid` on((`event`.`rfid` = `coutbyid`.`evento`))) order by `event`.`nome`; 
Dentro da pasta  A-PRESENCE-CONTROL você vai encontrar os segintes arquivos

 new.js responsável em realizar a comunicação com o DB e salvar os dados das tasgs quando aproximadas do leitor


'use strict';
var pcsc = require('pcsclite');
var mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host : 'servidor',
user : 'user',
password : '123456',
database : 'database'
});

// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
 if (err) {
 console.log(err);
 }
});

var pcsc = pcsc();
// PC/SC interface.
pcsc.on('reader', function(reader) {
console.log('Reader detected:', reader);
reader.on('error', function(err) {
console.log('Error(', reader.name, '):', err.message);
});
reader.on('status', function(status) {
console.log('Status(', reader.name, '):', status);
// Check changes.
var changes = this.state ^ status.state;
if (changes) {
// Card removed.
if ((changes & this.SCARD_STATE_EMPTY) && (status.state & this.SCARD_STATE_EMPTY)) {
console.log('Status(', reader.name, '): Card removed');
reader.disconnect(reader.SCARD_LEAVE_CARD, function(err) {
if (err) {
console.log('Error(', reader.name, '):', err);
}
else {
console.log('Status(', reader.name, '): Disconnected');
}
});
}
// Card inserted.
else if ((changes & this.SCARD_STATE_PRESENT) && (status.state & this.SCARD_STATE_PRESENT)) {
console.log('Status(', reader.name, '): Card inserted');
reader.connect({ share_mode : this.SCARD_SHARE_SHARED }, function(err, protocol) {
if (err) {
console.log('Error(', reader.name, '):', err);
}
else {
console.log('Protocol(', reader.name, '):', protocol);
/*
Read card UID: [0xFF, 0xCA, 0x00, 0x00, 0x00]
UID is specified in the ISO 14443 T=CL transport protocol while APDU's are specified in the ISO 7816 application layer protocol.
"Get Data Command" is defined in PCSC 3 v2. If your driver is PCSC v2 compliant, you can get UID using it:
Class = 0xFF
INS = 0xCA
P1 = 0x00
P2 = 0x00
Le = 0x00 (return full length: ISO14443A single 4 bytes, double 7 bytes, triple 10 bytes, for ISO14443B 4 bytes PUPI, for 15693 8 bytes UID)
Expected response: Data+SW1SW2
*/
var message = new Buffer([0xFF, 0xCA, 0x00, 0x00, 0x00]);
reader.transmit(message, 40, protocol, function(err, data) {
if (err) {
console.log('Error(', reader.name, '):', err);
} else {
/* buf.readUIntLE(offset, byteLength[, noAssert])
Set noAssert to true to skip validation of value and offset. Defaults to false.
*/
var lastRead = data.readUIntBE(0, 6, true).toString(16);
var post = {evento: lastRead};
var sql = connection.query('SELECT COUNT (*) AS tt FROM `event` WHERE `rfid` = ?', lastRead, function(err, rows, results){
if (err)throw err;
if (rows[0].tt < 1){
console.log(lastRead + ' Nao resgistrado');
}else{
var query = connection.query('INSERT INTO ck SET ?', post, function(err, resuslt){
});
console.log(query.sql);
}
});
console.log('Status(', reader.name, '): Read:', data, ' toString:', lastRead);
}
});
}
});
}
}
});

reader.on('end', function() {
console.log('Status(', reader.name, '): Removed');

// Release resources.
reader.close();
pcsc.close();
});
});
pcsc.on('error', function(err) {
console.log('Error( PCSC ): ', err);
});

Se você criou a base de dados e as tabelas, digite para testar:

~$ node new

Aproxime a tag rfid do leitor ACR122u se receber a mensagem “Número RFID + Nao registrado”, é porque tudo esta funcionando perfeitamente.

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 *