socket.js 5.78 KB
var net = require('net'),
    _ = require('lodash'),
    tagService = require('./tagService.js'),
    readerConfig = require('./readerConfig.js').getReaderConfig(),
    async = require('async'),
    WebSocketServer = require('ws').Server;

var r = require('./rfidRedis.js');
// 清除redis内存数据库数据
r.keys('*', function(err, keys){

    keys.forEach(function (key, pos)
    {
        r.del(key, function(err, o)
        {
            if (err)
            {
                console.error('没有' + key);
            }
            if (pos === (keys.length - 1))
            {
                console.log('redis内存数据清理成功');
            }
        });
    });
});

/**
 * socket服务创建模块
 */
function main()
{
    // 读取配置文件
    var host = '172.16.13.95',
        port = 12345;

    // 连接所有读写器
    tagService.connectAllReaders();

    var wss = new WebSocketServer({ host: host, port: port }, function(){
        console.log('Socket创建成功在%s:%d', host, port);
    });

    var terminals = [];
    wss.on('connection', function(ws) {
        var remoteIp = ws._socket.remoteAddress;
        console.log('远程主机%s连接成功', remoteIp);
        ws.on('message', function(data) {
            var tags = [];
            // 处理传过来的数据
            var params = getCommand(data);
            if(params.commandType === 'daemon') // 监控
            {
                var infos = {
                    readers: tagService.connectedReaders,
                    terminals: terminals,
                    redis: {
                        host: '127.0.0.1',
                        port: 6379,
                        status: r.connected,
                        used_memory: r.server_info.used_memory
                    }
                };

                ws.send(JSON.stringify(infos));
            }
            else if(params.commandType === 'restart') // 重启读写器
            {
                var reader = readerConfig[params.reader];
                console.log(reader);
                var filter = {
                    'on': '1',
                    rssi: reader.rssi
                };
                // 尝试重连5次
                async.retry(5, function(cb, results){
                    setTimeout(function(){
                        tagService.connectReader(params.reader, 9761, filter, reader.frequency, reader.inventory_time, reader.stay_time, reader.ants, reader.group, cb);
                    }, 3000);

                }, function(err, results){
                    if(err){
                        console.error(err);
                    }
                });
            }
            else
            {
                terminals.push({
                    name: remoteIp,
                    group: params.groupId
                });
                terminals = _.uniq(terminals, 'name');

                r.hget(params.groupId, params.state, function(err, epcs)
                {
                    if (err) {
                        console.error(err);
                    } else {
                        try
                        {
                            epcs = JSON.parse(epcs);
                            _.forEach(epcs, function(tagData){
                                if(tagData && getMillTimeDiffNow(tagData.updateTime) < 30000)
                                {
                                    console.log('groupId:%s ------- %s', tagData.GroupID, tagData.EPC);
                                    tags.push(tagData);
                                }
                            });
                        }
                        catch(er)
                        {
                            console.error('标签数据JSON格式错误:'+er);
                        }
                    }

                    // 有离架标签则记录日志
                    if(tags.length)
                    {
                        console.log(tags);
                    }

                    ws.send(output(params.commandType, 100, tags));
                });
            }
        });

        //连接关闭
        ws.onclose = function() {
            terminals = _.filter(terminals, function(termial){
                return termial.name !== remoteIp;
            });
            console.log('远程主机%s断开连接', remoteIp);
        }
    });
    wss.on('error', function(err){
        console.log(err);
        wss.close();
    });
}

/**
 * 获取指定时间和当前时间的差异
 * @param val 指定的时间
 * @returns int 时间差(单位:毫秒)
 */
function getMillTimeDiffNow(val)
{
    var end = new Date();
    return end.getTime() - val;
}

/**
 * 读取命令结果
 * @param {String} data 传入的数据
 * @returns {Object} 解析出来的数据对象
 */
function getCommand(data)
{
    try
    {
        data = JSON.parse(data);
    }
    catch(er)
    {
        console.log('JSON格式错误:'+er);
    }
    var params = {};

    if(data.Key != '123456')
    {
        params.commandType = 'error';
        return params;
    }

    params.commandType = data.CommandType;
    if('GroupID' in data)
    {
        params.groupId = data.GroupID;
    }

    if('state' in data)
    {
        var state = data.State;
        if(state == 'ShelfOn' || state == 'ShelfOnAndNear')
        {
            state = 'on'
        }
        else
        {
            state = 'off'
        }
        params.state = state;
    }
    if('reader' in data)
    {
        params.reader = data.reader;
    }

    return params;
}

/**
 * 格式化输出内容
 * @param commandType 命令类型
 * @param code 状态码
 * @param data 数据
 * @returns string
 */
function output(commandType, code, data)
{
    var res = {
        CommandType: commandType,
        Code: code,
        Data: data
    };

    return JSON.stringify(res);
}

main();