connector.js
1.69 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
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;