-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
85 lines (81 loc) · 2.55 KB
/
index.ts
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
import * as Net from 'net';
type LinkResult = {
message: Buffer,
address: string,
result: string | null,
resultBuffer: Buffer | null,
error?: any,
}
type CallbackResult = (error: boolean, linkResult: LinkResult) => void
type QueueArr = {
message: Buffer,
address: string,
callback: CallbackResult,
running: boolean,
}[]
export class Hostlink {
connection: Net.Socket | undefined;
queue: QueueArr = [];
processRunning: boolean = false;
connectStatus: boolean = false;
options: Net.NetConnectOpts;
constructor(options: Net.NetConnectOpts) {
this.options = options;
}
connect(callback: () => void | undefined) {
const connection = Net.createConnection(this.options, callback);
this.connection = connection;
connection.on('data', this.onData.bind(this));
connection.on('error', this.onError.bind(this));
}
private onData(data: Buffer) {
const queueData = this.queue.shift();
if (!queueData) { return; }
const resultData: LinkResult = {
message: queueData.message,
address: queueData.address,
result: data.toString(),
resultBuffer: data,
};
queueData.callback(false, resultData);
}
private onError(error: any) {
console.error('error happen');
const queueData = this.queue.shift();
if (!queueData) { return; }
const resultData: LinkResult = {
message: queueData.message,
address: queueData.address,
result: null,
resultBuffer: null,
error,
};
queueData.callback(true, resultData);
}
private onConnect() {
this.connectStatus = true;
}
private run() {
if (this.processRunning || !this.connection) { return; }
this.processRunning = true;
const queueArr = this.queue.filter((data) => (!data.running));
if (queueArr.length === 0) { this.processRunning = false; return; }
const data = queueArr[0];
this.connection.write(data.message);
data.running = true;
this.processRunning = false;
setTimeout(() => { this.run(); }, 500);
}
readItem(address: string, callback: CallbackResult) {
// if (!this.connectStatus) { console.log('un connect'); }
const message = Buffer.from(`RD ${address.trim()}\r\n`);
const queueData = { callback, message, address, running: false };
this.queue.push(queueData);
this.run();
}
writeItem(address: string, value:string, cb?: ((err?: Error | undefined) => void) | undefined) {
if (this.processRunning || !this.connection) { return; }
const message = Buffer.from(`WR ${address.trim()} ${value.trim()}\r\n`);
this.connection.write(message,cb);
}
}