Frontend to the famous GRBL.

gcodeinterpreter.cpp 3.4KB

    /* Part of x2grbl * * Copyright Johann Wilhelm <johann.wilhelm@9mal6.de> 2015 * * see Readme.md for detailed license and usage information! */ #include "gcodeinterpreter.h" #include <QDebug> #include <QRegExp> #include <QStringList> GCodeInterpreter::GCodeInterpreter(QObject *parent) : QObject(parent) { isRelative=true; Unit=MeasuringUnit_mm; } bool GCodeInterpreter::Run(GCodeOutputDevice &Device, GCodeParser &Parser) { Device.Reset(); if (Parser.isEmpty()) return true; int LineNumber=Parser.getFirstLine(); QRegExp CommandParser(QString("([MG][^MG]+)")); QRegExp RemoveWhiteSpaces(QString("\\s")); QRegExp RemoveInLineComments(QString("\\(.*\\)")); QRegExp RemoveEndComments(QString("(;.*)")); while (LineNumber!=-1) { QString Line=Parser.getLine(LineNumber); Line.replace(RemoveWhiteSpaces,QString("")); Line.replace(RemoveInLineComments, QString("")); Line.replace(RemoveEndComments, QString("")); LineNumber=Parser.getNextLine(LineNumber); int pos=0; while (pos >= 0) { pos=CommandParser.indexIn(Line, pos); if (pos >= 0) { QStringList Matches=CommandParser.capturedTexts(); if (Matches.count()>1) { if (!Execute(Device, Matches[1], LineNumber)) { qDebug()<<"Executing GCode Line "<<LineNumber<< " \""<<Matches[1]<<"\" failed!\n"; return false; } } pos++; } } } return true; } bool GCodeInterpreter::Execute(GCodeOutputDevice &Device, QString Command, int &NextLine) { QRegExp CommandParser(QString("([MG])([0-9]+(?:\\.[0-9]+)?)(.*)")); QRegExp ParameterParser(QString("([A-Z])([^A-Z]+)")); CommandParser.indexIn(Command); QStringList Parts=CommandParser.capturedTexts(); if (Parts.count()==4) { if (Parts[1].length()==1 && Parts[2].length()>0) { QStringList CommandNumberList=Parts[2].split(QString(".")); bool Ok; int Cmd=CommandNumberList[0].toInt(&Ok); if (!Ok) return false; int SubCmd=-1; if (CommandNumberList.count()==2) { SubCmd=CommandNumberList[1].toInt(&Ok); if (!Ok) return false; } GCode Code; Code.Cmd=Cmd; Code.SubCmd=SubCmd; int pos=0; while (pos >= 0) { pos=ParameterParser.indexIn(Parts[3], pos); if (pos >= 0) { QStringList Matches=ParameterParser.capturedTexts(); if (Matches.count()>2) { Code.Parameters[Matches[1]]=Matches[2]; } pos++; } } if (Parts[1]==QString("M")) { Code.Code=CodeType_MCode; } else if (Parts[1]=="G") { Code.Code=CodeType_GCode; } else { qDebug()<<"Unexpected Code "<<Command<<"\n"; return false; } if (Device.supported(Code)) return Device.Run(Code); else { qDebug()<<"Device "<<Device.name()<<"does not support"<<Command<<"\n"; } } } return false; }