connector.js
2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* @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;