-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcode-parser.js
109 lines (86 loc) · 1.93 KB
/
gcode-parser.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
function Whitespace(line) {
return {
type: 'whitespace',
value: line
};
}
function Comment(line) {
return {
type: 'comment',
value: line.split(';').slice(1).join(';')
};
}
function GCode(line) {
// there can be a comment later in the line. Split that first.
var parts = line.trim().split(';');
// the first part is the gcode
var terms = parts[0].split(' ').filter(function(term) {
// strip whitespace
return !!term;
});
var obj = {
type: 'gcode',
command: terms[0],
terms: terms
};
if (parts.length > 1) {
obj.comment = parts.slice(1).join(';');
}
var unknown = [];
terms.forEach(function(term) {
var start = term[0];
var rest = term.slice(1);
switch (start) {
case 'G':
// the g-code command. G0 or G1
obj['G'] = parseInt(rest, 10);
break;
case 'F':
// feed rate in mm/minute
obj['F'] = parseInt(rest, 10);
break;
case 'E':
// extruder
obj['E'] = parseFloat(rest);
break;
case 'X':
// x position
obj['X'] = parseFloat(rest);
break;
case 'Y':
// y position
obj['Y'] = parseFloat(rest);
break;
case 'Z':
// z position
obj['Z'] = parseFloat(rest);
break;
default:
unknown.push(term);
}
});
if (unknown.length) {
obj.unknown = unknown;
}
return obj;
}
function parseLine(line) {
const trimmed = line.trim();
if (!trimmed) {
return Whitespace(line);
}
if (trimmed[0] == ';') {
return Comment(line);
}
return GCode(line);
}
// through-stream that reads lines and writes simple objects that represent
// gcode commands, comments and whitespace, etc.
function parse(read) {
return function parseReadable(end, cb) {
read(end, function parseCallback(end, line) {
cb(end, end ? null : parseLine(line));
})
}
}
module.exports = parse;