connector.js 1.69 KB
import net from 'net';
import orders from './interface';
import events from 'events';
import {
    log, toHex, spliteRet, locateOrder
}
from './util';

/**
 * 连接器
 * 连接到读写器端
 */
class Connector extends events.EventEmitter {

    constructor(config, send, receive) {
        super();
        this.orderMq = [];
        this.client = new net.Socket();
        let client = this.client;
        let that = this;

        //初始化
        client.connect(config.port, config.host, function () {
            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);
            client.destroy();
            receive(client, null, error);
        });

        client.on('close', function () {
            log.info('读写器连接断开');
        });
    }
    send(sendOrder) {
        this.orderMq.push(sendOrder.substr(0, 2).toLowerCase());
        let call = new Buffer(sendOrder, 'hex');
        this.client.write(call);
    }
}
export default Connector;