Ejemplo n.º 1
0
		public override ScanData DoTask(ScanData source)
		{
			ScanData step1 = base.DoTask(source);
			step1.Sort(); //SORT
            Dictionary<string, ScanLine> step2 = new Dictionary<string, ScanLine>();
			for (int i = 0; i < step1.Count; i++)
			{
				ScanLine line = step1[i];
				if (line.Count > 0)
				{
                    for (int c = 0; c < NumClass; c++)
                    {
                        string key = string.Format("{0}->{1}", line.LaserID, c);
                        if (!step2.ContainsKey(key))
                            step2[key] = new ScanLine(line.LaserID, NumClass);
                        step2[key].Add(GetSample(line, NumClass, c));
                    }

					//step2[line.LaserID].Add(line[0]);
				}
			}

			ScanData step3 = new ScanData(step2.Keys.Count);
			for (int i = 0; i < step2.Keys.Count; i++)
            {
                string k = step2.Keys.ElementAt(i);
                step3.Add(step2[k]);

            }
			return step3;
		}
Ejemplo n.º 2
0
        private void Insert(string data)
        {
            try
            {
                ScanData @new = new ScanData
                {
                    IdScanner           = ScannerId,
                    IdUser              = UserId,
                    IdType              = (int)ScanType,
                    AdditionalServiceId = ServiceId,
                    DataValue           = data,
                    ScannedAt           = DateTime.Now
                };

                if (!IsUnique(@new))
                {
                    OnUnique(this, new OnUniqueArg(@new)); //ponowny skan
                    return;
                }

                int affected = Database.Insert(@new);
                if (affected > 0)
                {
                    OnInsert(this, new OnInsertArg(@new));
                }
            }
            catch (Exception e)
            {
                OnError(this, new OnErrorArg(e.Message));
            }
        }
