This repository was archived by the owner on Oct 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathserialport.js
502 lines (421 loc) · 12.2 KB
/
serialport.js
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
'use strict';
// Copyright 2011 Chris Williams <[email protected]>
const _debug = false;
const debug = (message) => {
if (_debug) console.log(message);
};
// shims
// Internal Dependencies
var SerialPortBinding = require('./bindings');
var parsers = require('./parsers');
// Built-ins Dependencies
var fs = require('fs');
var stream = require('stream');
var util = require('util');
// VALIDATION ARRAYS
var DATABITS = [5, 6, 7, 8];
var STOPBITS = [1, 1.5, 2];
var PARITY = ['none', 'even', 'mark', 'odd', 'space'];
var FLOWCONTROLS = ['xon', 'xoff', 'xany', 'rtscts'];
var SET_OPTIONS = ['brk', 'cts', 'dtr', 'dts', 'rts'];
// Stuff from ReadStream, refactored for our usage:
var kPoolSize = 40 * 1024;
var kMinPoolSpace = 128;
var defaultSettings = {
baudRate: 9600,
autoOpen: true,
parity: 'none',
xon: false,
xoff: false,
xany: false,
rtscts: false,
hupcl: true,
dataBits: 8,
stopBits: 1,
bufferSize: 64 * 1024,
lock: true,
parser: parsers.raw,
platformOptions: SerialPortBinding.platformOptions
};
var defaultSetFlags = {
brk: false,
cts: false,
dtr: true,
dts: false,
rts: true
};
// deprecate the lowercase version of these options next major release
var LOWERCASE_OPTIONS = [
'baudRate',
'dataBits',
'stopBits',
'bufferSize',
'platformOptions'
];
function correctOptions(options) {
LOWERCASE_OPTIONS.forEach((name) => {
var lowerName = name.toLowerCase();
if (options.hasOwnProperty(lowerName)) {
var value = options[lowerName];
delete options[lowerName];
options[name] = value;
}
});
return options;
}
function SerialPort(path, options, callback) {
if (typeof callback === 'boolean') {
throw new TypeError('`openImmediately` is now called `autoOpen` and is a property of options');
}
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
stream.Stream.call(this);
if (!path) {
throw new TypeError('No path specified');
}
this.path = path;
var correctedOptions = correctOptions(options);
var settings = Object.assign({}, defaultSettings, correctedOptions);
if (typeof settings.baudRate !== 'number') {
throw new TypeError(`Invalid "baudRate" must be a number got: ${settings.baudRate}`);
}
if (DATABITS.indexOf(settings.dataBits) === -1) {
throw new TypeError(`Invalid "databits": ${settings.dataBits}`);
}
if (STOPBITS.indexOf(settings.stopBits) === -1) {
throw new TypeError(`Invalid "stopbits": ${settings.stopBits}`);
}
if (PARITY.indexOf(settings.parity) === -1) {
throw new TypeError(`Invalid "parity": ${settings.parity}`);
}
FLOWCONTROLS.forEach((control) => {
if (typeof settings[control] !== 'boolean') {
throw new TypeError(`Invalid "${control}" is not boolean`);
}
});
settings.disconnectedCallback = this._disconnected.bind(this);
settings.dataCallback = settings.parser.bind(this, this);
this.fd = null;
this.paused = true;
this.opening = false;
this.closing = false;
if (process.platform !== 'win32') {
this.bufferSize = settings.bufferSize;
this.readable = true;
this.reading = false;
}
this.options = settings;
if (this.options.autoOpen) {
// is nextTick necessary?
process.nextTick(this.open.bind(this, callback));
}
}
util.inherits(SerialPort, stream.Stream);
SerialPort.prototype._error = function(error, callback) {
if (callback) {
callback.call(this, error);
} else {
this.emit('error', error);
}
};
SerialPort.prototype.open = function(callback) {
if (this.isOpen()) {
return this._error(new Error('Port is already open'), callback);
}
if (this.opening) {
return this._error(new Error('Port is opening'), callback);
}
this.paused = true;
this.readable = true;
this.reading = false;
this.opening = true;
SerialPortBinding.open(this.path, this.options, (err, fd) => {
this.opening = false;
if (err) {
debug('SerialPortBinding.open had an error', err);
return this._error(err, callback);
}
this.fd = fd;
this.paused = false;
if (process.platform !== 'win32') {
this.serialPoller = new SerialPortBinding.SerialportPoller(this.fd, (err) => {
if (!err) {
this._read();
} else {
this._disconnected(err);
}
});
this.serialPoller.start();
}
this.emit('open');
if (callback) {
callback.call(this, null);
}
});
};
SerialPort.prototype.update = function(options, callback) {
if (!this.isOpen()) {
debug('update attempted, but port is not open');
return this._error(new Error('Port is not open'), callback);
}
var correctedOptions = correctOptions(options);
var settings = Object.assign({}, defaultSettings, correctedOptions);
this.options.baudRate = settings.baudRate;
SerialPortBinding.update(this.fd, this.options, (err) => {
if (err) {
return this._error(err, callback);
}
if (callback) {
callback.call(this, null);
}
});
};
SerialPort.prototype.isOpen = function() {
return this.fd !== null && !this.closing;
};
SerialPort.prototype.write = function(buffer, ending, callback) {
if (!this.isOpen()) {
debug('write attempted, but port is not open');
return this._error(new Error('Port is not open'), callback);
}
if (!Buffer.isBuffer(buffer)) {
buffer = Buffer.from(buffer);
}
switch (ending) {
case 'Newline':
buffer = Buffer.concat([buffer, Buffer.from('\n')]);
break;
case 'Carriage return':
buffer = Buffer.concat([buffer, Buffer.from('\r')]);
break;
case 'Both NL & CR':
buffer = Buffer.concat([buffer, Buffer.from('\r\n')]);
break;
default:
break;
}
debug(`write ${buffer.length} bytes of data`);
SerialPortBinding.write(this.fd, buffer, (err) => {
if (err) {
debug('SerialPortBinding.write had an error', err);
return this._error(err, callback);
}
if (callback) {
callback.call(this, null);
}
});
};
if (process.platform !== 'win32') {
SerialPort.prototype._read = function() {
if (!this.readable || this.paused || this.reading || this.closing) {
return;
}
this.reading = true;
if (!this.pool || this.pool.length - this.pool.used < kMinPoolSpace) {
// discard the old pool. Can't add to the free list because
// users might have references to slices on it.
this.pool = Buffer.alloc(kPoolSize);
this.pool.used = 0;
}
// Grab another reference to the pool in the case that while we're in the
// thread pool another read() finishes up the pool, and allocates a new
// one.
var toRead = Math.min(this.pool.length - this.pool.used, ~~this.bufferSize);
var start = this.pool.used;
var _afterRead = (err, bytesRead, readPool, bytesRequested) => {
this.reading = false;
if (err) {
if (err.code && err.code === 'EAGAIN') {
if (this.isOpen()) {
this.serialPoller.start();
}
// handle edge case were mac/unix doesn't clearly know the error.
} else if (err.code && (err.code === 'EBADF' || err.code === 'ENXIO' || (err.errno === -1 || err.code === 'UNKNOWN'))) {
this._disconnected(err);
} else {
this.fd = null;
this.readable = false;
this.emit('error', err);
}
return;
}
// Since we will often not read the number of bytes requested,
// let's mark the ones we didn't need as available again.
this.pool.used -= bytesRequested - bytesRead;
if (bytesRead === 0) {
if (this.isOpen()) {
this.serialPoller.start();
}
} else {
var b = this.pool.slice(start, start + bytesRead);
// do not emit events if the stream is paused
if (this.paused) {
if (!this.buffer) {
this.buffer = Buffer.alloc(0);
}
this.buffer = Buffer.concat([this.buffer, b]);
return;
}
this._emitData(b);
// do not emit events anymore after we declared the stream unreadable
if (!this.readable) {
return;
}
this._read();
}
};
fs.read(this.fd, this.pool, this.pool.used, toRead, null, (err, bytesRead) => {
var readPool = this.pool;
var bytesRequested = toRead;
_afterRead(err, bytesRead, readPool, bytesRequested);
});
this.pool.used += toRead;
};
SerialPort.prototype._emitData = function(data) {
this.options.dataCallback(data);
};
SerialPort.prototype.pause = function() {
this.paused = true;
};
SerialPort.prototype.resume = function() {
this.paused = false;
if (this.buffer) {
var buffer = this.buffer;
this.buffer = null;
this._emitData(buffer);
}
// No longer open?
if (!this.isOpen()) {
return;
}
this._read();
};
} // if !'win32'
SerialPort.prototype._disconnected = function(err) {
this.paused = true;
this.emit('disconnect', err);
if (this.closing) {
return;
}
if (this.fd === null) {
return;
}
this.closing = true;
if (process.platform !== 'win32') {
this.readable = false;
this.serialPoller.close();
}
SerialPortBinding.close(this.fd, (err) => {
this.closing = false;
if (err) {
debug('Disconnect close completed with error: ', err);
}
this.fd = null;
this.emit('close');
});
};
SerialPort.prototype.close = function(callback) {
this.paused = true;
if (this.closing) {
debug('close attempted, but port is already closing');
return this._error(new Error('Port is not open'), callback);
}
if (!this.isOpen()) {
debug('close attempted, but port is not open');
return this._error(new Error('Port is not open'), callback);
}
this.closing = true;
// Stop polling before closing the port.
if (process.platform !== 'win32') {
this.readable = false;
this.serialPoller.close();
}
SerialPortBinding.close(this.fd, (err) => {
this.closing = false;
if (err) {
debug('SerialPortBinding.close had an error', err);
return this._error(err, callback);
}
this.fd = null;
this.emit('close');
if (callback) {
callback.call(this, null);
}
});
};
SerialPort.prototype.flush = function(callback) {
if (!this.isOpen()) {
debug('flush attempted, but port is not open');
return this._error(new Error('Port is not open'), callback);
}
SerialPortBinding.flush(this.fd, (err, result) => {
if (err) {
debug('SerialPortBinding.flush had an error', err);
return this._error(err, callback);
}
if (callback) {
callback.call(this, null, result);
}
});
};
SerialPort.prototype.set = function(options, callback) {
if (!this.isOpen()) {
debug('set attempted, but port is not open');
return this._error(new Error('Port is not open'), callback);
}
options = options || {};
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
var settings = {};
for (var i = SET_OPTIONS.length - 1; i >= 0; i--) {
var flag = SET_OPTIONS[i];
if (options[flag] !== undefined) {
settings[flag] = options[flag];
} else {
settings[flag] = defaultSetFlags[flag];
}
}
SerialPortBinding.set(this.fd, settings, (err) => {
if (err) {
debug('SerialPortBinding.set had an error', err);
return this._error(err, callback);
}
if (callback) {
callback.call(this, null);
}
});
};
SerialPort.prototype.drain = function(callback) {
if (!this.isOpen()) {
debug('drain attempted, but port is not open');
return this._error(new Error('Port is not open'), callback);
}
SerialPortBinding.drain(this.fd, (err) => {
if (err) {
debug('SerialPortBinding.drain had an error', err);
return this._error(err, callback);
}
if (callback) {
callback.call(this, null);
}
});
};
SerialPort.parsers = parsers;
SerialPort.list = SerialPortBinding.list;
// Write a depreciation warning once
Object.defineProperty(SerialPort, 'SerialPort', {
get: function() {
// console.warn('DEPRECATION: Please use `require(\'serialport\')` instead of `require(\'serialport\').SerialPort`');
Object.defineProperty(SerialPort, 'SerialPort', {
value: SerialPort
});
return SerialPort;
},
configurable: true
});
module.exports = SerialPort;