-
Notifications
You must be signed in to change notification settings - Fork 279
/
uart.ts
458 lines (370 loc) · 15.6 KB
/
uart.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/* istanbul ignore file */
import {EventEmitter} from 'events';
import net from 'net';
import {SerialPort} from '../../serialPort';
import SocketPortUtils from '../../socketPortUtils';
import {Queue, Waitress, Wait} from '../../../utils';
import {Writer} from './writer';
import {Parser} from './parser';
import {Frame as NpiFrame, FrameType} from './frame';
import {SerialPortOptions} from '../../tstype';
import wait from '../../../utils/wait';
import {logger} from '../../../utils/logger';
const NS = 'zh:ezsp:uart';
enum NcpResetCode {
RESET_UNKNOWN_REASON = 0x00,
RESET_EXTERNAL = 0x01,
RESET_POWER_ON = 0x02,
RESET_WATCHDOG = 0x03,
RESET_ASSERT = 0x06,
RESET_BOOTLOADER = 0x09,
RESET_SOFTWARE = 0x0B,
ERROR_EXCEEDED_MAXIMUM_ACK_TIMEOUT_COUNT = 0x51,
ERROR_UNKNOWN_EM3XX_ERROR = 0x80,
}
type EZSPPacket = {
sequence: number
};
type EZSPPacketMatcher = {
sequence: number
};
export class SerialDriver extends EventEmitter {
private serialPort: SerialPort;
private socketPort: net.Socket;
private writer: Writer;
private parser: Parser;
private initialized: boolean;
private portType: 'serial' | 'socket';
private sendSeq = 0; // next frame number to send
private recvSeq = 0; // next frame number to receive
private ackSeq = 0; // next number after the last accepted frame
private rejectCondition = false;
private waitress: Waitress<EZSPPacket, EZSPPacketMatcher>;
private queue: Queue;
constructor() {
super();
this.initialized = false;
this.queue = new Queue(1);
this.waitress = new Waitress<EZSPPacket, EZSPPacketMatcher>(
this.waitressValidator, this.waitressTimeoutFormatter);
}
async connect(options: SerialPortOptions): Promise<void> {
this.portType = SocketPortUtils.isTcpPath(options.path) ? 'socket' : 'serial';
if (this.portType === 'serial') {
await this.openSerialPort(options.path, options.baudRate, options.rtscts);
} else {
await this.openSocketPort(options.path);
}
}
private async openSerialPort(path: string, baudRate: number, rtscts: boolean): Promise<void> {
const options = {
path,
baudRate: typeof baudRate === 'number' ? baudRate : 115200,
rtscts: typeof rtscts === 'boolean' ? rtscts : false,
autoOpen: false,
parity: 'none',
stopBits: 1,
xon: false,
xoff: false,
};
// enable software flow control if RTS/CTS not enabled in config
if (!options.rtscts) {
logger.debug(`RTS/CTS config is off, enabling software flow control.`, NS);
options.xon = true;
options.xoff = true;
}
logger.debug(`Opening SerialPort with ${JSON.stringify(options)}`, NS);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.serialPort = new SerialPort(options);
this.writer = new Writer();
this.writer.pipe(this.serialPort);
this.parser = new Parser(!options.rtscts);// flag unhandled XON/XOFF in logs if software flow control enabled
this.serialPort.pipe(this.parser);
this.parser.on('parsed', this.onParsed.bind(this));
try {
await this.serialPort.asyncOpen();
logger.debug('Serialport opened', NS);
this.serialPort.once('close', this.onPortClose.bind(this));
this.serialPort.on('error', this.onPortError.bind(this));
// reset
await this.reset();
this.initialized = true;
} catch (error) {
this.initialized = false;
if (this.serialPort.isOpen) {
this.serialPort.close();
}
throw error;
}
}
private async openSocketPort(path: string): Promise<void> {
const info = SocketPortUtils.parseTcpPath(path);
logger.debug(`Opening TCP socket with ${info.host}:${info.port}`, NS);
this.socketPort = new net.Socket();
this.socketPort.setNoDelay(true);
this.socketPort.setKeepAlive(true, 15000);
this.writer = new Writer();
this.writer.pipe(this.socketPort);
this.parser = new Parser();
this.socketPort.pipe(this.parser);
this.parser.on('parsed', this.onParsed.bind(this));
return new Promise((resolve, reject): void => {
const openError = (err: Error): void => {
this.initialized = false;
reject(err);
};
this.socketPort.on('connect', () => {
logger.debug('Socket connected', NS);
});
this.socketPort.on('ready', async (): Promise<void> => {
logger.debug('Socket ready', NS);
this.socketPort.removeListener('error', openError);
this.socketPort.once('close', this.onPortClose.bind(this));
this.socketPort.on('error', this.onPortError.bind(this));
// reset
await this.reset();
this.initialized = true;
resolve();
});
this.socketPort.once('error', openError);
this.socketPort.connect(info.port, info.host);
});
}
private async onParsed(frame: NpiFrame): Promise<void> {
const rejectCondition = this.rejectCondition;
try {
frame.checkCRC();
/* Frame receive handler */
switch (frame.type) {
case FrameType.DATA:
this.handleDATA(frame);
break;
case FrameType.ACK:
this.handleACK(frame);
break;
case FrameType.NAK:
this.handleNAK(frame);
break;
case FrameType.RST:
this.handleRST(frame);
break;
case FrameType.RSTACK:
this.handleRSTACK(frame);
break;
case FrameType.ERROR:
await this.handleError(frame);
break;
default:
this.rejectCondition = true;
logger.debug(`UNKNOWN FRAME RECEIVED: ${frame}`, NS);
}
} catch (error) {
this.rejectCondition = true;
logger.error(error, NS);
logger.error(`Error while parsing to NpiFrame '${error.stack}'`, NS);
}
// We send NAK only if the rejectCondition was set in the current processing
if (!rejectCondition && this.rejectCondition) {
// send NAK
this.writer.sendNAK(this.recvSeq);
}
}
private handleDATA(frame: NpiFrame): void {
/* Data frame receive handler */
const frmNum = (frame.control & 0x70) >> 4;
const reTx = (frame.control & 0x08) >> 3;
logger.debug(`<-- DATA (${frmNum},${frame.control & 0x07},${reTx}): ${frame}`, NS);
// Expected package {recvSeq}, but received {frmNum}
// This happens when the chip sends us a reTx packet, but we are waiting for the next one
if (this.recvSeq != frmNum) {
if (reTx) {
// if the reTx flag is set, then this is a packet replay
logger.debug(`Unexpected DATA packet sequence ${frmNum} | ${this.recvSeq}: packet replay`, NS);
} else {
// otherwise, the sequence of packets is out of order - skip or send NAK is needed
logger.debug(`Unexpected DATA packet sequence ${frmNum} | ${this.recvSeq}: reject condition`, NS);
this.rejectCondition = true;
return;
}
}
this.rejectCondition = false;
this.recvSeq = (frmNum + 1) & 7; // next
logger.debug(`--> ACK (${this.recvSeq})`, NS);
this.writer.sendACK(this.recvSeq);
const handled = this.handleACK(frame);
if (reTx && !handled) {
// if the package is resent and did not expect it,
// then will skip it - already processed it earlier
logger.debug(`Skipping the packet as repeated (${this.recvSeq})`, NS);
return;
}
const data = frame.buffer.subarray(1, -3);
this.emit('received', NpiFrame.makeRandomizedBuffer(data));
}
private handleACK(frame: NpiFrame): boolean {
/* Handle an acknowledgement frame */
// next number after the last accepted frame
this.ackSeq = frame.control & 0x07;
logger.debug(`<-- ACK (${this.ackSeq}): ${frame}`, NS);
const handled = this.waitress.resolve({sequence: this.ackSeq});
if (!handled && this.sendSeq !== this.ackSeq) {
// Packet confirmation received for {ackSeq}, but was expected {sendSeq}
// This happens when the chip has not yet received of the packet {sendSeq} from us,
// but has already sent us the next one.
logger.debug(`Unexpected packet sequence ${this.ackSeq} | ${this.sendSeq}`, NS);
}
return handled;
}
private handleNAK(frame: NpiFrame): void {
/* Handle negative acknowledgment frame */
const nakNum = frame.control & 0x07;
logger.debug(`<-- NAK (${nakNum}): ${frame}`, NS);
const handled = this.waitress.reject({sequence: nakNum}, 'Recv NAK frame');
if (!handled) {
// send NAK
logger.debug(`NAK Unexpected packet sequence ${nakNum}`, NS);
} else {
logger.debug(`NAK Expected packet sequence ${nakNum}`, NS);
}
}
private handleRST(frame: NpiFrame): void {
logger.debug(`<-- RST: ${frame}`, NS);
}
private handleRSTACK(frame: NpiFrame): void {
/* Reset acknowledgement frame receive handler */
let code;
this.rejectCondition = false;
logger.debug(`<-- RSTACK ${frame}`, NS);
try {
code = NcpResetCode[frame.buffer[2]];
} catch (e) {
code = NcpResetCode.ERROR_UNKNOWN_EM3XX_ERROR;
}
logger.debug(`RSTACK Version: ${frame.buffer[1]} Reason: ${code.toString()} frame: ${frame}`, NS);
if (NcpResetCode[<number>code].toString() !== NcpResetCode.RESET_SOFTWARE.toString()) {
return;
}
this.waitress.resolve({sequence: -1});
}
private async handleError(frame: NpiFrame): Promise<void> {
logger.debug(`<-- Error ${frame}`, NS);
try {
// send reset
await this.reset();
} catch (error) {
logger.error(`Failed to reset on Error Frame: ${error}`, NS);
}
}
async reset(): Promise<void> {
logger.debug('Uart reseting', NS);
this.parser.reset();
this.queue.clear();
this.sendSeq = 0;
this.recvSeq = 0;
return this.queue.execute<void>(async (): Promise<void> => {
try {
logger.debug(`--> Write reset`, NS);
const waiter = this.waitFor(-1, 10000);
this.rejectCondition = false;
this.writer.sendReset();
logger.debug(`-?- waiting reset`, NS);
await waiter.start().promise;
logger.debug(`-+- waiting reset success`, NS);
await wait(2000);
} catch (e) {
logger.error(`--> Error: ${e}`, NS);
this.emit('reset');
throw new Error(`Reset error: ${e}`);
}
});
}
public async close(emitClose: boolean): Promise<void> {
logger.debug('Closing UART', NS);
this.queue.clear();
if (this.initialized) {
this.initialized = false;
if (this.portType === 'serial') {
try {
await this.serialPort.asyncFlushAndClose();
} catch (error) {
if (emitClose) {
this.emit('close');
}
throw error;
}
} else {
this.socketPort.destroy();
}
}
if (emitClose) {
this.emit('close');
}
}
private onPortError(error: Error): void {
logger.error(`Port error: ${error}`, NS);
}
private onPortClose(err: boolean | Error): void {
logger.debug(`Port closed. Error? ${err}`, NS);
// on error: serialport passes an Error object (in case of disconnect)
// net.Socket passes a boolean (in case of a transmission error)
// try to reset instead of failing immediately
if (err != null && err !== false) {
this.emit('reset');
} else {
this.initialized = false;
this.emit('close');
}
}
public isInitialized(): boolean {
return this.initialized;
}
public async sendDATA(data: Buffer): Promise<void> {
const seq = this.sendSeq;
this.sendSeq = ((seq + 1) % 8); // next
const nextSeq = this.sendSeq;
const ackSeq = this.recvSeq;
return this.queue.execute<void>(async (): Promise<void> => {
const randData = NpiFrame.makeRandomizedBuffer(data);
try {
const waiter = this.waitFor(nextSeq);
logger.debug(`--> DATA (${seq},${ackSeq},0): ${data.toString('hex')}`, NS);
this.writer.sendData(randData, seq, 0, ackSeq);
logger.debug(`-?- waiting (${nextSeq})`, NS);
await waiter.start().promise;
logger.debug(`-+- waiting (${nextSeq}) success`, NS);
} catch (e1) {
logger.error(`--> Error: ${e1}`, NS);
logger.error(`-!- break waiting (${nextSeq})`, NS);
logger.error(`Can't send DATA frame (${seq},${ackSeq},0): ${data.toString('hex')}`, NS);
try {
await Wait(500);
const waiter = this.waitFor(nextSeq);
logger.debug(`->> DATA (${seq},${ackSeq},1): ${data.toString('hex')}`, NS);
this.writer.sendData(randData, seq, 1, ackSeq);
logger.debug(`-?- rewaiting (${nextSeq})`, NS);
await waiter.start().promise;
logger.debug(`-+- rewaiting (${nextSeq}) success`, NS);
} catch (e2) {
logger.error(`--> Error: ${e2}`, NS);
logger.error(`-!- break rewaiting (${nextSeq})`, NS);
logger.error(`Can't resend DATA frame (${seq},${ackSeq},1): ${data.toString('hex')}`, NS);
if (this.initialized) {
this.emit('reset');
}
throw new Error(`sendDATA error: try 1: ${e1}, try 2: ${e2}`);
}
}
});
}
public waitFor(sequence: number, timeout = 4000)
: { start: () => { promise: Promise<EZSPPacket>; ID: number }; ID: number } {
return this.waitress.waitFor({sequence}, timeout);
}
private waitressTimeoutFormatter(matcher: EZSPPacketMatcher, timeout: number): string {
return `${JSON.stringify(matcher)} after ${timeout}ms`;
}
private waitressValidator(payload: EZSPPacket, matcher: EZSPPacketMatcher): boolean {
return (payload.sequence === matcher.sequence);
}
}