Select Git revision

Jake Read authored
gcode.js 1.71 KiB
const EventEmitter = require('events')
class Gcode extends EventEmitter {}
function create() {
var gcode = new Gcode()
// state
gcode.mode = 'G0'
gcode.speeds = {
G0: 1200,
G1: 400
}
// local functions
function getKeyValues(str) {
var kv = {}
for (var i = 0; i < str.length; i++) {
if (str[i].match('[A-Za-z]')) { // regex to match upper case letters
var lastIndex = str.indexOf(' ', i)
if (lastIndex < 0) {
lastIndex = str.length
}
var key = str[i].toUpperCase()
kv[key] = parseFloat(str.slice(i + 1, lastIndex))
}
}
return kv
}
function parseGcode(str){
var instruction = {
position: {},
hasMove: false,
speed: 0
}
kv = getKeyValues(str)
// track modality
if(kv.G == 0 | kv.G == 1){
gcode.mode = 'G' + kv.G.toString()
} else if (kv.G != null) {
// no arcs pls
console.log('unfriendly Gcode mode!', kv)
}
for(key in kv){
if(key.match('[A-EX-Z]')){
instruction.position[key] = kv[key]
instruction.hasMove = true
} else if (key.match('[F]')){
gcode.speeds[gcode.mode] = kv.F
}
}
instruction.speed = gcode.speeds[gcode.mode]
// and this for help later?
instruction.kv = kv
return instruction
}
// input functions
gcode.lineIn = function(str) {
var instruction = parseGcode(str)
if (instruction.hasMove){
gcode.emit('newInstruction', instruction)
} else {
gcode.emit('modeChange', gcode.mode)
}
}
return gcode
}
module.exports = {
create: create
}