private void Button2_Click(object sender, EventArgs e) { string src = File.ReadAllText(file); var lexer = new Lexer(src); List <Token> tokens = lexer.Tokenize().ToList(); var parser = new Parser(tokens); List <Code> gcodes = parser.Parse().ToList(); MessageBox.Show("File Loaded"); foreach (var code in gcodes) { string test = code.ToString(); if (!test.Equals("Gcodes.Ast.Mcode")) { Gcode tempCode = (Gcode)code; List <Argument> args = tempCode.args; string output = tempCode.ToString().Substring(0, 2) + " "; foreach (var arg in args) { output = output + arg.Kind.ToString() + " " + arg.Value.ToString() + " "; } listBox1.Items.Add(output); } } }
public CodeEditorViewTemplate(int tabId, Gcode file = null) { InitializeComponent(); _viewModel = new CodeEditorViewModel(tabId, file); DataContext = _viewModel; }
public void Connect() { if (serialPort != null) { Disconnect(); } else { serialPort = new SerialPort(port, baud); } if (port != null) { serialPort.ReadTimeout = 1000; serialPort.WriteTimeout = 1000; serialPort.Open(); if (serialPort.IsOpen) { WaitFor("wait", 5000); Send(Gcode.ParseLine("M117 PrintSharp")); WaitFor("ok 0", 5000); } else { throw new Exception("Failed to open COM port " + port); } } else { throw new Exception("Cannot connect to NULL port"); } }
/// <summary> /// Get the <see cref="IOperation"/> corresponding to a particular /// <see cref="Gcode"/>. /// </summary> /// <param name="code"></param> /// <param name="initialState"></param> /// <returns></returns> public virtual IOperation GcodeOp(Gcode code, MachineState initialState) { Exception ex; if (ignoredGcodes.Contains(code.Number)) { return(new Noop(initialState)); } switch (code.Number) { case 4: var ms = code.ValueFor(ArgumentKind.P); if (ms == null) { ex = new ArgumentException("Dwell commands require a P argument"); ex.Data[nameof(code)] = code; throw ex; } return(new Noop(initialState, TimeSpan.FromMilliseconds(ms.Value))); default: ex = new UnknownGcodeException($"No applicable operation for G{code.Number}"); ex.Data[nameof(code)] = code; throw ex; } }
private void cmdDuplicateAll_Click(object sender, RoutedEventArgs e) { if (gCodeObject.gCodeList.Count < 1) { return; } double distXDir = HelperClass.ShowInputBox("Distance between Macros in X Direction"); int numXDir = Convert.ToInt32(HelperClass.ShowInputBox("Number of Macros in X Direction")); double distYDir = HelperClass.ShowInputBox("Distance between Macros in Y Direction"); int numYDir = Convert.ToInt32(HelperClass.ShowInputBox("Number of Macros in Y Direction")); List <Gcode> DuplicatedList = new List <Gcode>(); foreach (Gcode item in gCodeObject.gCodeList) { Gcode gcodeToCopy = CloneClass.CloneObject <Gcode>(item); DuplicatedList.Add(gcodeToCopy); double distX = item.xStart; double distY = item.yStart; double distYDirFixed = distYDir; for (int x = 0; x <= numXDir; x++) { for (int y = 1; y < numYDir; y++) { distY += distYDirFixed; Gcode copyY = CloneClass.CloneObject <Gcode>(gcodeToCopy); copyY.xStart = distX; copyY.yStart = distY; DuplicatedList.Add(copyY); } distYDirFixed *= -1; distX += distXDir; if (x >= numXDir - 1) { break; } Gcode copyX = CloneClass.CloneObject <Gcode>(gcodeToCopy); copyX.xStart = distX; copyX.yStart = distY; DuplicatedList.Add(copyX); } } gCodeObject.gCodeList = DuplicatedList; gCodeObject.DrawObjects(ref MainCanvas, ref MainCanvasScale, ref GCodeView, ref Arrow, xMeasure, yMeasure); }
public async Task <List <LineBuilder> > BuildGcodeLayerModelListAsync(Gcode gcode, IProgress <int> prog) { gcode.IsWorking = true; var lineBuilders = new List <LineBuilder>(); SortedDictionary <double, LineBuilder> gcodeLayers = new SortedDictionary <double, LineBuilder>(); try { var Commands = gcode.Commands; await Task.Run(() => { try { var temp = new List <LinesVisual3D>(); int i = 0; foreach (List <GcodeCommandLine> commands in Commands) { double z = gcode.ZHeights.Keys.ElementAt(i); Application.Current.Dispatcher.Invoke((() => { LineBuilder builder = BuildLineFromCommands(commands, z); gcodeLayers.Add(z, builder); })); if (prog != null) { double test = (((double)i / Commands.Count) * 100f); if (i < Commands.Count - 1) { prog.Report(Convert.ToInt32(test)); } else { prog.Report(100); } } i++; } } catch (Exception exc) { logger.Error(string.Format(Strings.EventExceptionOccurredFormated, exc.TargetSite, exc.Message)); } }); Application.Current.Dispatcher.Invoke(() => { gcode.LayerModelGenerated = true; lineBuilders = gcodeLayers.Select(pair => pair.Value).ToList(); }); } catch (Exception exc) { logger.Error(string.Format(Strings.EventExceptionOccurredFormated, exc.TargetSite, exc.Message)); } gcode.IsWorking = false; return(lineBuilders); }
private bool LoadStlFile(string filename) { this.stl_file = filename; if (!File.Exists(filename)) { pictureBox1.Image = null; return(false); } int w = 2400; int h = 1600; int xdiv = 12; int ydiv = 8; //slice Stopwatch sw = Stopwatch.StartNew(); Mesh mesh = new Mesh(filename); Console.WriteLine("load stl: {0} ms", sw.ElapsedMilliseconds); sw.Restart(); mesh.ShiftCenter(); mesh.Scale(appset.stl_scale); Console.WriteLine("shift/scale stl: {0} ms", sw.ElapsedMilliseconds); sw.Restart(); //float zstep = (mesh.zmax - mesh.zmin) / (xdiv * ydiv); float zstep = appset.zstep; slices = new Slices(mesh, zstep, appset.slice_tol, appset.z_angle * (float)Math.PI / 180f); Console.WriteLine("total slicing: {0} ms", sw.ElapsedMilliseconds); sw.Restart(); //visualize Visualize vis = new Visualize(w, h); pictureBox1.Image = vis.show_Slices(slices, xdiv, ydiv); Console.WriteLine("visualize: {0} ms", sw.ElapsedMilliseconds); sw.Restart(); //gcode gcode = new Gcode(); gcode.ZStep = appset.zstep; gcode.header = appset.gcode_header; gcode.footer = appset.gcode_footer; gcode.WallThickness = appset.WallThickness; gcode.FilamentDiameter = appset.FilamentDiameter; gcode.PrintSpeed = appset.PrintSpeed; gcode.PrintPerimeter = appset.PrintPerimeter; gcode.Append(slices); Console.WriteLine("gcode: {0} ms", sw.ElapsedMilliseconds); sw.Restart(); //show info txtInfo.Text = gcode.info().Replace(";", "").Replace("\n", "\r\n") + mesh.ToString() + "\r\n" + string.Format("Mesh Facets {0:0.}\r\n", mesh.Facets.Length) + string.Format("Layers {0:0.}\r\n", slices.slices.Count) + string.Format("Line Segments {0:0.}\r\n", slices.LineSegmentCount()); //clear settings isdirty flag appset.IsDirtyClearFlag(); return(true); }
public void BoringGcode() { var src = "G01"; var parser = new Parser(src); var got = parser.ParseGCode(); var shouldBe = new Gcode(1, new List <Argument>(), new Span(0, src.Length)); Assert.Equal(shouldBe, got); }
public void RecogniseADwell() { var duration = 5; var code = new Gcode(4, new List <Argument> { new Argument(ArgumentKind.P, duration * 1000, Span.Empty) }, Span.Empty); var shouldBe = new Noop(initialState, duration); var got = operations.GcodeOp(code, initialState); Assert.Equal(shouldBe, got); }
static void Main(string[] args) { string raw = "G1 F900 X49.728 Y37.435 E2.17868 ;Test"; Command command = Gcode.ParseLine(raw); command.Debug = true; Console.WriteLine(command.ToString()); Console.ReadLine(); }
public void StartProcessingGcode() { if (Gcode != null & (InIdleState | InCheckState)) { rx_buffer_size = Convert.ToInt16(ConfigurationManager.AppSettings["CommandBufferCapacity"]); Gcode.Reset(); GcodeIsRunning = true; lastprocessedindex = 0; QueuedSize = 0; Task.Run(() => ProcessGcode()); } }
public void TestGcodeParseline() { string raw = "G1 F900 X49.728 Y37.435 E2.17868 ;Test"; Command command = Gcode.ParseLine(raw); Assert.AreEqual(command.Text, raw); Assert.AreEqual(command.Code, "G1"); Assert.AreEqual(command.Comment, "Test"); Assert.AreNotEqual(command.Parameters, null); Assert.AreEqual(command.Parameters.Length, 4); Assert.AreEqual(command.Parameters[0], "F900"); Assert.AreEqual(command.Parameters[1], "X49.728"); Assert.AreEqual(command.Parameters[2], "Y37.435"); Assert.AreEqual(command.Parameters[3], "E2.17868"); }
private void DuplicateGcode(double distXDir, int numXDir, double distYDir, int numYDir, int index) { Gcode gcodeToCopy = CloneClass.CloneObject <Gcode>(gCodeObject.gCodeList[index]); double distX = gCodeObject.gCodeList[index].xStart; double distY = gCodeObject.gCodeList[index].yStart; for (int x = 0; x <= numXDir; x++) { for (int y = 1; y < numYDir; y++) { distY += distYDir; Gcode copyY = CloneClass.CloneObject <Gcode>(gcodeToCopy); copyY.xStart = distX; copyY.yStart = distY; gCodeObject.gCodeList.Add(copyY); } distYDir *= -1; distX += distXDir; if (x >= numXDir - 1) { break; } Gcode copyX = CloneClass.CloneObject <Gcode>(gcodeToCopy); copyX.xStart = distX; copyX.yStart = distY; gCodeObject.gCodeList.Add(copyX); } gCodeObject.DrawObjects(ref MainCanvas, ref MainCanvasScale, ref GCodeView, ref Arrow, xMeasure, yMeasure); }
private void ProcessResponse(string _data, bool _iserror = false) { if (GcodeIsRunning) { GcodeLine gcodeline = Gcode.Where(x => x.Index == lastprocessedindex).First(); gcodeline.InSerialBuffer = false; gcodeline.IsProcessed = true; gcodeline.Response = _iserror ? Error.Codes[_data.Split(':')[1]] : _data; GcodeLineChanged?.Invoke(gcodeline, new EventArgs()); ++lastprocessedindex; } else { if (_iserror) { ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(Error.Codes[_data.Split(':')[1]])); } } GetStatus(); }
private void ProcessGcode() { bool takeabreak = false; while (GcodeIsRunning) { GcodeIsRunning = Gcode.Where(x => !x.IsProcessed).FirstOrDefault() != null; takeabreak = !InIdleState & !InCheckState & !InRunState; lock (Gcode) QueuedSize = Gcode.Where(x => !x.IsProcessed & x.InSerialBuffer).Sum(x => x.CommandLength); GcodeLine gcodeline = Gcode.Where(x => !x.IsProcessed & !x.InSerialBuffer).FirstOrDefault(); while (gcodeline != null & !takeabreak && (GcodeIsRunning & ((rx_buffer_size - QueuedSize) >= gcodeline.CommandLength))) { serialport.Write(Command.AddReturn(gcodeline.GrblCommand).ToString()); gcodeline.InSerialBuffer = true; lock (Gcode) QueuedSize = Gcode.Where(x => !x.IsProcessed & x.InSerialBuffer).Sum(x => x.CommandLength); gcodeline = Gcode.Where(x => !x.IsProcessed & !x.InSerialBuffer).FirstOrDefault(); } } }
public virtual void Visit(Gcode code) { }
public Gcode FromXML(string filename, string path) { //log.Debug("In FromXML()"); Gcode clean = null; bool process = false; string compiler = ""; try { // Point to the file string fileLocation = System.IO.Path.Combine(path, filename); try { FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read); // Pass the parameters in XmlReaderSettings xmlSettings = new XmlReaderSettings { // Enable <!ENTITY to be expanded // <!ENTITY chap1 SYSTEM "chap1.xml"> // &chap1; DtdProcessing = DtdProcessing.Parse }; // Open the file and pass in the settings try { Stack <string> stack = new Stack <string>(); string element = ""; string text = ""; string current = ""; // Used to flag what level we are at int level = 1; // Indentation level XmlReader xmlReader = XmlReader.Create(fs, xmlSettings); while (xmlReader.Read()) { switch (xmlReader.NodeType) { #region Element case XmlNodeType.Element: { element = xmlReader.LocalName.ToLower(); if (!xmlReader.IsEmptyElement) { //log.Info(Level(level) + "<" + element + ">"); level = level + 1; } else { //log.Info(Level(level) + "<" + element + "/>"); } switch (element) { #region Book case "clean": { stack.Push(current); current = element; clean = new Gcode(); break; } #endregion default: { stack.Push(current); current = element; break; } } break; } #endregion #region EndElement case XmlNodeType.EndElement: { element = xmlReader.LocalName; level = level - 1; //log.Info(Level(level) + "</" + element + ">"); switch (element) { case "clean": { break; } } current = stack.Pop(); break; } #endregion #region Text case XmlNodeType.Text: { text = xmlReader.Value; text = text.Replace("\t", ""); text = text.Replace("\n", ""); text = text.Trim(); //log.Info(Level(level) + text); switch (current) { case "x": { break; } } break; } #endregion #region Entity case XmlNodeType.Entity: break; #endregion case XmlNodeType.EndEntity: break; case XmlNodeType.Whitespace: break; case XmlNodeType.Comment: break; case XmlNodeType.Attribute: break; default: //log.Info(xmlReader.NodeType); break; } } xmlReader.Close(); // Force the close xmlReader = null; } catch (Exception ex) { //log.Warn("XML Error " + ex.Message); } fs.Close(); fs.Dispose(); // Force the dispose as it was getting left open } catch (FileNotFoundException ex) { //log.Warn("File Error " + ex.Message); } catch (Exception ex) { //log.Warn("File Error " + ex.Message); } } catch (Exception e) { //log.Error("Other Error " + e.Message); } //log.Debug("Out FromXML()"); return(clean); }
public async Task <List <LinesVisual3D> > Create2dGcodeLayerModelListAsync(Gcode gcode, IProgress <int> prog) { gcode.IsWorking = true; var list = new List <LinesVisual3D>(); //var line = new LinesVisual3D(); SortedDictionary <double, LinesVisual3D> gcodeLayers = new SortedDictionary <double, LinesVisual3D>(); //ConcurrentBag<LinesVisual3D> layers = new ConcurrentBag<LinesVisual3D>(); try { var Commands = gcode.Commands; await Task.Run(() => { try { var temp = new List <LinesVisual3D>(); int i = 0; //foreach (List<GCodeCommand> commands in Commands) foreach (List <GcodeCommandLine> commands in Commands) { double z = gcode.ZHeights.Keys.ElementAt(i); var pointsPerLayer = GetLayerPointsCollection(commands, z); if (pointsPerLayer.Count > 0) { Application.Current.Dispatcher.Invoke((() => { gcodeLayers.Add(z, new LinesVisual3D() { Points = new Point3DCollection(pointsPerLayer) }); //layers.Add(new LinesVisual3D() { Points = new Point3DCollection(pointsPerLayer) }); })); } if (prog != null) { float test = (((float)i / Commands.Count) * 100f); if (i < Commands.Count - 1) { prog.Report(Convert.ToInt32(test)); } else { prog.Report(100); } } i++; } } catch (Exception exc) { logger.Error(string.Format(Strings.EventExceptionOccurredFormated, exc.TargetSite, exc.Message)); } }); /**/ Application.Current.Dispatcher.Invoke(() => { gcode.LayerModelGenerated = true; list = gcodeLayers.Select(pair => pair.Value).ToList(); }); //list = layers.ToList(); } catch (Exception exc) { logger.Error(string.Format(Strings.EventExceptionOccurredFormated, exc.TargetSite, exc.Message)); } gcode.IsWorking = false; return(list); } public async Task <List <LinesVisual3D> > Create3dGcodeLayerModelListAsync(Gcode gcode, IProgress <int> prog) { gcode.IsWorking = true; var list = new List <LinesVisual3D>(); SortedDictionary <double, LinesVisual3D> gcodeLayers = new SortedDictionary <double, LinesVisual3D>(); try { var Commands = gcode.Commands; LinesVisual3D normalmoves = new LinesVisual3D(); LinesVisual3D rapidmoves = new LinesVisual3D(); LinesVisual3D wirebox = new LinesVisual3D(); await Task.Run(() => { var temp = new List <LinesVisual3D>(); int i = 0; foreach (List <GcodeCommandLine> commands in Commands) { double z = gcode.ZHeights.Keys.ElementAt(i); for (int j = 0; j < commands.Count; j++) { GcodeCommandLine cmd = commands[j]; if (cmd.Command != "g0" && cmd.Command != "g1" && cmd.Command != "g2" && cmd.Command != "g3") { continue; } double x_prev = !double.IsInfinity(cmd.PrevX) ? cmd.PrevX : 0; double y_prev = !double.IsInfinity(cmd.PrevY) ? cmd.PrevY : 0; double z_prev = !double.IsInfinity(cmd.PrevZ) ? cmd.PrevZ : 0; double x = !double.IsInfinity(cmd.X) ? cmd.X : x_prev; double y = !double.IsInfinity(cmd.Y) ? cmd.Y : y_prev; //z = cmd.Z; switch (cmd.Command) { case "g0": Application.Current.Dispatcher.Invoke((() => { DrawLine(rapidmoves, x_prev, y_prev, z_prev, x, y, z); })); break; case "g1": Application.Current.Dispatcher.Invoke((() => { DrawLine(normalmoves, x_prev, y_prev, z_prev, x, y, z); })); break; case "g2": case "g3": /* * bool clockwise = false; * if (cmd.Command == "g2") * clockwise = true; */ throw new Exception("Not supported!"); } x_prev = x; y_prev = y; z_prev = z; }