public bool OpenDeviceByLocation(uint LocationID) { if (USB_Interface.IsOpen) { USB_Interface.Close(); } ExtLog.AddLine("Opening device"); var ftStatus = USB_Interface.OpenByLocation(LocationID); if (ftStatus != FTDI.FT_STATUS.FT_OK) { ExtLog.AddLine("Failed to open device (error " + ftStatus + ")"); return(false); } ExtLog.AddLine("Setting default bauld rate (" + GlobalProperties.baudRate + ")"); ftStatus = USB_Interface.SetBaudRate(GlobalProperties.baudRate); if (ftStatus != FTDI.FT_STATUS.FT_OK) { ExtLog.AddLine("Failed to set Baud rate (error " + ftStatus + ")"); return(false); } ExtLog.AddLine("Setting BitMode"); ftStatus = USB_Interface.SetBitMode(GlobalProperties.portDirectionMask, FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_BITBANG); if (ftStatus != FTDI.FT_STATUS.FT_OK) { ExtLog.AddLine("Failed to set BitMode (error " + ftStatus + ")"); return(false); } UpdateProgress(100, true); return(true); }
public bool MoveTo(float X, float Y) { var success = false; var current_pos = CurrentLocation(); if (!MaxXswitch && !MinXswitch && !MaxYswitch && !MinYswitch) { var deltaX = X - current_pos.X; var deltaY = Y - current_pos.Y; if (OnMove != null) { OnMove(X, Y); } success = MoveBy((int)(deltaX * GlobalProperties.X_Scale), (int)(deltaY * GlobalProperties.Y_Scale)); if (OnMoveCompleted != null) { OnMoveCompleted(); } } else { ExtLog.AddLine("Limit switch warning must be cleared before moving."); } return(success); }
private void RemoveDuplicates() { var dup = new bool[Shapes.Count]; for (var i = 0; i < Shapes.Count; i++) { if (!dup[i]) { for (var j = 0; j < Shapes.Count; j++) { if ((i != j) && (!dup[j])) { var dist = Math.Sqrt(Math.Pow(Shapes[i].x - Shapes[j].x, 2) + Math.Pow(Shapes[i].y - Shapes[j].y, 2)); dup[j] = (dist < NodeEpsilon); } } } } for (var i = 0; i < Shapes.Count; i++) { Shapes[i].isDuplicate = dup[i]; } Shapes.RemoveAll(d => d.isDuplicate); ExtLog.AddLine(Shapes.Count + " Uniques"); }
private void removeZeros() { DrillNodes.RemoveAll( dn => (Math.Sqrt(Math.Pow(dn.location.X, 2) + Math.Pow(dn.location.Y, 2)) < NodeEpsilon)); ExtLog.AddLine(DrillNodes.Count.ToString("D") + " Non-Zeros"); }
private void SeekShape(StreamReader reader) { while (!reader.EndOfStream) { var l = reader.ReadLine(); if (l != null) { if (l.StartsWith("<Shape ID=")) { Shapes.Add(readUntilEndOfShape(reader)); } if (l.StartsWith("<PageWidth Unit='IN'>")) { PageWidth = SafeFloatParse(TrimString(l, "<PageWidth Unit='IN'>", "</PageWidth>"), PageWidth); } if (l.StartsWith("<PageHeight Unit='IN'>")) { PageHeight = SafeFloatParse(TrimString(l, "<PageHeight Unit='IN'>", "</PageHeight>"), PageHeight); } //<PageWidth Unit='IN'>8.5</PageWidth> //<PageHeight Unit='IN'>11</PageHeight> } } ExtLog.AddLine(Shapes.Count.ToString("D") + " Shapes"); }
private void removeDuplicates() { var duplicates = new bool[DrillNodes.Count]; for (var i = 0; i < DrillNodes.Count; i++) { if (!duplicates[i]) { for (var j = 0; j < DrillNodes.Count; j++) { if ((i != j) && (!duplicates[j]) && (sameLocation(DrillNodes[i], DrillNodes[j]))) { duplicates[j] = true; } } } } for (var i = duplicates.Length - 1; i >= 0; i--) { if (duplicates[i]) { DrillNodes.RemoveAt(i); } } ExtLog.AddLine(DrillNodes.Count.ToString("D") + " Uniques"); }
private void cancelTask() { if (asyncWorker.IsBusy) { ExtLog.AddLine("Cancelling Task..."); asyncWorker.CancelAsync(); } }
private void RemoveZero() { for (var i = 0; i < Shapes.Count; i++) { Shapes[i].isZero = (Math.Abs(Shapes[i].x) < float.Epsilon) && (Math.Abs(Shapes[i].y) < float.Epsilon); } Shapes.RemoveAll(d => d.isZero); ExtLog.AddLine(Shapes.Count + " Non-zeros"); }
public void asyncWorkerDoWork_DrillAll(object sender, DoWorkEventArgs e) { var nodes = e.Argument as List <DrillNode> ?? new List <DrillNode>(); var success = nodes.Count > 0; if (success) { for (var i = 0; i < nodes.Count; i++) { if (!asyncWorker.CancellationPending) { if (success && USB.Check_Limit_Switches() && USB.TopSwitch && !USB.BottomSwitch) { if (nodes[i].status != DrillNode.DrillNodeStatus.Drilled) { UpdateNodes(i, DrillNode.DrillNodeStatus.Next); ExtLog.AddLine("Moving to [" + (i + 1) + "/" + nodes.Count + "]: " + nodes[i].Location); USB.MoveTo(nodes[i].location.X, nodes[i].location.Y); ExtLog.AddLine("Drilling..."); //start drill from top if (USB.IsOpen && USB.Check_Limit_Switches()) { success = Initiate_Drill_From_Top(20, 50); } //wait for drill to reach back top if (success && USB.IsOpen && USB.Check_Limit_Switches()) { success = Wait_For_Drill_To_Top(20, 50); } UpdateNodes(i, DrillNode.DrillNodeStatus.Drilled); asyncWorker.ReportProgress(100 * (i + 1) / nodes.Count, true); } else { ExtLog.AddLine("Node [" + (i + 1) + "/" + nodes.Count + "] already drilled"); } } else { success = false; } } else { e.Cancel = true; } } } asyncWorker.ReportProgress(100); e.Result = success; }
private void asyncWorkerProgressChange(object sender, ProgressChangedEventArgs e) { var inhibit = e.UserState as bool? ?? false; if (!inhibit) { ExtLog.AddLine("Progress: " + e.ProgressPercentage.ToString("D") + "%"); } taskDialog.update(e.ProgressPercentage); }
public static List <DrillNode> OptimizeNodesVScanLine(List <DrillNode> Nodes, PointF StartLocation) { if (Nodes.Count > 2) { ExtLog.AddLine("Optimizing node sequence (V-scanlines)"); var oldPathLength = getPathLength(Nodes, StartLocation); var oldNodesCount = Nodes.Count; var newXNodes = new List <DrillNode>(Nodes); newXNodes.Sort(X_Sort_Ascending_Predicate); var outputNodes = new List <DrillNode>(); var itteration = 0; for (var i = 0; i < newXNodes.Count; i++) { var target_X = newXNodes[i].location.X; var X_list = newXNodes.Where(n => Math.Abs(n.location.X - target_X) < OptimizationEpsilon).ToList(); if ((itteration % 2) == 0) { X_list.Sort(Y_Sort_Ascending_Predicate); } else { X_list.Sort(Y_Sort_Descending_Predicate); } outputNodes.AddRange(X_list); i += X_list.Count - 1; itteration++; } if (outputNodes.Count == oldNodesCount) { var X_Length = getPathLength(outputNodes, StartLocation); if (X_Length < oldPathLength) { outputNodes.ForEach(ResetNodeStatus_Predicate); ExtLog.AddLine("Path of " + X_Length.ToString("F4") + " / " + oldPathLength.ToString("F4")); return(outputNodes); } ExtLog.AddLine("Optimize Failed (new path length is longer)"); } else { ExtLog.AddLine("Optimize Failed (nodes count mismatch)"); } } else { ExtLog.AddLine("Not enough nodes to optimize path."); } return(Nodes); }
private void DrillAllNodebutton_Click(object sender, EventArgs e) { if ((Nodes != null) && (Nodes.Count > 0)) { TaskRunner.startAsyncWorkerWithTask("Drill All Nodes (Async)...", TaskRunner.asyncWorkerDoWork_DrillAll, asyncWorkerDoWork_DrillAll_Cleanup, Nodes); } else { ExtLog.AddLine("No Nodes to Drill"); } }
private void asyncWorkerDoWork_DrillSelected_Cleanup(bool success) { if (success) { ExtLog.AddLine("Task Completed"); Nodes[listBox1.SelectedIndex].status = DrillNode.DrillNodeStatus.Drilled; UpdateNodeColors(); } else { ExtLog.AddLine("Drill Sequence Failed"); } }
private void asyncWorkerDoWork_FindAxisOrigin_Cleanup(bool success) { ExtLog.AddLine("Task Completed"); if (success) { var loc = USB.CurrentLocation(); ExtLog.AddLine("Location Set to Zero, Origin was found at X=" + loc.X.ToString("F3") + " Y=" + loc.Y.ToString("F3")); zeroAllbutton_Click(this, null); } else { ExtLog.AddLine("Origin not found (out of reach / farther than 1 inch from expected location)"); } }
private void ReadNodes(string filename) { Shapes = new List <rawShapeData>(); try { var f = File.OpenText(filename); SeekShape(f); f.Close(); } catch (IOException ex) { ExtLog.AddLine(ex.Message); DrillNodes.Clear(); } }
private void AsyncDrillSelectedButton_Click(object sender, EventArgs e) { if ((listBox1.SelectedIndex > 0) && (listBox1.SelectedIndex <= Nodes.Count)) { Nodes[listBox1.SelectedIndex].status = DrillNode.DrillNodeStatus.Next; UpdateNodeColors(); var toDrill = Nodes[listBox1.SelectedIndex].location; TaskRunner.startAsyncWorkerWithTask("Drill Selected Node (Async)...", TaskRunner.asyncWorkerDoWork_DrillSelected, asyncWorkerDoWork_DrillSelected_Cleanup, toDrill); } else { ExtLog.AddLine("Invalid Selection"); } }
public void startAsyncWorkerWithTask(string desc, DoWorkEventHandler asyncWork, CleanupDelegate asyncCleanup, object argument) { if (!asyncWorker.IsBusy) { if (USB.Check_Limit_Switches() && USB.IsOpen) { ExtLog.AddLine("Starting Async Task"); USB.Inhibit_LimitSwitches_Warning = true; HostControl.Enabled = false; try { ExtLog.AddLine(desc); asyncWorker.DoWork += asyncWork; lastTask = asyncWork; CleanupCallback = asyncCleanup; asyncWorker.RunWorkerAsync(argument); } catch (Exception ex) { ExtLog.AddLine("Async Task failed: " + ex.Message); } ExtLog.AddLine("Async Started"); if (taskDialog.ShowDialog(HostControl) == DialogResult.Abort) { cancelTask(); USB.CancelMove(); } HostControl.Enabled = true; USB.Inhibit_LimitSwitches_Warning = false; } else { ExtLog.AddLine("Can't init scripted sequence, limit switches are not properly set or USB interface is Closed"); } } else { ExtLog.AddLine("Async Task Already Running"); } }
private void asyncWorkerComplete(object sender, RunWorkerCompletedEventArgs e) { asyncWorker.DoWork -= lastTask; taskDialog.done(); if (e.Error != null) { ExtLog.AddLine("Error running Task: " + e.Error.Message); } else if (e.Cancelled) { ExtLog.AddLine("Task Cancelled"); } else { var success = e.Result as bool? ?? false; if (CleanupCallback != null) { CleanupCallback(success); } } }
public List <string> GetDevicesList() { var result = new List <string>(); uint numUI = 0; var ftStatus = USB_Interface.GetNumberOfDevices(ref numUI); if (ftStatus == FTDI.FT_STATUS.FT_OK) { if (numUI > 0) { ExtLog.AddLine(numUI.ToString("D") + " Devices Found."); var ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[numUI]; ftStatus = USB_Interface.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (var i = 0; i < numUI; i++) { result.Add(ftdiDeviceList[i].LocId.ToString("D4") + ":" + ftdiDeviceList[i].Description); } } else { ExtLog.AddLine("Failed to list devices (error " + ftStatus + ")"); } } else { ExtLog.AddLine("No devices found."); } } else { ExtLog.AddLine("Failed to get number of devices (error " + ftStatus + ")"); } return(result); }
private void readCircles(string filename) { var svgReader = SvgDocument.Open(filename); PageHeight = svgReader.Width.Value; PageHeight = svgReader.Height.Value; var circlesEnum = svgReader.Children.FindSvgElementsOf <SvgCircle>(); var circlesList = circlesEnum as IList <SvgCircle> ?? circlesEnum.ToList(); for (var i = 0; i < circlesList.Count; i++) { var pt = new[] { new PointF(circlesList[i].CenterX.Value, circlesList[i].CenterY.Value) }; applyParentsTransforms(pt, circlesList[i].Parent); pt[0].X /= 72; //svgReader.Ppi; pt[0].Y /= 72; //svgReader.Ppi; DrillNodes.Add(new DrillNode(pt[0], i)); } ExtLog.AddLine(DrillNodes.Count.ToString("D") + " Shapes"); }
private bool SendToUSB() { var result = true; uint res = 0; var ftStatus = USB_Interface.Write(OutputBuffer, dataSize, ref res); if ((ftStatus != FTDI.FT_STATUS.FT_OK) && (res != dataSize)) { USB_Interface.Close(); ExtLog.AddLine(string.Format("Failed to write data (error {0}) ({1}/{2})", ftStatus, res, dataSize)); result = false; } else { ftStatus = USB_Interface.Read(InputBuffer, (uint)dataSize, ref res); if ((ftStatus != FTDI.FT_STATUS.FT_OK) && (res != dataSize)) { USB_Interface.Close(); ExtLog.AddLine(string.Format("Failed to write data (error {0}) ({1}/{2})", ftStatus, res, dataSize)); result = false; } } return(result); }
public static List <DrillNode> OptimizeNodesNN(List <DrillNode> Nodes, PointF StartLocation) { if (Nodes.Count > 2) { ExtLog.AddLine("Optimizing node sequence (nearest neighbor)"); var oldPathLength = getPathLength(Nodes, StartLocation); var oldNodesCount = Nodes.Count; var nodes = new List <DrillNode>(Nodes); var CurrentPosition = StartLocation; var newNodes = new List <DrillNode>(); var dists = GetNodeDistances(nodes, CurrentPosition); var Closest = 0; for (var i = 0; i < dists.Length; i++) { if (dists[i] < dists[Closest]) { Closest = i; } } newNodes.Add(nodes[Closest]); nodes.Remove(nodes[Closest]); for (var j = 0; j < oldNodesCount - 1; j++) { CurrentPosition = newNodes[newNodes.Count - 1].location; dists = GetNodeDistances(nodes, CurrentPosition); Closest = 0; for (var i = 0; i < dists.Length; i++) { if (dists[i] < dists[Closest]) { Closest = i; } } newNodes.Add(nodes[Closest]); nodes.Remove(nodes[Closest]); } var newPathLength = getPathLength(newNodes, StartLocation); var newNodesCount = newNodes.Count; if (newPathLength <= oldPathLength) { if (newNodesCount == oldNodesCount) { newNodes.ForEach(ResetNodeStatus_Predicate); ExtLog.AddLine("Path of " + newPathLength.ToString("F4") + " / " + oldPathLength.ToString("F4")); return(newNodes); } ExtLog.AddLine("Optimize Failed (nodes count mismatch)"); } else { ExtLog.AddLine("Optimize Failed (new path length is longer)"); } } else { ExtLog.AddLine("Not enough nodes to optimize path."); } return(Nodes); }
private void asyncWorkerDoWork_DrillAll_Cleanup(bool success) { ExtLog.AddLine(success ? "Task Completed" : "Drill Sequence Failed"); }
public bool MoveBy(int byX, int byY) { cancelJob = false; var success = true; var abyX = Math.Abs(byX); var abyY = Math.Abs(byY); //process directions var XStepDirection = (byX == 0) ? 0 : byX / abyX; var YStepDirection = (byY == 0) ? 0 : byY / abyY; //process backlash X_Last_Direction = XStepDirection; Y_Last_Direction = YStepDirection; //process moves var numMoves = (abyX >= abyY) ? abyX : abyY; var stridex = 1.0f; //default maximum stride var stridey = 1.0f; if ((abyX != 0) || (abyY != 0)) //adjust stride { if (abyX > abyY) { stridey = (float)abyY / abyX; } else if (abyY > abyX) { stridex = (float)abyX / abyY; } } var fractx = 0.0f; var fracty = 0.0f; for (var i = 0; i < numMoves; i++) { fractx += stridex; fracty += stridey; if (fractx >= 0.5f) { X_Abs_Location += XStepDirection; fractx -= 1.0f; } if (fracty >= 0.5f) { Y_Abs_Location += YStepDirection; fracty -= 1.0f; } Transfer(); UpdateProgress(100 * i / numMoves, false); if (!Check_Limit_Switches()) { if (!Inhibit_LimitSwitches_Warning) { ExtLog.AddLine("Limit switch triggered before end of move"); } i = numMoves; //exit loop success = false; } if (jobCancelled()) { ExtLog.AddLine("Move Cancelled"); i = numMoves; //exit loop success = false; } } UpdateProgress(100, true); return(success); }
private void LoadFileButton_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { if (dtypeDialog.ShowDialog() == DialogResult.OK) { if (File.Exists(openFileDialog1.FileName)) { ExtLog.AddLine("Opening File: " + openFileDialog1.FileName); var loader = (INodeLoader)null; if (openFileDialog1.FileName.ToUpperInvariant().EndsWith(".VDX")) { loader = new VDXLoader(); } else if (openFileDialog1.FileName.ToUpperInvariant().EndsWith(".SVG")) { loader = new SVGLoader(); } else { ExtLog.AddLine("File Type not supported."); } if (loader != null) { loader.PageWidth = 11.0f; loader.PageHeight = 11.0f; loader.DrillNodes = new List <DrillNode>(); var dresult = dtypeDialog.DrawingConfig; loader.Load(openFileDialog1.FileName, dresult); Nodes = loader.DrillNodes; if (dresult.reset_origin) { var leftmost = loader.PageWidth; var topmost = loader.PageHeight; for (var i = 0; i < Nodes.Count; i++) { if (Nodes[i].location.X < leftmost) { leftmost = Nodes[i].location.X; } if (Nodes[i].location.Y < topmost) { topmost = Nodes[i].location.Y; } } XoriginTextbox.Text = (leftmost - dresult.origin_x).ToString("F4"); YoriginTextbox.Text = (topmost - dresult.origin_y).ToString("F4"); OffsetOriginBtton_Click(sender, e); } ExtLog.AddLine(Nodes.Count.ToString("D") + " Nodes loaded."); ExtLog.AddLine("Page Width: " + loader.PageWidth.ToString("F1")); ExtLog.AddLine("Page Height: " + loader.PageHeight.ToString("F1")); drawingPageBox = new Box(0, 0, loader.PageWidth, loader.PageHeight, Color.GhostWhite); lastSelectedStatus = DrillNode.DrillNodeStatus.Idle; RebuildListBoxAndViewerFromNodes(); lastSelectedIndex = -1; } } } } }
public bool MoveBy(int byX, int byY) { cancelJob = false; var success = true; var abyX = Math.Abs(byX); var abyY = Math.Abs(byY); //process directions var XStepDirection = (byX == 0) ? 0 : byX / abyX; var YStepDirection = (byY == 0) ? 0 : byY / abyY; //process backlash if (!Inhibit_Backlash_Compensation) { if ((XStepDirection != 0) && (XStepDirection != X_Last_Direction)) { abyX += GlobalProperties.X_Backlash; X_Delta += GlobalProperties.X_Backlash * XStepDirection; X_Last_Direction = XStepDirection; } if ((YStepDirection != 0) && (YStepDirection != Y_Last_Direction)) { abyY += GlobalProperties.Y_Backlash; Y_Delta += GlobalProperties.Y_Backlash * YStepDirection; Y_Last_Direction = YStepDirection; } } else { X_Last_Direction = XStepDirection; Y_Last_Direction = YStepDirection; } //Enable TQA Driver if requested TQA_Driver_Bit = TQA_Driver_Enable; Transfer(); //process moves var numMoves = (abyX >= abyY) ? abyX : abyY; var stridex = 1.0f; //default maximum stride var stridey = 1.0f; if ((abyX != 0) || (abyY != 0)) //adjust stride { if (abyX > abyY) { stridey = (float)abyY / abyX; } else if (abyY > abyX) { stridex = (float)abyX / abyY; } } var fractx = 0.0f; var fracty = 0.0f; for (var i = 0; i < numMoves; i++) { fractx += stridex; fracty += stridey; if (fractx >= 0.5f) { X_Abs_Location += XStepDirection; fractx -= 1.0f; } if (fracty >= 0.5f) { Y_Abs_Location += YStepDirection; fracty -= 1.0f; } Transfer(); UpdateProgress(100 * i / numMoves, false); if (!Check_Limit_Switches()) { if (!Inhibit_LimitSwitches_Warning) { ExtLog.AddLine("Limit switch triggered before end of move"); } i = numMoves; //exit loop success = false; } if (jobCancelled()) { ExtLog.AddLine("Move Cancelled"); i = numMoves; //exit loop success = false; } } UpdateProgress(100, true); TQA_Driver_Bit = false; //Disable TQA Driver Transfer(); return(success); }
private void RemoveNonEllipses() { Shapes.RemoveAll(d => !d.isEllipse); ExtLog.AddLine(Shapes.Count + " Ellipses"); }