daemon.js 1.68 KB
var events = require('events'),
    async = require('async'),
    util = require('util'),
    _ = require('lodash'),
    tagService = require('./tagService.js'),
    readerConfig = require('./readerConfig.js').getReaderConfig();

/**
 * 通过edgejs控制RFID模块
 * 继承EventEmitter内部模块,然后调用emit和on的方式去监听
 * 读写器信息的变化
 *
 * @example new Daemon();
 */
function Daemon()
{
    events.EventEmitter.call(this);

    this.readers = [];

    // 监听重连事件
    this.on('reconnect', function(host){
        tagService.connectedReaders = _.forEach(tagService.connectedReaders, function(reader){
            if(reader.name === host)
            {
                reader.status = false;
                reader.restartTimes++;
            }
        });

        var checkedReader = _.findWhere(tagService.connectedReaders, {name: host});
        if(checkedReader !== undefined && checkedReader.restartTimes === 1) // 只自动重连一次
        {
            var reader = readerConfig[host];
            var filter = {
                'on': '1',
                rssi: reader.rssi
            };
            // 尝试重连5次
            async.retry(5, function(cb, results){
                console.log(results);
                setTimeout(function(){
                    tagService.connectReader(host, 9761, filter, reader.frequency, reader.inventory_time, reader.stay_time, reader.ants, reader.group, cb);
                }, 3000);

            }, function(err, results){
                if(err){
                    console.error(err);
                }
            });
        }

    });
}

util.inherits(Daemon, events.EventEmitter);

module.exports = new Daemon();