/
index.js
350 lines (294 loc) · 9.95 KB
/
index.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
/* eslint no-bitwise: 0 */
/* eslint no-continue: 0 */
import events from 'events';
import fs from 'fs';
import timers from 'timers';
import stream, { Transform } from 'stream';
const noop = () => {};
const streamify = (text) => {
const s = new stream.Readable();
s.push(text);
s.push(null);
return s;
};
const containsLineEnd = (() => {
const re = new RegExp(/.*(?:\r\n|\r|\n)/g);
return (s => !!s.match(re));
})();
// @param {array} arr The array to iterate over.
// @param {object} opts The options object.
// @param {function} iteratee The iteratee invoked per element.
// @param {function} done The done invoked after the loop has finished.
const iterateArray = (arr = [], opts = {}, iteratee = noop, done = noop) => {
if (typeof opts === 'function') {
done = iteratee;
iteratee = opts;
opts = {};
}
opts.batchSize = opts.batchSize || 1;
const loop = (i = 0) => {
for (let count = 0; i < arr.length && count < opts.batchSize; ++i, ++count) {
iteratee(arr[i], i, arr);
}
if (i < arr.length) {
timers.setImmediate(() => loop(i));
return;
}
done();
};
loop();
};
// @param {string} line The G-code line
const parseLine = (() => {
// http://reprap.org/wiki/G-code#Special_fields
// The checksum "cs" for a GCode string "cmd" (including its line number) is computed
// by exor-ing the bytes in the string up to and not including the * character.
const computeChecksum = (s) => {
s = s || '';
if (s.lastIndexOf('*') >= 0) {
s = s.substr(0, s.lastIndexOf('*'));
}
let cs = 0;
for (let i = 0; i < s.length; ++i) {
const c = s[i].charCodeAt(0);
cs ^= c;
}
return cs;
};
// http://linuxcnc.org/docs/html/gcode/overview.html#gcode:comments
// Comments can be embedded in a line using parentheses () or for the remainder of a lineusing a semi-colon. The semi-colon is not treated as the start of a comment when enclosed in parentheses.
const stripComments = (() => {
const re1 = new RegExp(/\s*\([^\)]*\)/g); // Remove anything inside the parentheses
const re2 = new RegExp(/\s*;.*/g); // Remove anything after a semi-colon to the end of the line, including preceding spaces
const re3 = new RegExp(/\s+/g);
return (line => line.replace(re1, '').replace(re2, '').replace(re3, ''));
})();
const re = /(%.*)|({.*)|((?:\$\$)|(?:\$[a-zA-Z0-9#]*))|([a-zA-Z][0-9\+\-\.]+)|(\*[0-9]+)/igm;
return (line, options) => {
options = options || {};
options.flatten = !!options.flatten;
options.noParseLine = !!options.noParseLine;
const result = {
line: line
};
if (options.noParseLine) {
return result;
}
result.words = [];
let ln; // Line number
let cs; // Checksum
const words = stripComments(line).match(re) || [];
for (let i = 0; i < words.length; ++i) {
const word = words[i];
const letter = word[0].toUpperCase();
const argument = word.slice(1);
// Parse % commands for bCNC and CNCjs
// - %wait Wait until the planner queue is empty
if (letter === '%') {
result.cmds = (result.cmds || []).concat(line.trim());
continue;
}
// Parse JSON commands for TinyG and g2core
if (letter === '{') {
result.cmds = (result.cmds || []).concat(line.trim());
continue;
}
// Parse $ commands for Grbl
// - $C Check gcode mode
// - $H Run homing cycle
if (letter === '$') {
result.cmds = (result.cmds || []).concat(`${letter}${argument}`);
continue;
}
// N: Line number
if (letter === 'N' && typeof ln === 'undefined') {
// Line (block) number in program
ln = Number(argument);
continue;
}
// *: Checksum
if (letter === '*' && typeof cs === 'undefined') {
cs = Number(argument);
continue;
}
let value = Number(argument);
if (Number.isNaN(value)) {
value = argument;
}
if (options.flatten) {
result.words.push(letter + value);
} else {
result.words.push([letter, value]);
}
}
// Line number
(typeof (ln) !== 'undefined') && (result.ln = ln);
// Checksum
(typeof (cs) !== 'undefined') && (result.cs = cs);
if (result.cs && (computeChecksum(line) !== result.cs)) {
result.err = true; // checksum failed
}
return result;
};
})();
// @param {object} stream The G-code line stream
// @param {options} options The options object
// @param {function} callback The callback function
const parseStream = (stream, options, callback = noop) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
const emitter = new events.EventEmitter();
try {
const results = [];
stream
.pipe(new GCodeLineStream(options))
.on('data', (data) => {
emitter.emit('data', data);
results.push(data);
})
.on('end', () => {
emitter.emit('end', results);
callback && callback(null, results);
})
.on('error', callback);
} catch (err) {
callback(err);
}
return emitter;
};
// @param {string} file The G-code path name
// @param {options} options The options object
// @param {function} callback The callback function
const parseFile = (file, options, callback = noop) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
file = file || '';
let s = fs.createReadStream(file, { encoding: 'utf8' });
s.on('error', callback);
return parseStream(s, options, callback);
};
const parseFileSync = (file, options) => {
return parseStringSync(fs.readFileSync(file, 'utf8'), options);
};
// @param {string} str The G-code text string
// @param {options} options The options object
// @param {function} callback The callback function
const parseString = (str, options, callback = noop) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
return parseStream(streamify(str), options, callback);
};
const parseStringSync = (str, options) => {
const { flatten = false, noParseLine = false } = { ...options };
const results = [];
const lines = str.split('\n');
for (let i = 0; i < lines.length; ++i) {
const line = lines[i].trim();
if (line.length === 0) {
continue;
}
const result = parseLine(line, {
flatten,
noParseLine
});
results.push(result);
}
return results;
};
// @param {string} str The G-code text string
// @param {options} options The options object
class GCodeLineStream extends Transform {
state = {
lineCount: 0,
lastChunkEndedWithCR: false
};
options = {
batchSize: 1000,
noParseLine: false
};
lineBuffer = '';
re = new RegExp(/.*(?:\r\n|\r|\n)|.+$/g);
// @param {object} [options] The options object
// @param {number} [options.batchSize] The batch size.
// @param {boolean} [options.flatten] True to flatten the array, false otherwise.
// @param {boolean} [options.noParseLine] True to not parse line, false otherwise.
constructor(options = {}) {
super({ objectMode: true });
this.options = {
...this.options,
...options
};
}
_transform(chunk, encoding, next) {
// decode binary chunks as UTF-8
encoding = encoding || 'utf8';
if (Buffer.isBuffer(chunk)) {
if (encoding === 'buffer') {
encoding = 'utf8';
}
chunk = chunk.toString(encoding);
}
this.lineBuffer += chunk;
if (!containsLineEnd(chunk)) {
next();
return;
}
const lines = this.lineBuffer.match(this.re);
if (!lines || lines.length === 0) {
next();
return;
}
// Do not split CRLF which spans chunks
if (this.state.lastChunkEndedWithCR && lines[0] === '\n') {
lines.shift();
}
this.state.lastChunkEndedWithCR = (this.lineBuffer[this.lineBuffer.length - 1] === '\r');
if ((this.lineBuffer[this.lineBuffer.length - 1] === '\r') ||
(this.lineBuffer[this.lineBuffer.length - 1] === '\n')) {
this.lineBuffer = '';
} else {
const line = lines.pop() || '';
this.lineBuffer = line;
}
iterateArray(lines, { batchSize: this.options.batchSize }, (line, key) => {
line = line.trim();
if (line.length > 0) {
const result = parseLine(line, {
flatten: this.options.flatten,
noParseLine: this.options.noParseLine
});
this.push(result);
}
}, next);
}
_flush(done) {
if (this.lineBuffer) {
const line = this.lineBuffer.trim();
if (line.length > 0) {
const result = parseLine(line, {
flatten: this.options.flatten,
noParseLine: this.options.noParseLine
});
this.push(result);
}
this.lineBuffer = '';
this.state.lastChunkEndedWithCR = false;
}
done();
}
}
export {
GCodeLineStream,
parseLine,
parseStream,
parseFile,
parseFileSync,
parseString,
parseStringSync
};