connector.js 2.36 KB
/**
 * @fileOverview 读写器连接客户端连接器类
 * @author qiqi.zhou@yoho.cn
 */
import net from 'net';
import orders from './interface';
import events from 'events';
import {
    log, toHex, spliteRet, locateOrder
}
from './util';

/**
 * @class 连接器
 * @extends {EventEmitter}
 * @module Connector
 * @member {Socket} client
 * @member {Array} orderMq
 * @description 连接到读写器端
 */
class Connector extends events.EventEmitter {

    /**
     * socket 客户端初始化
     * @param  {Object} config 配置
     * @param  {Function} send 发送的回调
     * @param  {Function} receive 接收的回调
     * @return {void} 无返回
     */
    constructor(config, send, receive) {
        super();
        this.connected = false;
        this.orderMq = [];
        this.client = new net.Socket();
        let client = this.client;
        let that = this;

        //初始化
        client.connect(config.port, config.host, function() {
            that.connected = true;
            log.info(config.host + ':' + config.port + ':读写器连接成功!');
            send();
        });


        //接收数据
        client.on('data', function(data) {

            let arr = toHex(data),
                rets = spliteRet(that.orderMq, arr),
                orderName = '',
                returnData = {};
            that.orderMq = rets.mq;
            for (let i = 0; i < rets.rets.length; i++) {

                orderName = locateOrder(orders, rets.rets[i]).name; //指令名称
                returnData = receive(client, rets.rets[i]); //接收返回

                that.emit(orderName, returnData); //触发接收数据的指令事件
            }
        });

        //异常处理
        client.on('error', function(error) {
            log.error('错误:' + error.code);

            // 读写器连接错误或者突然断开
            this.connected = false;

            client.destroy();
            receive(client, null, error);
        });

        client.on('close', function() {
            log.info('读写器连接断开');
            // 触发重连事件
            that.emit('reconnect');
        });
    }
    send(sendOrder) {
        this.orderMq.push(sendOrder.substr(0, 2).toLowerCase());
        let call = new Buffer(sendOrder, 'hex');
        this.client.write(call);
    }
}

/**
 * @exports lib/Connector
 */
export default Connector;