private void Message(string message) { string m = message + Path.GetFileName(_sendingFileName); GRBLMachinePlugin.Log("\n" + m); ThisApplication.AddLogMessage(m); }
private static void ReadThread() { _firstParse = true; while (true) { try { string incoming = _serialPort.ReadLine().Trim(' ', '\t', '\r', '\n'); _this.InvokeOnUI(() => { Parse(incoming); }); } catch (System.IO.IOException) { _readThread = null; return; } catch (InvalidOperationException) { _readThread = null; return; } catch (Exception e) { GRBLMachinePlugin.Log(e.ToString()); } } }
public static bool WriteCOMPort(string data) { if (!_this.InvokeRequired) { new Thread(new ParameterizedThreadStart(WriteCOMPortAsync)) { Name = "WriteCOMPortAsync", IsBackground = true }.Start(data); return(true); } try { if (_serialPort.IsOpen) { if ((data.Length + 1) > BUFMAX) { GRBLMachinePlugin.Respond(GRBLMachinePlugin.Response.error, 0); return(false); } GRBLMachinePlugin.Log(">>> " + data); for (int i = 0; i != (data.Length + 1); i++) { _writeSemaphore.Acquire(); } lock (_serialPort) _serialPort.Write(data + '\r'); lock (_writeQueue) _writeQueue.Enqueue(data.Length + 1); return(true); } else { ClearWriteQueue(); GRBLMachinePlugin.Log(data); return(false); } } catch (ThreadInterruptedException) { ClearWriteQueue(); throw; } catch (Exception) { ClearWriteQueue(); return(false); } }
private void MPos_Click(object sender, EventArgs e) { if (!_connected) { return; } GRBLMachinePlugin.PropertyChange("DisplayPosType", GRBLMachinePlugin.Props.DisplayPosType = PosType.MachineCoordinates); CamBamUI.MainUI.ObjectProperties.Refresh(); }
private void FeedUnitInches_Click(object sender, EventArgs e) { if (!_connected) { return; } ConnectionExpander.WriteCOMPort("$13=1"); GRBLMachinePlugin.PropertyChange("ReportInInches", GRBLMachinePlugin.Props.ReportInInches = InchMM.Inches); CamBamUI.MainUI.ObjectProperties.Refresh(); }
private static bool CloseCOMPort(bool immediate = false) { _this.StatusTimer.Enabled = false; try { _serialPort.DtrEnable = false; _serialPort.RtsEnable = false; _serialPort.Close(); _serialPort.Dispose(); GRBLMachinePlugin.Log("Closed: " + _serialPort.PortName); _serialPort = new SerialPort(); if (!immediate) { System.Threading.Thread.Sleep(2000); } Disconnect(); return(true); } catch (Exception) { try { _serialPort.Close(); _serialPort.Dispose(); } catch (Exception) { } Disconnect(); return(false); } }
private void WriteThread() { FileStream fs = null; StreamReader sr = null; try { if (JobStarted != null) { InvokeOnUI(() => { JobStarted(); }); } string s; int i; fs = new FileStream(_sendingFileName, FileMode.Open, FileAccess.Read, FileShare.Read); sr = new StreamReader(fs); Message("Parsing: "); while ((s = sr.ReadLine()) != null) { _pauseEvent.WaitOne(); GRBLMachinePlugin.Log("---" + s, true); bool removeComments = true; foreach (string nrc in _noRemoveCommentGCODEs) { if (s.ToUpper().StartsWith(nrc)) { removeComments = false; break; } } if (removeComments) { StringBuilder line = new StringBuilder(); string[] comments = s.Split('(', ')', ';', '%'); for (i = 1; i < comments.Length; i++) { line.Append(comments[i]); } if (line.Length != 0) { GRBLMachinePlugin.Log("// " + line.ToString()); } if (comments.Length != 0) { line = new StringBuilder(); string[] packed = comments[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string p in packed) { if (_unsupportedGCODEs.Contains(p)) { GRBLMachinePlugin.Log("!! Unsuppported GCODE '" + p + "' skipped"); } else { line.Append(p); } } if (line.Length != 0) { _fileData.AddLast(line.ToString()); } } } else { _fileData.AddLast(s); } } sr.Close(); sr = null; fs.Close(); fs = null; InvokeOnUI(() => { LinesTotal.Text = _fileData.Count.ToString(); LinesSent.Text = "0"; }); Message("Sending: "); i = 0; _lastState = GRBLMachinePlugin.MachineState.Jog; WaitIdle(); foreach (string line in _fileData) { _pauseEvent.WaitOne(); _toolChangingEvent.WaitOne(); if (line.ToUpper().Contains("M6")) { switch (GRBLMachinePlugin.Props.ToolChangeProcess) { case IgnoreProcessPassOn.Ignore: break; case IgnoreProcessPassOn.Process: DoToolChange(line); break; case IgnoreProcessPassOn.PassOn: ConnectionExpander.WriteCOMPort(line); break; } } else { ConnectionExpander.WriteCOMPort(line); } InvokeOnUI(() => { GRBLMachinePlugin.Log("=== " + line, true); LinesSent.Text = (++i).ToString(); }); } } catch (ThreadAbortException) { GRBLMachinePlugin.Log("\naborted"); ConnectionExpander.WriteCOMPort((char)0x18); } catch (ThreadInterruptedException) { GRBLMachinePlugin.Log("\nstopped"); ConnectionExpander.WriteCOMPort((char)0x18); } catch (Exception ex) { InvokeOnUI(() => { MessageBox.Show(ex.ToString()); }); } finally { if (sr != null) { sr.Close(); } if (fs != null) { fs.Close(); } ConnectionExpander.WriteCOMPort("M5"); _writeThread = null; InvokeOnUI(() => { SystemSounds.Asterisk.Play(); Message("Done:"); EnableButtons(); FileName.Enabled = true; BrowseButton.Enabled = true; _pauseEvent.Set(); _toolChangerEvent.Set(); _toolChangingEvent.Set(); if (JobStopped != null) { JobStopped(); } if (!ToolChangeButton.Enabled) { ToolChangeEnd(); } }); } }
private static void Parse(string message) { XPropertyGrid grid = CamBamUI.MainUI.ObjectProperties; GRBLMachinePlugin.Log(message, message.StartsWith("<")); if (_firstParse && message.StartsWith("Grbl")) { string[] greetz = message.Split(' '); if (greetz.Length > 1) { GrblVersion = greetz[1]; GrblIsV1 = GrblVersion.CompareTo("1.1a") >= 0; _this.VersionLabel.Text = GrblVersion; _this.VersionLabel.ForeColor = GrblIsV1 ? Color.LimeGreen : (GrblVersion.CompareTo("0.8") >= 0 ? Color.Orange : Color.Red); } _firstParse = false; WriteCOMPort("$$"); WriteCOMPort("$N"); _this.StatusTimer.Enabled = true; } if (message.StartsWith("<") && message.EndsWith(">")) { if (!GrblIsV1) { //Version < 1.1 ==> "<Idle,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>" char[] charmessage = message.ToCharArray(); charmessage[message.IndexOf(",MPos:")] = '|'; charmessage[message.IndexOf(",WPos:")] = '|'; message = new string(charmessage); // ==> "<Idle|MPos:0.000,0.000,0.000|WPos:0.000,0.000,0.000>" } string[] report = message.Split('<', '|', '>'); if (report.Length > 2) { // report[0] = "" // report[1] = Idle string[] states = report[1].Split(':'); GRBLMachinePlugin.Stat((GRBLMachinePlugin.MachineState)Enum.Parse(typeof(GRBLMachinePlugin.MachineState), states[0], true), states.Length > 1 ? int.Parse(states[1]) : -1); if (report.Length > 3) // report[2] = MPos:0.000,0.000,0.00 { string[] pos = report[2].Split(':', ','); PosType type = PosType.Unknown; double x = double.NaN; double y = double.NaN; double z = double.NaN; if (pos.Length > 0) { switch (pos[0].ToUpper()) { case "MPOS": type = PosType.MachineCoordinates; break; case "WPOS": type = PosType.WorkCoordinates; break; } } if (pos.Length > 1) { x = double.Parse(pos[1], EN_US); } if (pos.Length > 2) { y = double.Parse(pos[2], EN_US); } if (pos.Length > 3) { z = double.Parse(pos[3], EN_US); } GRBLMachinePlugin.Pos(type, x, y, z); if (report.Length > 4) // report[3] = WPos:0.000,0.000,0.000 { string[] speeds = report[3].Split(':', ','); switch (speeds[0].ToUpper()) { case "F": GRBLMachinePlugin.Speeds(double.Parse(speeds[1], EN_US), 0); break; case "FS": GRBLMachinePlugin.Speeds(double.Parse(speeds[1], EN_US), int.Parse(speeds[2], EN_US)); break; case "WPOS": { double wx = double.NaN; double wy = double.NaN; double wz = double.NaN; if (speeds.Length > 1) { wx = double.Parse(speeds[1], EN_US); } if (speeds.Length > 2) { wy = double.Parse(speeds[2], EN_US); } if (speeds.Length > 3) { wz = double.Parse(speeds[3], EN_US); } if (!double.IsNaN(wx) && !double.IsNaN(x)) { wx = (x - wx); } if (!double.IsNaN(wy) && !double.IsNaN(y)) { wy = (y - wy); } if (!double.IsNaN(wz) && !double.IsNaN(z)) { wz = (z - wz); } GRBLMachinePlugin.Pos(PosType.WCO, wx, wy, wz); } break; } if (report.Length > 5) { pos = report[4].Split(':', ','); switch (pos[0].ToUpper()) { case "WCO": type = PosType.Unknown; x = double.NaN; y = double.NaN; z = double.NaN; if (pos.Length > 0) { type = (PosType)Enum.Parse(typeof(PosType), pos[0], true); } if (pos.Length > 1) { x = double.Parse(pos[1], EN_US); } if (pos.Length > 2) { y = double.Parse(pos[2], EN_US); } if (pos.Length > 3) { z = double.Parse(pos[3], EN_US); } GRBLMachinePlugin.Pos(type, x, y, z); break; case "OV": break; } } } } } } else if (message.Equals("ok", StringComparison.OrdinalIgnoreCase)) { lock (_writeQueue) { if (_writeQueue.Count == 0) { _writeSemaphore.Reset(BUFMAX); } else { int n = _writeQueue.Dequeue(); for (int i = 0; i != n; i++) { _writeSemaphore.Release(); } } } GRBLMachinePlugin.Respond(GRBLMachinePlugin.Response.ok); } else if (message.StartsWith("error", StringComparison.OrdinalIgnoreCase)) { string[] error = message.Split(':'); int code = (error.Length > 1 && GrblIsV1) ? int.Parse(error[1]) : 0; if (code > 0) { GRBLMachinePlugin.Log(ErrorDict[code]); } ClearWriteQueue(); GRBLMachinePlugin.Respond(GRBLMachinePlugin.Response.error, code); } else if (message.StartsWith("alarm", StringComparison.OrdinalIgnoreCase)) { string[] alarm = message.Split(':'); int code = (alarm.Length > 1 && GrblIsV1) ? int.Parse(alarm[1]) : 0; if (code > 0) { GRBLMachinePlugin.Log(AlarmDict[code]); } ClearWriteQueue(); GRBLMachinePlugin.Respond(GRBLMachinePlugin.Response.alarm, code); GRBLMachinePlugin.Stat(GRBLMachinePlugin.MachineState.Alarm, code); } else if (message.StartsWith("$N")) { string[] dollar = message.Split('='); switch (dollar[0]) { case "$N0": GRBLMachinePlugin.Props.Startup1 = dollar[1]; break; //Startup Block 0 case "$N1": GRBLMachinePlugin.Props.Startup2 = dollar[1]; break; //Startup Block 0 } if (grid.SelectedObject == GRBLMachinePlugin.Props) { grid.Refresh(); } } else if (message.StartsWith("$")) { string[] dollar = message.Split('=', ';', '('); double val = double.Parse(dollar[1], EN_US); switch (dollar[0]) { case "$0": GRBLMachinePlugin.Props.StepPulseTime = (int)val; break; //(Step pulse time, microseconds) case "$1": GRBLMachinePlugin.Props.StepIdleDelay = (int)val; break; //(Step idle delay, milliseconds) case "$2": GRBLMachinePlugin.Props.StepPulseInvert = (InvertMask)val; break; //(Step pulse invert, mask) case "$3": GRBLMachinePlugin.Props.StepDirectionInvert = (InvertMask)val; break; //(Step direction invert, mask) case "$4": GRBLMachinePlugin.Props.InvertStepEnablePin = val != 0; break; //(Invert step enable pin, boolean) case "$5": GRBLMachinePlugin.Props.InvertLimitPins = val != 0; break; //(Invert limit pins, boolean) case "$6": GRBLMachinePlugin.Props.InvertProbePin = val != 0; break; //(Invert probe pin, boolean) case "$10": GRBLMachinePlugin.Props.StatusReportOptions = (int)val; break; //(Status report options, mask) case "$11": GRBLMachinePlugin.Props.JunctionDeviation = val; break; //(Junction deviation, millimeters) case "$12": GRBLMachinePlugin.Props.ArcTolerance = val; break; //(Arc tolerance, millimeters) case "$13": GRBLMachinePlugin.Props.ReportInInches = (InchMM)val; GRBLMachinePlugin.PropertyChange("ReportInInches", (InchMM)val); break; //(Report in inches, boolean) case "$20": GRBLMachinePlugin.Props.SoftLimitsEnable = (EnabledDisabled)val; break; //(Soft limits enable, boolean) case "$21": GRBLMachinePlugin.Props.HardLimitsEnable = (EnabledDisabled)val; break; //(Hard limits enable, boolean) case "$22": GRBLMachinePlugin.Props.HomingCycleEnable = (EnabledDisabled)val; GRBLMachinePlugin.PropertyChange("HomingCycleEnable", (EnabledDisabled)val); break; //(Homing cycle enable, boolean) case "$23": GRBLMachinePlugin.Props.HomingDirectionInvert = (InvertMask)val; break; //(Homing direction invert, mask) case "$24": GRBLMachinePlugin.Props.HomingLocateFeedRate = val; break; //(Homing locate feed rate, mm/min) case "$25": GRBLMachinePlugin.Props.HomingSearchSeekRate = val; break; //(Homing search seek rate, mm/min) case "$26": GRBLMachinePlugin.Props.HomingSwitchDebounceDelay = (int )val; break; //(Homing switch debounce delay, milliseconds) case "$27": GRBLMachinePlugin.Props.HomingSwitchPullOffDistance = val; break; //(Homing switch pull-off distance, millimeters) case "$30": GRBLMachinePlugin.Props.MaximumSpindleSpeed = (int)val; break; //(Maximum spindle speed, RPM) case "$31": GRBLMachinePlugin.Props.MinimumSpindleSpeed = (int)val; break; //(Minimum spindle speed, RPM) case "$32": GRBLMachinePlugin.Props.LaserModeEnable = (EnabledDisabled)val; GRBLMachinePlugin.PropertyChange("LaserModeEnable", (EnabledDisabled)val); break; //(Laser-mode enable, boolean) case "$100": GRBLMachinePlugin.Props.X.Resolution = val; break; //(X-axis travel resolution, step/mm) case "$101": GRBLMachinePlugin.Props.Y.Resolution = val; break; //(Y-axis travel resolution, step/mm) case "$102": GRBLMachinePlugin.Props.Z.Resolution = val; break; //(Z-axis travel resolution, step/mm) case "$110": GRBLMachinePlugin.Props.X.MaximumRate = val; break; //(X-axis maximum rate, mm/min) case "$111": GRBLMachinePlugin.Props.Y.MaximumRate = val; break; //(Y-axis maximum rate, mm/min) case "$112": GRBLMachinePlugin.Props.Z.MaximumRate = val; break; //(Z-axis maximum rate, mm/min) case "$120": GRBLMachinePlugin.Props.X.Acceleration = val; break; //(X-axis acceleration, mm/sec^2) case "$121": GRBLMachinePlugin.Props.Y.Acceleration = val; break; //(Y-axis acceleration, mm/sec^2) case "$122": GRBLMachinePlugin.Props.Z.Acceleration = val; break; //(Z-axis acceleration, mm/sec^2) case "$130": GRBLMachinePlugin.Props.X.AxisMaximumTravel = val; GRBLMachinePlugin.PropertyChange("AxisMaximumTravel", val); break; //(X-axis maximum travel, millimeters) case "$131": GRBLMachinePlugin.Props.Y.AxisMaximumTravel = val; GRBLMachinePlugin.PropertyChange("AxisMaximumTravel", val); break; //(Y-axis maximum travel, millimeters) case "$132": GRBLMachinePlugin.Props.Z.AxisMaximumTravel = val; GRBLMachinePlugin.PropertyChange("AxisMaximumTravel", val); break; //(Z-axis maximum travel, millimeters) default: break; } if (grid.SelectedObject == GRBLMachinePlugin.Props) { grid.Refresh(); } } }
private static bool OpenCOMPort(bool reportException = true) { if (string.IsNullOrEmpty(GRBLMachinePlugin.Props.COMPort)) { return(false); } try { if (_serialPort.IsOpen) { _serialPort.Close(); _serialPort.Dispose(); _serialPort = new SerialPort(); System.Threading.Thread.Sleep(100); } _serialPort.PortName = GRBLMachinePlugin.Props.COMPort; _serialPort.DataBits = 8; _serialPort.StopBits = System.IO.Ports.StopBits.One; _serialPort.Parity = System.IO.Ports.Parity.None; _serialPort.BaudRate = GRBLMachinePlugin.Props.Baudrate; _serialPort.Handshake = System.IO.Ports.Handshake.None; _serialPort.ReadTimeout = -1; _serialPort.RtsEnable = false; _serialPort.DtrEnable = false; _serialPort.Open(); GRBLMachinePlugin.Log("Opened: " + _serialPort.PortName); if (_readThread == null) { _readThread = new System.Threading.Thread(ReadThread); _readThread.IsBackground = true; _readThread.Name = "PortReader"; _readThread.Start(); } _serialPort.RtsEnable = true; _serialPort.DtrEnable = true; ClearWriteQueue(); System.Threading.Thread.Sleep(10); Connect(); return(true); } catch (Exception e) { if (reportException) { GRBLMachinePlugin.Log(e.ToString()); } Disconnect(); return(false); } }