Ejemplo n.º 3
0
        //public void GetCycleCountList()
        //{
        //    string error = "";
        //    isDatabindingCycleCountList = true;

        //    var cycleCountNumbers = cycle.GetCycleCountNumbers(out error);
        //    if (error != "")
        //    {
        //        alert.ShowError(alertLevel.High, error, "GetCycleCountList() Error");
        //        return;
        //    }
        //    if (cycleCountNumbers == null)
        //    {
        //        alert.ShowError(alertLevel.High, "There are no active Cycle Counts.", "GetCycleCountList() Error");
        //        return;
        //    }
        //    cycleCountForm.cbxCycleCount.DataSource = cycleCountNumbers;
        //    cycleCountForm.cbxCycleCount.DisplayMember = "Description";
        //    cycleCountForm.cbxCycleCount.ValueMember = "CycleCountNumber";

        //    SelectedCycleCount = cycleCountForm.cbxCycleCount.SelectedValue.ToString();
        //    cycleCountForm.pnlDataForm.Enabled = true;
        //    cycleCountForm.tbxLocation.Focus();

        //    isDatabindingCycleCountList = false;
        //}

        #endregion



        #region Serial Methods

        //public void SerialEntered(int serial)
        //{
        //    if (LastSerial == null)
        //    {
        //        // Prepare current serial for Cycle Count
        //        GetObjectInfo(serial);
        //    }
        //    else
        //    {
        //        // Add the previous serial to the Cycle Count, prepare current serial for Cycle Count
        //        CycleCountTheObject();
        //        GetObjectInfo(serial);
        //    }
        //}

        //private void GetObjectInfo(int serial)
        //{
        //    string part, quantity, loc, error = "";

        //    cycle.GetObjectInfo(serial, out part, out quantity, out loc, out error);
        //    if (error != "")
        //    {
        //        alert.ShowError(alertLevel.High, error, "GetObjectInfo() Error");
        //        cycleCountForm.tbxSerial.Text = "";
        //        return;
        //    }
        //    LastSerial = serial;
        //    cycleCountForm.tbxPart.Text = part;
        //    cycleCountForm.tbxQuantity.Text = quantity;
        //    cycleCountForm.tbxRealQuantity.Focus();
        //}

        //public void CycleCountTheObject()
        //{
        //    decimal realquantity = -1;
        //    if (cycleCountForm.tbxRealQuantity.Text.Trim() != "")
        //    {
        //        realquantity = ValidateQuantity(cycleCountForm.tbxRealQuantity.Text.Trim());
        //        if (realquantity < 0)
        //        {
        //            alert.ShowError(alertLevel.Medium, "Real quantity is not valid.", "Error");
        //            return;
        //        }
        //    }

        //    string error = "";
        //    string actionTakenMessage = "";
        //    int? actionTaken = null;
        //    string ccnumber = cycleCountForm.cbxCycleCount.SelectedValue.ToString();
        //    string part = cycleCountForm.tbxPart.Text;
        //    string loc = cycleCountForm.tbxLocation.Text.Trim();
        //    int lastserial = Convert.ToInt32(LastSerial);

        //    if (realquantity < 0)
        //    {
        //        decimal quantity = Convert.ToDecimal(cycleCountForm.tbxQuantity.Text.Trim());
        //        int? result = cycle.CycleCountTheObject(OperatorCode, ccnumber, lastserial, part, quantity, loc, out actionTakenMessage, out actionTaken, out error);
        //        if (error != "")
        //        {
        //            alert.ShowError(alertLevel.High, error, "CycleCountTheObject() Error");
        //        }
        //        else
        //        {
        //            messageController.ShowMessage(actionTakenMessage);
        //        }
        //    }
        //    else
        //    {
        //        int? result = cycle.CycleCountTheObject(OperatorCode, ccnumber, lastserial, part, realquantity, loc, out actionTakenMessage, out actionTaken, out error);
        //        if (error != "")
        //        {
        //            alert.ShowError(alertLevel.High, error, "CycleCountTheObject() Error");
        //        }
        //        else
        //        {
        //            messageController.ShowMessage(actionTakenMessage);
        //        }
        //    }
        //}

        //public int ValidateSerial(string ser)
        //{
        //    int serial = 0;
        //    try
        //    {
        //        serial = Convert.ToInt32(ser);
        //    }
        //    catch (Exception)
        //    {
        //        return serial;
        //    }
        //    return serial;
        //}

        //private decimal ValidateQuantity(string qty)
        //{
        //    decimal quantity = -1;
        //    try
        //    {
        //        quantity = Convert.ToDecimal(qty);
        //    }
        //    catch (Exception)
        //    {
        //        return quantity;
        //    }
        //    return quantity;
        //}

        #endregion



        #region Additional Methods

        public void handleScan(RFScanEventArgs e)
        {
            try
            {
                ScanData scanData = e.Text;

                if (scanData.ScanDataType == eScanDataType.Serial || scanData.ScanDataType == eScanDataType.Undef)
                {
                    int serial = int.Parse(scanData.DataValue.Trim());
                    //cycleCountForm.tbxSerial.Text = scanData.DataValue.Trim();
                    //SerialEntered(serial);
                }
                else if (scanData.ScanDataType == eScanDataType.Shipper)
                {
                    //cycleCountForm.tbxLocation.Text = scanData.DataValue.Trim();
                    //LocationEntered(scanData.DataValue.Trim());
                }
                else
                {
                    alert.ShowError(alertLevel.High, "Invalid scan.", "Error");
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    alert.ShowError(alertLevel.High, ex.InnerException.ToString(), "handleScan() Error");
                }
                else
                {
                    alert.ShowError(alertLevel.High, ex.Message, "handleScan() Error");
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// If the ScanData object vanishes, we recreate it with this method.
        /// </summary>
        /// <param name="LastScanDate"></param>
        /// <param name="MostRecentlySeen"></param>
        /// <returns></returns>
        public async Task <ScanData> CreateScanData(DateTimeOffset?LastScanDate = null, DateTimeOffset?MostRecentlySeen = null)
        {
            await FirestoreSetup();

            ScanData sd = new ScanData()
            {
                LastScanDate     = LastScanDate ?? DateTimeOffset.Now,
                MostRecentlySeen = MostRecentlySeen ?? DateTimeOffset.Now
            };

            try {
                if (ScanDataReference == null)
                {
                    ScanDataReference = DBHandle.Document(SCANDATA);
                }
                await DBHandle.RunTransactionAsync(async transaction => {
                    transaction.Create(ScanDataReference, sd);
                    await Task.Delay(0);
                });
            }
            catch (Exception e) {
                // Some failure happened while trying to recreate our scan object
            }
            return(sd);
        }
Ejemplo n.º 5
0
        public override ScanData DoTask(ScanData source)
        {
            source.Sort();
            ScanData ret = source;
            Dictionary<int, ScanData> laserScanData = new Dictionary<int, ScanData>();
            UpdatePercent(0, ret);
            ret = new ScanData();

            int count = source.Count ;
            double delta_angle = DeltaAngle;
            int step = (int)((count * delta_angle) / 360.0);
            for (double ang = 0; ang < 360; ang += delta_angle)
            {
                int biggestIndex = 0;
                int biggestCount = 0;
                List<ScanLine> lines = GetScanlinesByAngle(ang, ang + delta_angle, source);
                for (int j = 0; j < lines.Count; j++)
                {
                    ScanLine l = lines[j];
                    int cnt = l.Count;
                    if (biggestCount < cnt)
                    {
                        biggestCount = cnt;
                        biggestIndex = j;
                    }
                }
                if(lines.Count>0)
                    ret.Add(AverageLines(biggestCount,biggestIndex, lines));
                UpdatePercent((int)(100 * ang/360), ret);
            }
            UpdatePercent(100, ret);
            return ret;
            
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Run the task
        /// </summary>
        /// <param name="source">Source data</param>
        /// <param name="control">Control that launch</param>
        /// <param name="worker">background worker trhead if anny</param>
        /// <param name="e">DoWork Event argument</param>
        /// <param name="updateFunc"> Update function to call</param>
        /// <returns></returns>
        public ScanData Run(ScanData source, Control control = null, BackgroundWorker worker = null, DoWorkEventArgs e = null, ProgressChangedEventHandler updateFunc = null)
        {
            LastError     = string.Empty;
            Worker        = worker;
            WorkerArg     = e;
            CallerControl = control;
            UpdateFunc    = updateFunc;
            ScanData ret = null;

            Status = eTaskStatus.Working;
            UpdatePercent(0, ret);
            try
            {
                ret = DoTask(source);
            }
            catch (Exception exception)
            {
                Status    = eTaskStatus.Error;
                LastError = exception.Message;
                return(null);
            }
            if (Status != eTaskStatus.Error)
            {
                Status = eTaskStatus.Finished;
                UpdatePercent(100, ret);
            }
            UpdateFunc    = null;
            CallerControl = null;
            Worker        = null;
            WorkerArg     = null;
            return(ret);
        }
Ejemplo n.º 7
0
		public static void Write(string file, ScanData data)
		{
			using (StreamWriter w = System.IO.File.CreateText(file))
			{
				w.WriteLine(string.Format("# Create By Sardauscan V{0}",Application.ProductVersion));
				w.WriteLine("#");
				w.WriteLine("# Object");
				List<FaceInfo> faces = new List<FaceInfo>();
				List<Vector3d> vertex = new List<Vector3d>();
				for (int i = 0; i < data.Count; i++) // collect vertices and face
				{
					ScanLine slice = data[i];
					if (slice.IsMesh)
					{
						List<Triangle3D> tris = slice.GetTriangles();
						for (int t = 0; t < tris.Count; t++)
						{
							Triangle3D triangle = tris[t];
							FaceInfo face = new FaceInfo();
							face.v1 = AddToList(vertex, triangle.Point1.Position);
							face.v2 = AddToList(vertex, triangle.Point2.Position);
							face.v3 = AddToList(vertex, triangle.Point3.Position);
							faces.Add(face);
						}
					}
				}
				w.WriteLine(string.Format("# Vertices {0}", vertex.Count));
				for (int i = 0; i < vertex.Count; i++)
					w.WriteLine(string.Format("v {0}",vertex[i].Dump()));
				w.WriteLine(string.Format("# Triangles {0}", faces.Count));
				for (int i = 0; i < faces.Count; i++)
					w.WriteLine(string.Format("f {0} {1} {2}", faces[i].v1 + 1, faces[i].v2 + 1, faces[i].v3 + 1));
			}
		}
Ejemplo n.º 8
0
		protected ScanData DoIteration(ScanData source, double pctMin, double pctMax)
		{
			ScanData ret = new ScanData(source.Count);
			ret.AddRange(source);
			int count = source.Count;
			int doneCount = 0;
			int ParallelCount = Settings.Get<Settings>().Read(Settings.SYSTEM, Settings.MAXTHREADS, 8);
			Parallel.For(1, count+1, new ParallelOptions { MaxDegreeOfParallelism = ParallelCount }, i =>
				{//for (int i = 1; i <= count; i++)
					{
						if (this.CancelPending) return;
						ScanLine current = source[i % count];
						ScanLine prev = source[(i - 1) % count];
						ScanLine next = source[(i + 1) % count];
						int lineCount = current.Count;

						ScanLine smoothed = new ScanLine(current.Count);
						smoothed.DisplayAsLine = current.DisplayAsLine;

						for (int l = 0; l < lineCount; l++)
						{
							smoothed.Add(Smooth(l, prev, current, next));
						}
						ret[i % count] = smoothed;
						doneCount++;
						int pct = (int)(pctMin + ((pctMax - pctMin) * doneCount) / count);
						UpdatePercent(pct, ret);
					}
				});
			return ret;
		}
Ejemplo n.º 9
0
 List<ScanLine> GetScanlinesByAngle(double from, double to,ScanData data)
 {
     List<ScanLine> ret = new List<ScanLine>();
     data.Sort();
     int startindex = -1;
     int cnt = data.Count;/*
     for (int i = 0; i < cnt && startindex == -1; i++) // find first of range
     {
         ScanLine line = data[i];
         double angle = line.Angle;
         while (angle < 0)
             angle += 360;
         if (angle >= from && angle <= to)
             startindex = i;
     }
     if (startindex < 0)
         return ret;*/
     startindex =0;
     for (int i = 0; i < cnt; i++) // fill the range
     {
         ScanLine line = data[(i + startindex)%cnt ];
         double angle = line.Angle;
         while (angle < 0)
             angle += 360;
         if (angle >= from && angle <= to)
             ret.Add(line);
         if (angle > to)
             return ret;
     }
     return ret;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the last known Scan Data object
        /// </summary>
        /// <returns></returns>
        public async Task <ScanData> GetScanData()
        {
            await FirestoreSetup();

            ScanData sd = null;

            try {
                ScanDataReference = DBHandle.Document(SCANDATA);
                if (ScanDataReference == null)
                {
                    // ScanData vanished - create a new one.
                    return(await CreateScanData());
                }
                DocumentSnapshot scanDataSnapshot = await ScanDataReference.GetSnapshotAsync();

                if (scanDataSnapshot.Exists)
                {
                    sd = scanDataSnapshot.ConvertTo <ScanData>();
                }
                else
                {
                    Logger.Log("No Scan Data was found, creating a new one and will pick up next invocation");
                    return(await CreateScanData());
                }
            }
            catch (Exception e) {
                Logger.Log("An unknown error ocurred while fetching Scan Data. Aborting.");
                // Some error occurred.
            }
            return(sd);
        }
Ejemplo n.º 11
0
        public override Sardauscan.Core.ScanData DoTask(Sardauscan.Core.ScanData source)
        {
            if (!HardwareAvailable)
            {
                throw new Exception(string.Format("HardWare missing : TURNTABLE:{0} LASER:{1} CAMERA:{2}", HardwarePresentTrace(TurnTable), HardwarePresentTrace(Laser), HardwarePresentTrace(Camera)));
            }

            double   RotationStep = (double)Math.Round(360.0 / (NumberOfGrab - 1), 2);
            ScanData ret          = new ScanData();

            UpdatePercent(0, ret);

            TurnTable.InitialiseRotation();
            Laser.TurnAll(false);
            int index = 0;

            for (double currentAngle = 0; currentAngle < 360f; currentAngle += RotationStep)
            {
                if (this.CancelPending)
                {
                    return(ret);
                }
                Bitmap imgoff = GetCapture();
                string path   = Path.Combine(Folder, string.Format("capture{0}.jpg", ++index, (int)currentAngle));
                imgoff.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

                int percent = (int)((currentAngle / 360f) * 100f);
                UpdatePercent(percent, ret);
                TurnTable.Rotate(currentAngle, false);
                Thread.Sleep(1000);
            }

            return(null);
        }
Ejemplo n.º 12
0
        private void MyRFGun_RFScan(object sender, RFScanEventArgs e)
        {
            try
            {
                ScanData scanData = e.Text;
                switch (scanData.ScanDataType)
                {
                case eScanDataType.Shipper:
                    EnterSID(scanData.DataValue);
                    break;

                case eScanDataType.PO:
                    EnterPO(scanData.DataValue);
                    break;

                case eScanDataType.Part:
                    EnterPart(scanData.DataValue);
                    break;

                case eScanDataType.Quantity:
                    EnterQty(scanData.DataValue);
                    break;

                case eScanDataType.Serial:
                    EnterLot(scanData.DataValue);
                    if (SID != null && PO != null && Part != null && Qty != null && Lot != null)
                    {
                        ReceiveBox();
                    }
                    break;

                case eScanDataType.TwoDBarcode:
                    TwoDEntered(scanData.DataValue);
                    break;

                case eScanDataType.Undef:
                    var ex = new Exception("Unknown data identifier.");
                    throw ex;
                }
            }
            catch (SqlException ex)
            {
                uxMessage.Text = ex.Message;
                //StreamWriter sw = File.AppendText("\\Application Data\\Error-RD.txt");
                // sw.WriteLine(ex.Message + "\r\n SID:" + uxSID.Text + "\r\n PO:" + uxPO.Text + "\r\n Part:" + uxPart.Text + "\r\n Qty:" + uxQty.Text + "\r\n Lot:" + uxLot.Text );
                // sw.WriteLine(" \r\n=================== \r\n");
                //sw.WriteLine(ex.Message + ",SID:" + uxSID.Text + ",PO:" + uxPO.Text + ",Part:" + uxPart.Text + ",Qty:" + uxQty.Text + ",Lot:" + uxLot.Text + ",select part_number,vendor_code,MIN(date_due) as due, DATEDIFF(dd,GETDATE(),Min(date_due)) as doh from po_detail where po_number=" + uxPO.Text + " group by part_number,vendor_code union");
                //sw.Close();
            }
            catch (Exception ex)
            {
                uxMessage.Text = ex.Message;
                //StreamWriter sw = File.AppendText("\\Application Data\\Error-RD.txt");
                // sw.WriteLine(ex.Message + "\r\n SID:" + uxSID.Text + "\r\n PO:" + uxPO.Text + "\r\n Part:" + uxPart.Text + "\r\n Qty:" + uxQty.Text + "\r\n Lot:" + uxLot.Text );
                // sw.WriteLine(" \r\n=================== \r\n");
                //sw.WriteLine(ex.Message + ",SID:" + uxSID.Text + ",PO:" + uxPO.Text + ",Part:" + uxPart.Text + ",Qty:" + uxQty.Text + ",Lot:" + uxLot.Text + ",select part_number,vendor_code,MIN(date_due) as due, DATEDIFF(dd,GETDATE(),Min(date_due)) as doh from po_detail where po_number=" + uxPO.Text + " group by part_number,vendor_code union");

                //sw.Close();
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Write ScanData To PLY file
 /// </summary>
 /// <param name="file"></param>
 /// <param name="points"></param>
 public static void Write(string file, ScanData points)
 {
     using (StreamWriter w = System.IO.File.CreateText(file))
     {
         w.WriteLine("ply");
         w.WriteLine("format ascii 1.0");
         w.WriteLine(string.Format("element vertex {0}", points.PointCount()));                  // Leave space for updating the vertex count
         w.WriteLine("property double x");
         w.WriteLine("property double y");
         w.WriteLine("property double z");
         w.WriteLine("property double nx");
         w.WriteLine("property double ny");
         w.WriteLine("property double nz");
         w.WriteLine("property uchar red");
         w.WriteLine("property uchar green");
         w.WriteLine("property uchar blue");
         w.WriteLine("element face 0");
         w.WriteLine("property list uchar int vertex_indices");
         w.WriteLine("end_header");
         for (int i = 0; i < points.Count; i++)
         {
             Write(w, points[i]);
         }
     }
 }
Ejemplo n.º 14
0
        private void Populate(string date, int count, Repository <ScanData> Database)
        {
            for (int i = 0; i < count; i++)
            {
                int hour   = rnd.Next(1, 24);
                int minute = rnd.Next(1, 60);
                int second = rnd.Next(60);

                DateTime dt = Convert.ToDateTime(date);

                dt = Convert.ToDateTime(new DateTime(dt.Year, dt.Month, dt.Day, hour, minute, second).ToString("yyyy-MM-dd h:mm:ss"));

                ScanData d = new ScanData()
                {
                    Id                  = 1,
                    IdScanner           = 1,
                    IdUser              = 1,
                    IdType              = 1,
                    AdditionalServiceId = 1,
                    DataValue           = RandomString(20),
                    ScannedAt           = dt
                };

                Database.Insert(d);
            }
        }
Ejemplo n.º 15
0
        ScanData sData;  //扫描数据
        //Barcode扫描
        private void barcode21_OnScan(ScanDataCollection scanDataCollection)
        {
            try
            {
                //this.Show();
                this.WindowState = FormWindowState.Maximized;
                this.Activate();
                //移除上次的items
                while (ScanDataShow.Items.Count > 0)
                {
                    ScanDataShow.Items.RemoveAt(0);
                }
                ScanData scanData = scanDataCollection.GetFirst; //接受到的数据

                ScanDataShow.Items.Add(scanData.Text + ";" + scanData.Type.ToString());

                sData = scanData;
                if (AutoSend.Checked)
                {
                    SendData(scanData);  //自动发送数据
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Ejemplo n.º 16
0
        public override ScanData DoTask(ScanData source)
        {
            LastError = string.Empty;
            {
                if (String.IsNullOrEmpty(Filename))
                {
                    string file = ShowDialog();
                    if (!string.IsNullOrEmpty(file))
                    {
                        this.Filename = file;
                    }
                }


                if (!String.IsNullOrEmpty(Filename))
                {
                    this.Status = eTaskStatus.Working;
                    UpdatePercent(0, source);
                    Save(source);
                    this.Status = eTaskStatus.Finished;
                    UpdatePercent(100, source);
                }
                else
                {
                    this.Status = eTaskStatus.Error;
                    LastError   = String.Format("Invalid File {0}", this.Filename);
                }
                return(source);
            }
        }
Ejemplo n.º 17
0
        public override ScanData DoTask(ScanData source)
        {
            ScanData step1 = base.DoTask(source);

            step1.Sort();             //SORT
            Dictionary <string, ScanLine> step2 = new Dictionary <string, ScanLine>();

            for (int i = 0; i < step1.Count; i++)
            {
                ScanLine line = step1[i];
                if (line.Count > 0)
                {
                    for (int c = 0; c < NumClass; c++)
                    {
                        string key = string.Format("{0}->{1}", line.LaserID, c);
                        if (!step2.ContainsKey(key))
                        {
                            step2[key] = new ScanLine(line.LaserID, NumClass);
                        }
                        step2[key].Add(GetSample(line, NumClass, c));
                    }

                    //step2[line.LaserID].Add(line[0]);
                }
            }

            ScanData step3 = new ScanData(step2.Keys.Count);

            for (int i = 0; i < step2.Keys.Count; i++)
            {
                string k = step2.Keys.ElementAt(i);
                step3.Add(step2[k]);
            }
            return(step3);
        }
Ejemplo n.º 18
0
		/// <summary>
		/// Write ScanData (mesh) to STL
		/// </summary>
		/// <param name="file"></param>
		/// <param name="points"></param>
		public static void Write(string file, ScanData points)
		{
			/*
			solid
				 :
				 :
				 facet normal 0.0 0.0 1.0 
				 outer loop 
						vertex  1.0  1.0  0.0 
						vertex -1.0  1.0  0.0 
						vertex  0.0 -1.0  0.0 
				 endloop
				 endfacet
				 :
				 :
			endsolid
			*/

			using (StreamWriter w = System.IO.File.CreateText(file))
			{
				w.WriteLine("solid");
				for (int i = 0; i < points.Count; i++)
				{
					ScanLine slice = points[i];
					if (slice.IsMesh)
					{
						List<Triangle3D> tris = slice.GetTriangles();
						for (int t = 0; t < tris.Count; t++)
							WriteTriangle(w, tris[t]);
					}
				}
				w.WriteLine("endsolid");
			}
		}
        private void DeleteScannedData(ScanData data)
        {
            try
            {
                if (User == null)
                {
                    return;
                }
                if (!User.SuperUser)
                {
                    Alert("Uwaga", "Brak uprawnień! Zaloguj się na użytkownika posiadającego prawa administracyjne!", "Ok.");
                    return;
                }

                IsBusy = true;

                if (Delete(data))
                {
                    var items = ReportList.Where(w => w.DataValue == data.DataValue).ToList();
                    foreach (ScanData item in items)
                    {
                        ReportList.Remove(item);
                    }

                    Alert("Sukcess", "Usuwanie zakończone.", "Ok.");
                }
            }
            catch (Exception ex)
            {
                Alert("Błąd", ex.Message, "Ok.");
            }
            finally {
                IsBusy = false;
            }
        }
Ejemplo n.º 20
0
 private void OnScanDataCallback(ScanData scan)
 {
     //Console.WriteLine( "> " + scan.code + " [" + scan.symb.ToString() + "]\n" );
     dataGridView1.SynchronizedInvoke(() => {
         dataGridView1.Rows.Add(scan.code, scan.symb.ToString());
     });
 }
Ejemplo n.º 21
0
        private void barcode21_OnScan(ScanDataCollection scanDataCollection)
        {
            this.Show();
            this.WindowState = FormWindowState.Maximized;
            this.Activate();
            //移除上次的items
            while (listBox1.Items.Count > 0)
            {
                listBox1.Items.RemoveAt(0);
            }
            ScanData scanData = scanDataCollection.GetFirst;

            if (scanData.Result == Results.SUCCESS)
            {
                if (client.Send(scanData.Text + ";" + scanData.Type.ToString()))
                {
                    // Write the scanned data and type (symbology) to the list box
                    listBox1.Items.Add(scanData.Text + ";" + scanData.Type.ToString());
                    listBox1.Items.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    textBox1.Text = "ok " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                }

                //textBox1.Text = SocketPlus.Send("192.168.10.150", 12345, scanData.Text + ";" + scanData.Type.ToString());
                //if (textBox1.Text == "ok")
                //{
                //    // Write the scanned data and type (symbology) to the list box
                //    listBox1.Items.Add(scanData.Text + ";" + scanData.Type.ToString());
                //}
            }
        }
Ejemplo n.º 22
0
 private void BC2_OnScan(ScanDataCollection scanDataCollection)
 {
     try
     {
         BarcodeTB.Text = "";
         AnswerTB.Text  = "";
         ScanData scanData = scanDataCollection.GetFirst;
         if (scanData.Result == Symbol.Barcode2.Results.SUCCESS)
         {
             BarcodeTB.Text = scanData.Text;
             if (Z_mXML.IsInputQuantity && BarcodeTB.Text.StartsWith("8001") && (BarcodeTB.Text.Length == 16 || BarcodeTB.Text.IndexOf('#') == 16))
             {
                 CountTB.ReadOnly = false;
                 if (BarcodeTB.Text.IndexOf('#') == 16)
                 {
                     CountTB.Text = BarcodeTB.Text.Substring(17);
                 }
                 else
                 {
                     CountTB.Text = "1";
                 }
                 CountTB.Focus();
             }
             else
             {
                 Send_Receive(scanData.Text);
             }
         }
         else
         {
             BarcodeTB.Text = "Ошибка";
         }
     }
     catch { }
 }
Ejemplo n.º 23
0
        public async Task TestParseScanTime()
        {
            FirestoreService FSS = new FirestoreService(logger);
            ScanData         sd  = await FSS.GetScanData();

            Assert.NotNull(sd);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Do the task
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public override ScanData DoTask(ScanData source)
        {
            ScanData ret = new ScanData(source.Count);

            source.Sort();
            int count         = source.Count;
            int ParallelCount = Settings.Get <Settings>().Read(Settings.SYSTEM, Settings.MAXTHREADS, 8);

            UpdatePercent(0, ret);
            if (LaunchParallel)
            {
                int doneCount = 0;
                Parallel.For(0, count, new ParallelOptions {
                    MaxDegreeOfParallelism = ParallelCount
                }, i =>
                {
                    if (this.CancelPending)
                    {
                        return;
                    }
                    ScanLine line = DoTask(source[i]);
                    if (line != null)
                    {
                        //line.DisplayAsLine = source[i].DisplayAsLine;
                        lock (ret)
                        {
                            ret.Add(line);
                        }
                        doneCount++;
                        {
                            int percent = (int)((100 * doneCount) / count);
                            if (percent % 10 == 0)
                            {
                                UpdatePercent(percent, ret);
                            }
                        }
                    }
                }
                             );
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    if (this.CancelPending)
                    {
                        return(ret);
                    }
                    ScanLine line = DoTask(source[i]);
                    if (line != null)
                    {
                        ret.Add(line);
                    }
                    UpdatePercent((int)(100 * i / count), ret);
                }
            }
            UpdatePercent(100, ret);
            return(ret);
        }
Ejemplo n.º 25
0
		/// <summary>
		/// Write ScanData to XYZ File
		/// </summary>
		/// <param name="file"></param>
		/// <param name="points"></param>
		public static void Write(string file, ScanData points)
		{
			using (StreamWriter w = System.IO.File.CreateText(file))
			{
				for (int i = 0; i < points.Count; i++)
					Write(w, points[i]);
			}
		}
Ejemplo n.º 26
0
        /// <summary>
        ///
        /// </summary>
        private void packScan()
        {
            ScanData sd = new ScanData();

            sd.code = _code.ToString();
            sd.symb = Symbology.UNKNOWN;
            OnScanData(sd);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 保存扫描的申请单
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private bool SaveScanImg(Bitmap bmp)
        {
            //创建一个扫描图像类
            ScanData oneScan = new ScanData();

            oneScan.申请ID      = _str申请ID;
            oneScan.扫描ID      = SqlHelper.GetNumGuid().ToString();
            oneScan.扫描信息.存储ID = 存储ID;
            oneScan.扫描信息.扫描人  = 扫描人;
            oneScan.扫描信息.扫描时间 = _scanModel.GetServerDate();
            oneScan.扫描信息.文件名  = Guid.NewGuid().ToString("N");
            oneScan.扫描信息.申请日期 = 申请日期;
            oneScan.扫描信息.CopyBasePro(oneScan);

            try
            {
                //保存临时文件
                var eps = new System.Drawing.Imaging.EncoderParameters(1);
                var ep  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                eps.Param[0] = ep;
                var jpsEncoder = GetEncoder(ImageFormat.Jpeg);

                FTPFileHelp ftpHelper = new FTPFileHelp();
                initFTP(_dbQuery, 存储ID, out ftpHelper);

                string vPath   = ftpHelper.VPath + "//" + oneScan.扫描信息.申请日期.ToString("yyyyMMdd") + "//" + oneScan.申请ID + "//apply//";
                string tmpFile = System.Windows.Forms.Application.StartupPath + @"\Temp" + vPath.Replace("//", "\\");
                if (Directory.Exists(tmpFile) == false)
                {
                    Directory.CreateDirectory(tmpFile);
                }

                tmpFile = tmpFile + oneScan.扫描信息.文件名 + ".jpg";
                bmp.Save(tmpFile, jpsEncoder, eps);
                //释放资源
                ep.Dispose();
                eps.Dispose();

                //上传FTP
                FileInfo fi = new FileInfo(tmpFile);
                ftpHelper.MakeDirectory(vPath);
                if (ftpHelper.FileUpLoad(vPath + oneScan.扫描信息.文件名 + ".jpg", fi) == true)
                {
                    //存入数据库
                    _scanModel.SaveScanImage(oneScan);
                }
                else
                {
                    return(false);
                }
                //ftpHelper.disConnect(); 没有关闭连接的方法吗?
            }
            catch (Exception ex)
            {
                MsgBox.ShowException(ex, this);
            }
            return(true);
        }
Ejemplo n.º 28
0
        private void TwoDEntered(String sPart)
        {
            string[] line = sPart.Split(']');
            line[0] = line[0].Replace("[", "");
            line[1] = line[1].Replace("[", "");
            line[2] = line[2].Replace("[", "");
            line[3] = line[3].Replace("[", "");
            line[4] = line[4].Replace("[", "");
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    ScanData scanData = line[i];
                    switch (scanData.ScanDataType)
                    {
                    case eScanDataType.Shipper:
                        EnterSID(scanData.DataValue);
                        break;

                    case eScanDataType.PO:
                        EnterPO(scanData.DataValue);
                        break;

                    case eScanDataType.Part:
                        EnterPart(scanData.DataValue);
                        break;

                    case eScanDataType.Quantity:
                        EnterQty(scanData.DataValue);
                        break;

                    case eScanDataType.Serial:
                        EnterLot(scanData.DataValue);
                        if (SID != null && PO != null && Part != null && Qty != null && Lot != null)
                        {
                            ReceiveBox();
                        }
                        break;

                    case eScanDataType.TwoDBarcode:
                        TwoDEntered(scanData.DataValue);
                        break;

                    case eScanDataType.Undef:
                        var ex = new Exception("Unknown data identifier.");
                        throw ex;
                    }
                }
                catch (SqlException ex)
                {
                    uxMessage.Text = ex.Message;
                }
                catch (Exception ex)
                {
                    uxMessage.Text = ex.Message;
                }
            }
        }
Ejemplo n.º 29
0
    private void barcodeMoto_OnScan(ScanDataCollection scanDataCollection)
    {
        ScanData scanData = scanDataCollection.GetFirst;

        if (scanData.Result == Results.SUCCESS)
        {
            varCallBackBarcode(scanData.Text);
        }
    }
Ejemplo n.º 30
0
        void MyRFGun_RFScan(object sender, RFScanEventArgs e)
        {
            try
            {
                ScanData scanData = e.Text;
                switch (scanData.ScanDataType)
                {
                case eScanDataType.Serial:
                    if (SID == null)
                    {
                        throw new Exception("Select a shipper before scanning inventory to stage.");
                    }
                    else
                    {
                        if (uxStage.Checked)
                        {
                            StageObject(Convert.ToInt32(scanData.DataValue));
                        }
                        else
                        {
                            UnstageObject(Convert.ToInt32(scanData.DataValue));
                        }
                    }
                    break;

                case eScanDataType.Shipper:
                    SelectShipper(Convert.ToInt32(scanData.DataValue));
                    break;

                case eScanDataType.Undef:
                    if (uxStage.Checked)
                    {
                        StageObject(Convert.ToInt32(scanData.DataValue));
                    }
                    else
                    {
                        UnstageObject(Convert.ToInt32(scanData.DataValue));
                    }
                    break;
                }
            }
            catch (SqlException ex)
            {
#if PocketPC
                MyRFGun.BadReadNotification();
#endif
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
#if PocketPC
                MyRFGun.BadReadNotification();
#endif
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 31
0
		Point3DList CreateListFromScanData(ScanData source)
		{
			Point3DList ret = new Point3DList();
			IqrFilter filter = new IqrFilter();
			filter.Factor = 0.5f;
			ScanData data = filter.Run(source);
			for (int i = 0; i < data.Count; i++)
				ret.AddRange(data[i]);
			return ret;
		}
Ejemplo n.º 32
0
 /// <summary>
 /// Write ScanData to XYZ File
 /// </summary>
 /// <param name="file"></param>
 /// <param name="points"></param>
 public static void Write(string file, ScanData points)
 {
     using (StreamWriter w = System.IO.File.CreateText(file))
     {
         for (int i = 0; i < points.Count; i++)
         {
             Write(w, points[i]);
         }
     }
 }
Ejemplo n.º 33
0
        void MyRFGun_RFScan(object sender, RFScanEventArgs e)
        {
            //exception =new exception
            try
            {
                ScanData scanData = e.Text;
                switch (scanData.ScanDataType)
                {
                //case eScanDataType.Shipper:
                //    Exception ex0 = new Exception("Not a part number or quantity");
                //    throw ex0;
                //    break;
                //case eScanDataType.PO:
                //    Exception ex1 = new Exception("Not a part number or quantity");
                //    throw ex1;
                //    break;
                case eScanDataType.Part:
                    EnterPart(scanData.DataValue);
                    break;

                case eScanDataType.Quantity:
                    EnterQty(scanData.DataValue);
                    break;
                //case eScanDataType.Serial:
                //    Exception ex2 = new Exception("Not a part number or quantity");
                //    throw ex2;
                //    break;


                case eScanDataType.TwoDBarcode:
                    //EnterQty();
                    //ModScan = scanData.DataValue.Replace("\31" , "*");
                    MessageBox.Show("2d");
                    MyRFGun.GoodReadNotification();
                    string[] words = scanData.DataValue.Split((char)31);
                    foreach (string word in words)
                    {
                        //MessageBox.show(word);
                        MessageBox.Show(word);
                    }

                    break;


                case eScanDataType.Undef:
                    Exception ex3 = new Exception("Unknown data identifier.");
                    throw ex3;
                }
            }

            catch (Exception ex)
            {
                uxMessage.Text = ex.Message;
            }
        }
Ejemplo n.º 34
0
        private async Task ScanAsync(string scanId, ScanData data)
        {
            using (var lck = data.GetLock())
            {
                if (lck.IsCaptured)
                {
                    data.IncAttempts();

                    using (var service = CreateService())
                    {
                        var item  = data.Item;
                        var train = await service.FetchTrainAsync(item.Date, item.Source, item.Destination, item.TrainNumber);

                        if (train != null)
                        {
                            CoachType[] coachTypes;

                            if (!String.IsNullOrEmpty(item.CoachType))
                            {
                                var coachType = FindCoachType(train, item.CoachType);

                                if (coachType == null)
                                {
                                    HandleError(scanId, data, $"Coach type {item.CoachType} not found");
                                    return;
                                }

                                coachTypes = new[] { coachType };
                            }
                            else
                            {
                                coachTypes = train.CoachTypes;
                            }

                            var sessionId = await BookAsync(train, coachTypes, item.FirstName, item.LastName);

                            if (!String.IsNullOrEmpty(sessionId))
                            {
                                await _successCallbackAsync(item.CallbackId, sessionId);

                                Abort(scanId);
                            }
                            else
                            {
                                HandleError(scanId, data, "No vacant seats");
                            }
                        }
                        else
                        {
                            HandleError(scanId, data, $"Train {item.TrainNumber} not found");
                        }
                    }
                }
            }
        }
Ejemplo n.º 35
0
		public override ScanData DoTask(ScanData source)
		{
			ScanData ret = source;
			Dictionary<int, ScanData> laserScanData = new Dictionary<int, ScanData>();
			UpdatePercent(0, ret);
			for (int i = 0; i < source.Count; i++)
			{
				ScanLine currentLine = source[i];
				ScanData data = laserScanData.ContainsKey(currentLine.LaserID)?laserScanData[currentLine.LaserID]: new ScanData();
				data.Add(currentLine);
				laserScanData[currentLine.LaserID] = data;
			}
			int masterLaserId = -1;
			foreach (int lId in laserScanData.Keys)
			{
				if (masterLaserId == -1)
					masterLaserId = lId;
				else if (laserScanData[masterLaserId].Count < laserScanData[lId].Count)
						masterLaserId = lId;
				laserScanData[lId].Sort();
			}
			ret = new ScanData();
			
			ScanData master = laserScanData[masterLaserId];
			double maxAngle = 180f / master.Count;
			for (int i = 0; i < master.Count; i++)
			{
				List<ScanLine> lines = new List<ScanLine>(laserScanData.Keys.Count);
				double currentAngle = master[i].Angle;
				int currentCount = master[i].Count;
				int biggestIndex = 0;
				lines.Add(master[i]);
				foreach (int key in laserScanData.Keys)
				{
					if (key != masterLaserId)
					{
						ScanLine currentLine = laserScanData[key].GetNearestLine(currentAngle);
						if (currentLine == null)
							continue;
						if (maxAngle > Math.Abs(Utils.DeltaAngle(currentAngle,currentLine.Angle)))
						{
							if (currentCount < currentLine.Count)
							{
								currentCount = currentLine.Count;
								biggestIndex = lines.Count;
							}
							lines.Add(currentLine);
						}
					}
				}
				ret.Add(AverageLines(currentCount,biggestIndex, lines));
			}
			UpdatePercent(100, ret);
			return ret;
		}
Ejemplo n.º 36
0
		public override ScanData DoTask(ScanData source)
		{
			CameraPosition = new Vector3d();
			Settings settings = Settings.Get<Settings>();
			CameraPosition.X = settings.Read(Settings.CAMERA, Settings.X, 0f);
			CameraPosition.Y = settings.Read(Settings.CAMERA, Settings.Y, 270f);
			CameraPosition.Z = settings.Read(Settings.CAMERA, Settings.Z, 70f);
			ScanData ret = base.DoTask(source);
			ret.Sort();
			return ret;
		}
Ejemplo n.º 37
0
        void ScanNotifyHandler(ScanDataCollection scancollection)
        {
            ScanData scanData = scancollection.GetFirst;

            if (scanData.Result == Results.SUCCESS)
            {
                txtBarCode.Text = scanData.Text;
                ScanBarCode();
            }
            scanManager.StartScan();
        }
Ejemplo n.º 38
0
        private void mBc2_OnScan(Symbol.Barcode2.ScanDataCollection scanDataCollection)
        {
            ScanData sData = scanDataCollection.GetFirst;
            var      str   = sData.Text;
            var      sType = sData.Type.ToString();

            byte[] by    = Encoding.Default.GetBytes(str);
            string sText = Encoding.GetEncoding(65001).GetString(by, 0, by.Length);

            scan_OnDecodeEvent(sText);
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Update percentage
 /// </summary>
 /// <param name="percent"></param>
 /// <param name="data"></param>
 public virtual void UpdatePercent(int percent, ScanData data)
 {
     if (Percent != percent)
     {
         Percent = percent;
         if (UpdateFunc != null)
         {
             UpdateFunc(this, new ProgressChangedEventArgs(percent, data));
         }
     }
 }
Ejemplo n.º 40
0
        public override enExperimentStatus Configure(IExperiment parent, string resultsFilePath)
        {
            if (status != enExperimentStatus.Running)
            {
                this.parent = parent;

                ResultsFilePath = Path.Combine(resultsFilePath, Name); ;
                ResultsFileName = "ExpScanArray - " + Name + ".dat";

                IPositioner pos = Settings.Positioners[Settings.Positioner];
                if (Settings.Tilt)
                {
                    pos = Settings.Positioners[Settings.TiltPositioner];
                    Tilt = new TiltCorrection(pos, Settings.Pos1, Settings.Pos2, Settings.Pos3, Settings.Offset);
                    Tilt.PositionStore = PositionStore;
                }

                Scanner = new ScannerArray(Settings.ScannerMode, pos, Settings.Lengths, Settings.Increments, Settings.Speeds,
                    Settings.ReverseSpeeds, Settings.PreMovementHook, Settings.PostMovementHook, Tilt,
                    Settings.XDelay, Settings.YDelay, Settings.ZDelay,
                    log);
                Scanner.Initialize();

                //safety check: if the tilt correction is in use, a scan in Z direction is not a good idea.
                if ((Math.Abs(Settings.Increments.Z) > 0) && (Math.Abs(Settings.Lengths.Z) > 0) &&
                    (Math.Abs(Settings.Increments.Z) <= Math.Abs(Settings.Lengths.Z)) && (Settings.Tilt))
                {
                    //todo: describe error
                    return enExperimentStatus.Error;
                }

                // create ScanData container
                scanData = new ScanData();
                scanData.experimentName = Name;

                reverseScanX = Settings.Increments.X < 0;
                reverseScanY = Settings.Increments.Y < 0;
                scanData.setScanDimensions(Scanner.NumScanPoints[0], Scanner.NumScanPoints[1]);

                // Current Positioner pos
                Position startPos = new Position();
                if(pos.GetAbsolutePosition(ref startPos) != enuPositionerStatus.Ready) return enExperimentStatus.Error;

                // set scanData dimensions
                scanData.X0 = Math.Min(startPos.X, (Scanner.NumScanPoints[0] - 1) * Settings.Increments.X);
                scanData.Y0 = Math.Min(startPos.Y, (Scanner.NumScanPoints[1] - 1) * Settings.Increments.Y);
                scanData.X1 = Math.Max(startPos.X, (Scanner.NumScanPoints[0] - 1) * Settings.Increments.X);
                scanData.Y1 = Math.Max(startPos.Y, (Scanner.NumScanPoints[1] - 1) * Settings.Increments.Y);
                status = enExperimentStatus.Idle;
                return status;
            }
            return enExperimentStatus.Error;
        }
Ejemplo n.º 41
0
		/// <summary>
		/// Do the task
		/// </summary>
		/// <param name="source"></param>
		/// <returns></returns>
		public override ScanData DoTask(ScanData source)
		{
			ScanData ret = new ScanData(source.Count);
			source.Sort();
			int count = source.Count;
			int ParallelCount = Settings.Get<Settings>().Read(Settings.SYSTEM, Settings.MAXTHREADS, 8);
			UpdatePercent(0, ret);
			if (LaunchParallel)
			{
				int doneCount = 0;
				Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = ParallelCount }, i =>
				{
					if (this.CancelPending) return;
					ScanLine line = DoTask(source[i]);
					if (line != null)
					{
						//line.DisplayAsLine = source[i].DisplayAsLine;
						lock (ret)
						{
							ret.Add(line);
						}
						doneCount++;
						{
							int percent = (int)((100 * doneCount) / count);
							if (percent % 10 == 0)
								UpdatePercent(percent, ret);
						}
					}

				}
							 );
			}
			else
			{

				for (int i = 0; i < count; i++)
				{
					if (this.CancelPending) return ret;
					ScanLine line = DoTask(source[i]);
					if (line != null)
						ret.Add(line);
					UpdatePercent((int)(100 * i / count), ret);
				}
			}
			UpdatePercent(100, ret);
			return ret;
		}
Ejemplo n.º 42
0
		public override ScanData DoTask(ScanData source)
		{
			ScanData ret = source;
			Dictionary<int, ScanData> laserScanData = new Dictionary<int, ScanData>();
			UpdatePercent(0, ret);
			for (int i = 0; i < source.Count; i++)
			{
				ScanLine currentLine = source[i];
				ScanData data = laserScanData.ContainsKey(currentLine.LaserID) ? laserScanData[currentLine.LaserID] : new ScanData();
				data.Add(currentLine);
				laserScanData[currentLine.LaserID] = data;
			}
			if (laserScanData.Keys.Count >= 1)
			{
					List<ScanData> datas = new List<ScanData>(laserScanData.Values);
					int maxSamplePoints = 10000;
					for (int i = 0; i < datas.Count; i++)
						maxSamplePoints = Math.Min(maxSamplePoints, datas[i].PointCount());
					//ICP.ICP icp = new ICP.ICP(maxSamplePoints/2, 0.001f, 10);
					ICP.IterativeClosestPointTransform icp = new ICP.IterativeClosestPointTransform();
					icp.NumberOfIterations = 1000;
					icp.NumberOfStartTrialPoints = maxSamplePoints/2;
					ICP.IterativeClosestPointTransform.SimulatedAnnealing = false;
					ICP.IterativeClosestPointTransform.DistanceOptimization = true;

					Point3DList refpoints = CreateListFromScanData(datas[0]);
					for (int i = 1; i < datas.Count; i++)
					{
						Point3DList points = CreateListFromScanData(datas[i]);
						Matrix4d mat =  icp.PerformICP(refpoints, points);
						datas[i].Transform(mat);
						
						//icp.Run(points, refpoints);
						UpdatePercent((int)(100f*i/datas.Count), ret);
					}
			}

			UpdatePercent(100, ret);
			return ret;

		}
Ejemplo n.º 43
0
		/// <summary>
		/// Write ScanData File
		/// </summary>
		/// <param name="file"></param>
		/// <param name="points"></param>
		public static void Write(string file, ScanData points)
		{
			using (StreamWriter w = System.IO.File.CreateText(file))
			{
				w.WriteLine(string.Format("slice count:{0}", points.Count));
				for (int i = 0; i < points.Count; i++)
				{
					ScanLine slice = points[i];
					w.WriteLine(string.Format("data:{0}", slice.LaserID.ToString()));
					w.WriteLine(string.Format("DrawAs:{0}", slice.DrawAs));
					w.WriteLine(string.Format("vertice count:{0}", slice.Count));
					for (int j = 0; j < slice.Count; j++)
					{
						Point3D p = slice[j];
						w.Write(string.Format("{0}|", p.Position.Dump()));
						w.Write(string.Format("{0}|", p.Normal.Dump()));
						w.WriteLine(string.Format("{0}", System.Drawing.ColorTranslator.ToHtml(p.Color)));
					}
				}
			}
		}
Ejemplo n.º 44
0
		/// <summary>
		/// Write ScanData To PLY file
		/// </summary>
		/// <param name="file"></param>
		/// <param name="points"></param>
		public static void Write(string file, ScanData points)
		{
			using (StreamWriter w = System.IO.File.CreateText(file))
			{
				w.WriteLine("ply");
				w.WriteLine("format ascii 1.0");
				w.WriteLine(string.Format("element vertex {0}", points.PointCount()));  // Leave space for updating the vertex count
				w.WriteLine("property double x");
				w.WriteLine("property double y");
				w.WriteLine("property double z");
				w.WriteLine("property double nx");
				w.WriteLine("property double ny");
				w.WriteLine("property double nz");
				w.WriteLine("property uchar red");
				w.WriteLine("property uchar green");
				w.WriteLine("property uchar blue");
				w.WriteLine("element face 0");
				w.WriteLine("property list uchar int vertex_indices");
				w.WriteLine("end_header");
				for (int i = 0; i < points.Count; i++)
					Write(w, points[i]);
			}
		}
Ejemplo n.º 45
0
		public override ScanData DoTask(ScanData source)
		{
			ScanData ret = new ScanData(source.Count);
			UpdatePercent(0, ret);
			source.Sort();
			int count = source.Count;
			/*
			for (int i = 1; i <= count; i++)
			{
				if (this.CancelPending) return source;
				ScanLine current = source[i % count];
				ScanLine prev = source[(i-1) % count];
				ScanLine next = source[(i+1) % count];
				int lineCount = current.Count;

				ScanLine smoothed = new ScanSlice(current.Count);
				smoothed.DisplayAsLine = current.DisplayAsLine;

				for (int l = 0; l < lineCount; l++)
				{
					smoothed.Add(Smooth(l, prev, current, next));
				}
				ret.Add(smoothed);
				UpdatePercent((int)((100 * i) / count), ret);
			}
			 */
			ret = source;
			for (int i = 0; i < Iteration; i++)
			{
				double pctstart = i * 100f/Iteration;
				double pctend = pctstart + 100f / Iteration;
				ret = DoIteration(ret, pctstart, pctend);
			}
			UpdatePercent(100, ret);
			return ret;
		}
Ejemplo n.º 46
0
        ArrayList SerializeOps(ScanData[] asd)
        {
            // Serialize ops. Remove trailing and beginning transparency between scans
            // and replace with NextScan ops.
            ArrayList alsOps = new ArrayList();
            ArrayList alsT = new ArrayList();
            int cpSkip = -1;
            foreach (ScanData sd in asd) {
                alsT.Clear();
                alsT.AddRange(sd.GetOps());

                // If cpSkip != -1 then we've removed some trailing transparency
                // from the last scan. Search the start of this new scan.
                if (cpSkip != -1) {
                    int iop = 0;
                    for (; iop < alsT.Count; iop++) {
                        // Add up the transparency
                        Op op = (Op)alsT[iop];
                        if (op >= Op.Transparent1 && op <= Op.Transparent32) {
                            cpSkip += op - Op.Transparent1 + 1;
                            continue;
                        }
                        break;
                    }

                    // Hit a non-transparent op or end of list. Remove found transparent ops
                    alsT.RemoveRange(0, iop);

                    // Max is...
                    int cpMax = m_cx > s_cpNextScanMax ? s_cpNextScanMax : m_cx;

                    // If there is too much transparency to endcode in one
                    // NextScan op, cut into pieces.
                    int cpExtra = cpSkip - cpMax;
                    if (cpExtra > 0) {
                        cpSkip -= cpExtra;
                        while (cpExtra != 0) {
                            int cpT = cpExtra <= s_cpTransparentMax ? cpExtra : s_cpTransparentMax;
                            alsT.Insert(0, Op.Transparent1 + cpT - 1);
                            cpExtra -= cpT;
                        }
                    }

                    // Insert NextScan op
                    alsT.Insert(0, Op.NextScan0 + cpSkip);
                }

                // Now remove trailing transparency if there is any.
                cpSkip = 0;
                int iopTrailing = -1;
                for (int iop = 0; iop < alsT.Count; iop++) {
                    Op op = (Op)alsT[iop];
                    if (op >= Op.Transparent1 && op <= Op.Transparent32) {
                        if (iopTrailing == -1)
                            iopTrailing = iop;
                        cpSkip += op - Op.Transparent1 + 1;
                        continue;
                    } else {
                        iopTrailing = -1;
                        cpSkip = 0;
                    }
                }

                // Remove the trailing transparency
                if (iopTrailing != -1) {
                    // Remove this transparency
                    alsT.RemoveRange(iopTrailing, alsT.Count - iopTrailing);

                    // If we've skipped more than the largest EndScan, insert some
                    // transparency.
                    int cpExtra = cpSkip - s_cpNextScanMax;
                    if (cpExtra > 0) {
                        cpSkip -= cpExtra;
                        while (cpExtra != 0) {
                            int cpT = cpExtra <= s_cpTransparentMax ? cpExtra : s_cpTransparentMax;
                            alsT.Add(Op.Transparent1 + cpT - 1);
                            cpExtra -= cpT;
                        }
                    }
                }

                // alsT is ready to add to the ops list
                alsOps.AddRange(alsT);
            }

            // Add End op
            alsOps.Add(Op.End);
            return alsOps;
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Do the task function override
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public override ScanData DoTask(ScanData source)
        {
            ScanData ret = new ScanData(source.Count);
            UpdatePercent(0, ret);
            source.Sort();
            int count = source.Count;
            //count = 2;
            //primitiveType = PrimitiveType.LineStrip;
            ScanLine top = new ScanLine(count);
            ScanLine bottom = new ScanLine(count);

            ScanLine prev = source[0];
            top.Add(prev.First());
            bottom.Add(prev.Last());

            for (int i = 1; i <= count; i++)
            {
                if (this.CancelPending) return source;
                ScanLine current = source[i % count];
                StripResult strip = CreateStrip(prev, current);

                top.Add(strip.Current.First());
                bottom.Add(strip.Current.Last());

                prev = strip.Current;

                ret.Add(strip.Result);
                UpdatePercent((int)((100 * i) / count), ret);
            }
            if (count <= 2)
                return ret;
            Point3D topcenter = Point3D.Average(top);
            Point3D bottomcenter = Point3D.Average(bottom);
            for (int i = 0; i < ret.Count; i++)
            {
                ret[i].Insert(0, topcenter);
                ret[i].Add(bottomcenter);
                AdjustNormalFromTriangleStrip(ret[i]);
            }
            UpdatePercent(100, ret);
            return ret;

        }
Ejemplo n.º 48
0
        /// <summary>
        /// Handle a single spectrum element and child nodes
        /// Called by ReadSpectrumList (xml hierarchy)
        /// </summary>
        /// <param name="reader">XmlReader that is only valid for the scope of the single spectrum element</param>
        /// <param name="includePeaks">Whether to read binary data arrays</param>
        private Spectrum ReadSpectrum(XmlReader reader, bool includePeaks = true)
        {
            reader.MoveToContent();
            string index = reader.GetAttribute("index");
            //Console.WriteLine("Reading spectrum indexed by " + index);
            // This is correct for Thermo files converted by msConvert, but need to implement for others as well
            string spectrumId = reader.GetAttribute("id"); // Native ID in mzML_1.1.0; unique identifier in mzML_1.0.0, often same as nativeID
            string nativeId = spectrumId;
            if (_version == MzML_Version.mzML1_0_0)
            {
                nativeId = reader.GetAttribute("nativeID"); // Native ID in mzML_1.0.0
            }

            int scanNum = -1;
            // If a random access reader, there is already a scan number stored, based on the order of the index. Use it instead.
            if (_randomAccess)
            {
                scanNum = (int) (_spectrumOffsets.NativeToIdMap[nativeId]);
            }
            else
            {
                scanNum = (int)(_artificialScanNum++);
                // Interpret the NativeID (if the format has an interpreter) and use it instead of the artificial number.
                // TODO: Better handling than the artificial ID for other nativeIDs (ones currently not supported)
                int num = 0;
                if (NativeIdConversion.TryGetScanNumberInt(nativeId, out num))
                {
                    scanNum = num;
                }
            }

            int defaultArraySize = Convert.ToInt32(reader.GetAttribute("defaultArrayLength"));
            reader.ReadStartElement("spectrum"); // Throws exception if we are not at the "spectrum" tag.
            bool is_ms_ms = false;
            int msLevel = 0;
            bool centroided = false;
            double tic = 0;
            List<Precursor> precursors = new List<Precursor>();
            List<ScanData> scans = new List<ScanData>();
            List<BinaryDataArray> bdas = new List<BinaryDataArray>();
            while (reader.ReadState == ReadState.Interactive)
            {
                // Handle exiting out properly at EndElement tags
                if (reader.NodeType != XmlNodeType.Element)
                {
                    reader.Read();
                    continue;
                }
                //////////////////////////////////////////////////////////////////////////////////////
                /// 
                /// MS1 Spectra: only need Spectrum data: scanNum, MSLevel, ElutionTime, mzArray, IntensityArray
                /// 
                /// MS2 Spectra: use ProductSpectrum; adds ActivationMethod and IsolationWindow
                /// 
                //////////////////////////////////////////////////////////////////////////////////////
                switch (reader.Name)
                {
                    case "referenceableParamGroupRef":
                        // Schema requirements: zero to many instances of this element
                        reader.Skip();
                        break;
                    case "cvParam":
                        // Schema requirements: zero to many instances of this element
                        /* MAY supply a *child* term of MS:1000465 (scan polarity) only once
                         *   e.g.: MS:1000129 (negative scan)
                         *   e.g.: MS:1000130 (positive scan)
                         * MUST supply a *child* term of MS:1000559 (spectrum type) only once
                         *   e.g.: MS:1000322 (charge inversion mass spectrum)
                         *   e.g.: MS:1000325 (constant neutral gain spectrum)
                         *   e.g.: MS:1000326 (constant neutral loss spectrum)
                         *   e.g.: MS:1000328 (e/2 mass spectrum)
                         *   e.g.: MS:1000341 (precursor ion spectrum)
                         *   e.g.: MS:1000579 (MS1 spectrum)
                         *   e.g.: MS:1000580 (MSn spectrum)
                         *   e.g.: MS:1000581 (CRM spectrum)
                         *   e.g.: MS:1000582 (SIM spectrum)
                         *   e.g.: MS:1000583 (SRM spectrum)
                         *   e.g.: MS:1000620 (PDA spectrum)
                         *   e.g.: MS:1000627 (selected ion current chromatogram)
                         *   e.g.: MS:1000789 (enhanced multiply charged spectrum)
                         *   e.g.: MS:1000790 (time-delayed fragmentation spectrum)
                         *   et al.
                         * MUST supply term MS:1000525 (spectrum representation) or any of its children only once
                         *   e.g.: MS:1000127 (centroid spectrum)
                         *   e.g.: MS:1000128 (profile spectrum)
                         * MAY supply a *child* term of MS:1000499 (spectrum attribute) one or more times
                         *   e.g.: MS:1000285 (total ion current)
                         *   e.g.: MS:1000497 (zoom scan)
                         *   e.g.: MS:1000504 (base peak m/z)
                         *   e.g.: MS:1000505 (base peak intensity)
                         *   e.g.: MS:1000511 (ms level)
                         *   e.g.: MS:1000527 (highest observed m/z)
                         *   e.g.: MS:1000528 (lowest observed m/z)
                         *   e.g.: MS:1000618 (highest observed wavelength)
                         *   e.g.: MS:1000619 (lowest observed wavelength)
                         *   e.g.: MS:1000796 (spectrum title)
                         *   et al.
                         */
                        switch (reader.GetAttribute("accession"))
                        {
                            case "MS:1000127":
                                // name="centroid spectrum"
                                centroided = true;
                                break;
                            case "MS:1000128":
                                // name="profile spectrum"
                                centroided = false;
                                break;
                            case "MS:1000511":
                                // name="ms level"
                                msLevel = Convert.ToInt32(reader.GetAttribute("value"));
                                break;
                            case "MS:1000579":
                                // name="MS1 spectrum"
                                is_ms_ms = false;
                                break;
                            case "MS:1000580":
                                // name="MSn spectrum"
                                is_ms_ms = true;
                                break;
                            case "MS:1000285":
                                // name="total ion current"
                                tic = Convert.ToDouble(reader.GetAttribute("value"));
                                break;
                        }
                        reader.Read(); // Consume the cvParam element (no child nodes)
                        break;
                    case "userParam":
                        // Schema requirements: zero to many instances of this element
                        reader.Skip();
                        break;
                    case "spectrumDescription": // mzML_1.0.0 compatibility
                        // Schema requirements: one instance of this element
                        ReadSpectrumDescription(reader.ReadSubtree(), ref scans, ref precursors, out centroided);
                        reader.ReadEndElement(); // "spectrumDescription" must have child nodes
                        break;
                    case "scanList":
                        // Schema requirements: zero to one instances of this element
                        scans.AddRange(ReadScanList(reader.ReadSubtree()));
                        reader.ReadEndElement(); // "scanList" must have child nodes
                        break;
                    case "precursorList":
                        // Schema requirements: zero to one instances of this element
                        precursors.AddRange(ReadPrecursorList(reader.ReadSubtree()));
                        reader.ReadEndElement(); // "precursorList" must have child nodes
                        break;
                    case "productList":
                        // Schema requirements: zero to one instances of this element
                        reader.Skip();
                        break;
                    case "binaryDataArrayList":
                        // Schema requirements: zero to one instances of this element
                        if (includePeaks)
                        {
                            bdas.AddRange(ReadBinaryDataArrayList(reader.ReadSubtree(), defaultArraySize));
                            reader.ReadEndElement(); // "binaryDataArrayList" must have child nodes
                        }
                        else
                        {
                            reader.Skip();
                        }
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }
            reader.Close();
            // Process the spectrum data
            ScanData scan = new ScanData();
            Spectrum spectrum;
            BinaryDataArray mzs = new BinaryDataArray();
            BinaryDataArray intensities = new BinaryDataArray();
            foreach (var bda in bdas)
            {
                if (bda.ArrayType == ArrayType.m_z_array)
                {
                    mzs = bda;
                }
                else if (bda.ArrayType == ArrayType.intensity_array)
                {
                    intensities = bda;
                }
            }
            
            if (!centroided && includePeaks)
            {
                // Centroid spectrum
                // ProteoWizard
                var centroider = new Centroider(mzs.Data, intensities.Data);
                double[] centroidedMzs, centroidedIntensities;
                centroider.GetCentroidedData(out centroidedMzs, out centroidedIntensities);
                mzs.Data = centroidedMzs;
                intensities.Data = centroidedIntensities;
            }
            if (scans.Count == 1)
            {
                scan = scans[0];
            }
            else if (scans.Count > 1)
            {
                // TODO: Should do something else to appropriately handle combinations...
                scan = scans[0];
            }

            if (is_ms_ms)
            {
                Precursor precursor = new Precursor();
                if (precursors.Count == 1)
                {
                    precursor = precursors[0];
                }
                else if (precursors.Count > 1)
                {
                    // TODO: Should do something else to appropriately handle multiple precursors...
                    precursor = precursors[0];
                }
                SelectedIon ion = new SelectedIon();
                if (precursor.Ions.Count == 1)
                {
                    ion = precursor.Ions[0];
                }
                else if (precursor.Ions.Count > 1)
                {
                    // TODO: Should do something else to appropriately handle multiple selected ions...
                    ion = precursor.Ions[0];
                }

                var pspectrum = new ProductSpectrum(mzs.Data, intensities.Data, scanNum);
                pspectrum.ActivationMethod = precursor.Activation;
                // Select mz value to use based on presence of a Thermo-specific user param.
                // The user param has a slightly higher precision, if that matters.
                double mz = scan.MonoisotopicMz == 0.0 ? ion.SelectedIonMz : scan.MonoisotopicMz;
                pspectrum.IsolationWindow = new IsolationWindow(precursor.IsolationWindowTargetMz, precursor.IsolationWindowLowerOffset, precursor.IsolationWindowUpperOffset, mz, ion.Charge);
                //pspectrum.IsolationWindow.OldCharge = ion.OldCharge;
                //pspectrum.IsolationWindow.SelectedIonMz = ion.SelectedIonMz;
                spectrum = pspectrum;
            }
            else
            {
                spectrum = new Spectrum(mzs.Data, intensities.Data, scanNum);
            }
            spectrum.MsLevel = msLevel;
            spectrum.ElutionTime = scan.StartTime;
            spectrum.NativeId = nativeId;
            spectrum.TotalIonCurrent = tic;
            
            return spectrum;
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Handle a single scan element and child nodes
        /// Called by ReadSpectrum (xml hierarchy)
        /// </summary>
        /// <param name="reader">XmlReader that is only valid for the scope of the single scan element</param>
        /// <returns></returns>
        private ScanData ReadScan(XmlReader reader)
        {
            reader.MoveToContent();
            if (_version == MzML_Version.mzML1_0_0)
            {
                string name = reader.Name;
                if (!name.Equals("scan") && !name.Equals("acquisition"))
                {
                    throw new XmlException("Invalid schema");
                }
                reader.ReadStartElement(name);
            }
            else
            {
                reader.ReadStartElement("scan"); // Throws exception if we are not at the "scan" tag.
            }
            ScanData scan = new ScanData();
            while (reader.ReadState == ReadState.Interactive)
            {
                // Handle exiting out properly at EndElement tags
                if (reader.NodeType != XmlNodeType.Element)
                {
                    reader.Read();
                    continue;
                }

                switch (reader.Name)
                {
                    case "referenceableParamGroupRef":
                        // Schema requirements: zero to many instances of this element
                        reader.Skip();
                        break;
                    case "cvParam":
                        // Schema requirements: zero to many instances of this element
                        /* MAY supply a *child* term of MS:1000503 (scan attribute) one or more times
                         *   e.g.: MS:1000011 (mass resolution)
                         *   e.g.: MS:1000015 (scan rate)
                         *   e.g.: MS:1000016 (scan start time)
                         *   e.g.: MS:1000502 (dwell time)
                         *   e.g.: MS:1000512 (filter string)
                         *   e.g.: MS:1000616 (preset scan configuration)
                         *   e.g.: MS:1000800 (mass resolving power)
                         *   e.g.: MS:1000803 (analyzer scan offset)
                         *   e.g.: MS:1000826 (elution time)
                         *   e.g.: MS:1000880 (interchannel delay)
                         * MAY supply a *child* term of MS:1000018 (scan direction) only once
                         *   e.g.: MS:1000092 (decreasing m/z scan)
                         *   e.g.: MS:1000093 (increasing m/z scan)
                         * MAY supply a *child* term of MS:1000019 (scan law) only once
                         *   e.g.: MS:1000094 (exponential)
                         *   e.g.: MS:1000095 (linear)
                         *   e.g.: MS:1000096 (quadratic)
                         */
                        switch (reader.GetAttribute("accession"))
                        {
                            case "MS:1000016":
                                // name="scan start time"
                                double time = Convert.ToDouble(reader.GetAttribute("value"));
                                bool isSeconds = reader.GetAttribute("unitName") == "second";
                                // Should only see "second" and "minute"
                                scan.StartTime = isSeconds ? time / 60.0 : time;
                                //scan.StartTime = Convert.ToDouble(reader.GetAttribute("value"));
                                break;
                            case "MS:1000512":
                                // name="filter string"
                                break;
                            case "MS:1000616":
                                // name="preset scan configuration"
                                break;
                            case "MS:1000927":
                                // name="ion injection time"
                                break;
                            case "MS:1000826":
                                // name="elution time"
                                //startTime = Convert.ToDouble(reader.GetAttribute("value"));
                                break;
                        }
                        reader.Read(); // Consume the cvParam element (no child nodes)
                        break;
                    case "userParam":
                        // Schema requirements: zero to many instances of this element
                        if (reader.GetAttribute("name") == "[Thermo Trailer Extra]Monoisotopic M/Z:")
                        {
                            scan.MonoisotopicMz = Convert.ToDouble(reader.GetAttribute("value"));
                        }
                        reader.Read(); // Consume the userParam element (no child nodes)
                        break;
                    case "scanWindowList":
                        // Schema requirements: zero to one instances of this element
                        //ReadScanList(reader.ReadSubtree());
                        //reader.ReadEndElement(); // "scanWindowList" must have child nodes
                        reader.Skip();
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }
            reader.Close();
            return scan;
        }
Ejemplo n.º 50
0
 /// <summary>
 /// 
 /// </summary>
 private void packScan()
 {
     ScanData sd = new ScanData();
     sd.code = _code.ToString();
     sd.symb = Symbology.UNKNOWN;
     OnScanData( sd );
 }
Ejemplo n.º 51
0
		/// <summary>
		/// Realy do the task
		/// </summary>
		/// <param name="source"></param>
		/// <returns></returns>
		public abstract ScanData DoTask(ScanData source);
Ejemplo n.º 52
0
		protected void UpdateViewer(ScanData points)
		{
			IScene3DViewer viewer = Settings.Get<IScene3DViewer>();
			if (viewer != null)
			{
				viewer.Scene.Clear();
				if (points != null)
					viewer.Scene.Add(points);
				viewer.Invalidate();
			}
		}
Ejemplo n.º 53
0
		protected override void Save(ScanData source)
		{
			WaveFormIO.Write(this.Filename, source);
		}
Ejemplo n.º 54
0
		public override ScanData DoTask(ScanData source)
		{
			LastError = string.Empty;
			{
				if (String.IsNullOrEmpty(Filename))
				{
					string file = ShowDialog();
					if (!string.IsNullOrEmpty(file))
						this.Filename = file;
				}


				if (!String.IsNullOrEmpty(Filename))
				{
					this.Status = eTaskStatus.Working;
					UpdatePercent(0, source);
					Save(source);
					this.Status = eTaskStatus.Finished;
					UpdatePercent(100, source);
				}
				else
				{
					this.Status = eTaskStatus.Error;
					LastError = String.Format("Invalid File {0}", this.Filename);
				}
				return source;
			}
		}
Ejemplo n.º 55
0
		/// <summary>
		/// Read ScanData File
		/// </summary>
		/// <param name="file"></param>
		/// <returns></returns>
		public static ScanData Read(string file)
		{
			ScanData ret = new ScanData();
			using (StreamReader r = System.IO.File.OpenText(file))
			{
				string line = r.ReadLine();
				string[] part = line.Split(":".ToArray());
				int slicecount = int.Parse(part[1]);
				for (int i = 0; i < slicecount; i++)
				{
					line = r.ReadLine();
					part = line.Split(":".ToArray());
					ScanLine slice = new ScanLine((int)double.Parse(part[1]));

					line = r.ReadLine();
					part = line.Split(":".ToArray());
					if (part[0] == "DrawAs")
					{
						OpenTK.Graphics.OpenGL.PrimitiveType primitive = OpenTK.Graphics.OpenGL.PrimitiveType.Points;
						Enum.TryParse<OpenTK.Graphics.OpenGL.PrimitiveType>(part[1], true, out primitive);
						switch (primitive)
						{
							case OpenTK.Graphics.OpenGL.PrimitiveType.TriangleStrip:
								{
									slice = new ScanSlice(10000);
									break;
								}
							case OpenTK.Graphics.OpenGL.PrimitiveType.LineStrip:
								{
									slice.DisplayAsLine = true;
									break;
								}
							default:
								{
									slice.DisplayAsLine = false;
									break;
								}
						}
						line = r.ReadLine();
						part = line.Split(":".ToArray());
					}
					int pointcount = int.Parse(part[1]);

					for (int j = 0; j < pointcount; j++)
					{
						line = r.ReadLine();
						part = line.Split("|".ToArray());

						Vector3d pos = GetVector(part[0]);
						Vector3d normal = pos.Normalized();
						try
						{
							normal = GetVector(part[1]);
						}
						catch { }
						Color color = System.Drawing.ColorTranslator.FromHtml(part[2]);
						Point3D p = new Point3D(pos, normal, color);
						slice.Add(p);
					}
					ret.Add(slice);
				}
			}
			return ret;
		}
Ejemplo n.º 56
0
		public override void UpdatePercent(int percent, ScanData data)
		{
			base.UpdatePercent(percent, data);
			IScene3DViewer viewer = Settings.Get<IScene3DViewer>();
			if (viewer != null)
			{
				Control ctl = viewer as Control;
				if (ctl == null || !ctl.InvokeRequired)
				{
					viewer.Scene.Clear();
					if (data != null)
						viewer.Scene.Add(data);
					viewer.Invalidate();
				}
				else
					ctl.BeginInvoke(new Action(() =>
					{
						viewer.Scene.Clear();
						if (data != null)
							viewer.Scene.Add(data);
						viewer.Invalidate();
					}));
			}
		}
Ejemplo n.º 57
0
		public override ScanData DoTask(ScanData source)
		{
			if (!HardwareAvailable)
				throw new Exception(string.Format("HardWare missing : TURNTABLE:{0} LASER:{1} CAMERA:{2}", HardwarePresentTrace(TurnTable), HardwarePresentTrace(Laser), HardwarePresentTrace(Camera)));



			RotationStep = (double)Math.Round(TurnTable.MinimumRotation() + (15f - TurnTable.MinimumRotation()) * ((100 - Precision) / 100f), 2);


			Settings settings = Settings.Get<Settings>();
			CameraLoc.X = settings.Read(Settings.CAMERA, Settings.X, 0f);
			CameraLoc.Y = settings.Read(Settings.CAMERA, Settings.Y, 270f);
			CameraLoc.Z = settings.Read(Settings.CAMERA, Settings.Z, 70f);

			double thres = settings.Read(Settings.LASER_COMMON, Settings.MAGNITUDE_THRESHOLD, 10);
			int min = settings.Read(Settings.LASER_COMMON, Settings.MIN_WIDTH, 1);
			int max = settings.Read(Settings.LASER_COMMON, Settings.MAX_WIDTH, 60);


			ICameraProxy camera = Settings.Get<ICameraProxy>();
			ImageProcessor = new ImageProcessor(thres, min, max);

			SizeF tableSize = new SizeF(
					(float)settings.Read(Settings.TABLE, Settings.DIAMETER, 20f),
                    (float)settings.Read(Settings.TABLE, Settings.HEIGHT, 15f)
					);

			Lasers = new List<LaserInfo>(LaserId.Length);
			for (int i = 0; i < LaserId.Length; i++)
			{
				Lasers.Add(new LaserInfo(LaserId[i], CameraLoc, tableSize));
			}

			ScanData ret = new ScanData();
			UpdatePercent(0, ret);
            int fadeTime = settings.Read(Settings.LASER_COMMON, Settings.FADE_DELAY, 100);

			TurnTable.InitialiseRotation();
			int laserCount = Lasers.Count;
			// Scan all laser location, 
			for (double currentAngle = 0; currentAngle < 360f; currentAngle += RotationStep)
			{
				if (this.CancelPending) return ret;

				Laser.TurnAll(false); // All laser off
                Thread.Sleep(fadeTime); // wait fade laser
                Bitmap imgoff = GetCapture();
				for (int laserIndex = 0; laserIndex < laserCount; laserIndex++)
				{
					Laser.Turn(Lasers[laserIndex].Id, true);
                    Thread.Sleep(fadeTime); // wait fade laser
					Bitmap imgon = GetCapture();
					Laser.Turn(Lasers[laserIndex].Id, false);

                    List<PointF> laserloc = ImageProcessor.Process(imgoff,imgon,null);

					Point3DList samplePoints = Lasers[laserIndex].MapPoints(laserloc, UseTexture ? imgoff : null, UseCorrectionMatrix);
					PositionPostProcess(ref samplePoints, -Utils.DEGREES_TO_RADIANS(currentAngle));
					ScanLine line = new ScanLine(laserIndex, samplePoints);
					line.DisplayAsLine = true;
					ret.Add(line);
				}
				int percent = (int)((currentAngle / 360f) * 100f);
				UpdatePercent(percent, ret);
				TurnTable.Rotate(currentAngle, false);
			}
			LineSort lineSort = new LineSort();
			ret = lineSort.Run(ret, CallerControl, this.Worker, this.WorkerArg);
			if (!string.IsNullOrEmpty(FileName))
			{
				string path = Path.Combine(Program.UserDataPath, FileName);
				ScanDataIO.Write(path, ret);
			}
			return ret;
		}
Ejemplo n.º 58
0
		protected virtual void Save(ScanData source)
		{
			ScanDataIO.Write(Filename, source);
		}
Ejemplo n.º 59
0
				public override ScanData DoTask(ScanData source)
        {
					LastError = string.Empty;
            if (!ValidFile)
            {
               string file =ShowDialog();
               if(!string.IsNullOrEmpty(file))
                   this.Filename = file;
            }


						if (ValidFile)
						{
							this.Status = eTaskStatus.Working;
							UpdatePercent(0, null);
							ScanData ret = ScanDataIO.Read(this.Filename);
							this.Status = eTaskStatus.Finished;
							UpdatePercent(100, ret);
							return ret;
						}
						else
						{
							this.Status = eTaskStatus.Error;
							LastError = String.Format("Invalid File {0}", this.Filename);
						}
					return null;
        }
Ejemplo n.º 60
0
        public override Sardauscan.Core.ScanData DoTask(Sardauscan.Core.ScanData source)
        {
            if (!HardwareAvailable)
                throw new Exception(string.Format("HardWare missing : TURNTABLE:{0} LASER:{1} CAMERA:{2}", HardwarePresentTrace(TurnTable), HardwarePresentTrace(Laser), HardwarePresentTrace(Camera)));

            double RotationStep = (double)Math.Round(360.0 / (NumberOfGrab-1), 2);
            ScanData ret = new ScanData();
            UpdatePercent(0, ret);

            TurnTable.InitialiseRotation();
            Laser.TurnAll(false);
            int index = 0;    
            for (double currentAngle = 0; currentAngle < 360f; currentAngle += RotationStep)
            {
                if (this.CancelPending) return ret;
                Bitmap imgoff = GetCapture();
                string path = Path.Combine(Folder, string.Format("capture{0}.jpg", ++index,(int)currentAngle));
                imgoff.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

                int percent = (int)((currentAngle / 360f) * 100f);
                UpdatePercent(percent, ret);
                TurnTable.Rotate(currentAngle, false);
                Thread.Sleep(1000);
            }

            return null;
        }