-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgcode-parser.js
More file actions
42 lines (40 loc) · 1.04 KB
/
gcode-parser.js
File metadata and controls
42 lines (40 loc) · 1.04 KB
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
/**
* Parses a string of gcode instructions, and invokes handlers for
* each type of command.
*
* Special handler:
* 'default': Called if no other handler matches.
*/
function GCodeParser(handlers) {
this.handlers = handlers || {};
}
GCodeParser.prototype.parseLine = function(text, info) {
text = text.replace(/;.*$/, '').trim(); // Remove comments
if (text) {
var tokens = text.split(' ');
if (tokens) {
var cmd = tokens[0];
var args = {
'cmd': cmd
};
tokens.splice(1).forEach(function(token) {
var key = token[0].toLowerCase();
var value = parseFloat(token.substring(1));
args[key] = value;
});
var handler = this.handlers[tokens[0]] || this.handlers['default'];
if (handler) {
return handler(args, info);
}
}
}
};
GCodeParser.prototype.parse = function(gcode) {
var lines = gcode.split('\n');
for (var i = 0; i < lines.length; i++) {
//console.log(lines[i]);
if (this.parseLine(lines[i], i) === false) {
break;
}
}
};