领胜LDS 键盘AOI检测项目
patrick.xu
2021-03-06 8a3ab64a65da226636743be07c4bee63f50da25d
src/Bro.Device.Gocator/GocatorDriver.cs
@@ -13,6 +13,7 @@
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
@@ -90,13 +91,12 @@
                            long bufferSize = width * height;
                            IntPtr bufferPointer = surfaceMsg.Data;
                            float zoomFactor = (float)((double)surfaceMsg.YResolution / (double)surfaceMsg.XResolution);
                            int zoomHeight = (int)(zoomFactor * height);
                            //IntPtr zoomPtr = Marshal.AllocHGlobal(zoomHeight * (int)width * 2);
                            IntPtr zoomPtr = Marshal.AllocHGlobal(zoomHeight * (int)width * 2);
                            //IntPtr zoomPtr = Marshal.AllocHGlobal(zoomHeight * (int)width * 4);
                            IntPtr zoomPtr = Marshal.AllocHGlobal(zoomHeight * (int)width * (int)IIConfig.ByteNums);
                            //IntPtr zoomPtr = Marshal.AllocHGlobal(zoomHeight * (int)width * (int)IIConfig.ByteNums);
                            //没有插值,默认0
                            //Parallel.For(0, height, h =>
@@ -104,44 +104,51 @@
                            //      CopyMemory((IntPtr)((long)zoomPtr + width * 2 * Math.Floor(h * zoomFactor)), (IntPtr)((long)bufferPointer + width * 2 * h), width * 2);
                            //  });
                            if (IIConfig.ByteNums == GocatorDataByteNums.Byte2)
                            //if (IIConfig.ByteNums == GocatorDataByteNums.Byte2)
                            //{
                            //使用上一行原有数据
                            Parallel.For(0, zoomHeight, h =>
                            {
                                //使用上一行原有数据
                                Parallel.For(0, zoomHeight, h =>
                                {
                                    int originHeightIndex = (int)Math.Floor((double)height * h / (double)zoomHeight);
                                int originHeightIndex = (int)Math.Floor((double)height * h / (double)zoomHeight);
                                CopyMemory((IntPtr)((long)zoomPtr + width * 2 * h), (IntPtr)((long)bufferPointer + width * 2 * originHeightIndex), width * 2);
                            });
                            //}
                            //else
                            //{
                            //    //使用上一行原有数据
                            //    Parallel.For(0, zoomHeight, h =>
                            //    {
                            //        int originHeightIndex = (int)Math.Floor((double)height * h / (double)zoomHeight);
                                    CopyMemory((IntPtr)((long)zoomPtr + width * 2 * h), (IntPtr)((long)bufferPointer + width * 2 * originHeightIndex), width * 2);
                                });
                            }
                            else
                            {
                                //使用上一行原有数据
                                Parallel.For(0, zoomHeight, h =>
                                {
                                    int originHeightIndex = (int)Math.Floor((double)height * h / (double)zoomHeight);
                            //        byte[] rowBuffer = new byte[width * 4];
                            //        Parallel.For(0, width, w =>
                            //        {
                            //            rowBuffer[w * 4 + 2] = Marshal.ReadByte(bufferPointer, (int)(width * 2 * originHeightIndex + w * 2));
                            //            rowBuffer[w * 4 + 3] = Marshal.ReadByte(bufferPointer, (int)(width * 2 * originHeightIndex + w * 2 + 1));
                            //        });
                                    byte[] rowBuffer = new byte[width * 4];
                                    Parallel.For(0, width, w =>
                                    {
                                        rowBuffer[w * 4 + 2] = Marshal.ReadByte(bufferPointer, (int)(width * 2 * originHeightIndex + w * 2));
                                        rowBuffer[w * 4 + 3] = Marshal.ReadByte(bufferPointer, (int)(width * 2 * originHeightIndex + w * 2 + 1));
                                    });
                                    Marshal.Copy(rowBuffer, 0, (IntPtr)((long)zoomPtr + width * 2 * h), rowBuffer.Length);
                                });
                            }
                            //        Marshal.Copy(rowBuffer, 0, (IntPtr)((long)zoomPtr + width * 2 * h), rowBuffer.Length);
                            //    });
                            //}
                            if (imgSet != null)
                            {
                                imgSet.HImage = new HImage();
                                //imgSet.HImage.GenImage1("uint2", (int)width, zoomHeight, zoomPtr);
                                //imgSet.HImage.GenImage1("int4", (int)width, zoomHeight, zoomPtr);
                                imgSet.HImage.GenImage1(IIConfig.ByteNums == GocatorDataByteNums.Byte2 ? "uint2" : "int4", (int)width, zoomHeight, zoomPtr);
                                //imgSet.HImage.GenImage1(IIConfig.ByteNums == GocatorDataByteNums.Byte2 ? "uint2" : "int4", (int)width, zoomHeight, zoomPtr);
                                imgSet.HImage_2 = imgSet.HImage.Clone();
                                imgSet.HImage.GenImage1("int2", (int)width, zoomHeight, zoomPtr);
                                //imgSet.HImage = imgSet.HImage.ConvertImageType("int4");
                                //imgSet.HImage = imgSet.HImage.ScaleImage(1.0, short.MaxValue + 1.0);
                                //imgSet.HImage = imgSet.HImage.ConvertImageType("uint2");
                                imgSet.HImage_2 = new HImage();
                                imgSet.HImage_2.GenImage1("int2", (int)width, zoomHeight, zoomPtr);
                                //imgSet.HImage_2.GenImage1("uint2", (int)width, zoomHeight, zoomPtr);
                                //imgSet.HImage_2.GenImage1("int4", (int)width, zoomHeight, zoomPtr);
                                //imgSet.HImage_2 = new HImage();
                                //imgSet.HImage_2.GenImage1(IIConfig.ByteNums == GocatorDataByteNums.Byte2 ? "uint2" : "int4", (int)width, zoomHeight, zoomPtr);
                                LaserScanParam para = new LaserScanParam()
@@ -159,6 +166,12 @@
                                //imgSet.HImage_2 = imgSet.HImage_2.ZoomImageSize((int)width, zoomHeight, "constant");
                            }
                            //var showImage = imgSet.HImage_2.ConvertSignedHImageTo16GrayBitmap();
                            //showImage.Save($@"D:\SI\{DateTime.Now.ToString("yyyyMMddHHmmss")}.tif", System.Drawing.Imaging.ImageFormat.Tiff);
                            //SaveOriginImage(null, showImage, imgSet.Id);
                            //Marshal.FreeHGlobal(zoomPtr);
                            Generate16GrayImageByPointer((int)width, zoomHeight, zoomPtr, imgSet?.Id).ContinueWith(t =>
                            {
                                Marshal.FreeHGlobal(zoomPtr);
@@ -216,6 +229,7 @@
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public override IImageSet Snapshot(IOperationConfig config)
        {
            GocatorOperationConfig opConfig = config as GocatorOperationConfig;
@@ -223,7 +237,7 @@
            {
                if (opConfig.IsOpenConnection)
                {
                    system.Start();
                    StartSensor();
                }
                if (!opConfig.IsSnapshotAction)
@@ -238,16 +252,25 @@
            GoDataSet dataSet = null;
            if (IIConfig.IsAsyncMode)
            {
                if (!IIConfig.IsHardwareTrigger)
                if (opConfig.IsSnapshotAction)
                {
                    _snapFlag = true;
                    if (!_snapHandle.WaitOne(IIConfig.SnapshotTimeout))
                    if (!IIConfig.IsHardwareTrigger)
                    {
                        LogAsync(DateTime.Now, $"{Name}获取图像超时", "");
                        return null;
                    }
                        _snapFlag = true;
                        if (!_snapHandle.WaitOne(IIConfig.SnapshotTimeout))
                        {
                            LogAsync(DateTime.Now, $"{Name}获取图像超时", "");
                            return imgSet;
                        }
                    dataSet = _currentData;
                        dataSet = _currentData;
                        //dataSet = system.ReceiveData(IIConfig.SnapshotTimeout);
                    }
                }
                else
                {
                    imgSet = null;
                }
            }
            else
@@ -257,36 +280,115 @@
                    return null;
                }
                try
                int reTryTime = 3;
                do
                {
                    dataSet = system.ReceiveData(IIConfig.SnapshotTimeout);
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, $"{Name}获取图像异常", ex.GetExceptionMessage());
                    return null;
                }
                    try
                    {
                        dataSet = system.ReceiveData(IIConfig.SnapshotTimeout);
                        reTryTime = 0;
                    }
                    catch (Exception ex)
                    {
                        reTryTime--;
                        LogAsync(DateTime.Now, $"{Name}获取图像异常", ex.GetExceptionMessage());
                        if (reTryTime <= 0)
                        {
                            imgSet.HImage = null;
                            dataSet = null;
                            system.ClearData();
                        }
                    }
                } while (reTryTime > 0);
            }
            if (!IIConfig.IsAsyncMode)
            {
                if (!opConfig.IsOpenConnection)
                {
                    system.Stop();
                    sensor.Flush();
                    StopSensor();
                }
            }
            HandleGoData(dataSet, imgSet);
            dataSet.Dispose();
            if (imgSet.HImage == null)
            if (dataSet != null)
            {
                LogAsync(DateTime.Now, $"{Name}未能获取HImage图像", "");
                HandleGoData(dataSet, imgSet);
                dataSet.Dispose();
                if (imgSet.HImage == null)
                {
                    LogAsync(DateTime.Now, $"{Name}未能获取HImage图像", "");
                }
            }
            sensor.Flush();
            return imgSet;
        }
        private void StopSensor()
        {
            while (sensor.State == GoState.Busy)
            {
                Thread.Sleep(100);
            }
            do
            {
                try
                {
                    sensor.Stop();
                    LogAsync(DateTime.Now, $"传感器状态:{sensor.State.ToString()}", "");
                    if (sensor.State != GoState.Ready)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, $"关闭异常:{ex.GetExceptionMessage()}", "");
                    Thread.Sleep(100);
                }
            } while (true);
            LogAsync(DateTime.Now, $"传感器关闭成功", "");
        }
        private void StartSensor()
        {
            while (sensor.State != GoState.Ready)
            {
                Thread.Sleep(10);
            }
            do
            {
                try
                {
                    sensor.Start();
                    LogAsync(DateTime.Now, $"传感器状态:{sensor.State.ToString()}", "");
                    if (sensor.State != GoState.Running)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, $"开启异常:{ex.GetExceptionMessage()}", "");
                    Thread.Sleep(100);
                }
            } while (true);
            LogAsync(DateTime.Now, $"传感器启动成功", "");
        }
        float _currentExposure = 0;
@@ -352,6 +454,7 @@
            system.EnableData(true);
            if (IIConfig.IsAsyncMode)
            {
                system.SetDataHandler(onData);
@@ -384,8 +487,26 @@
        {
            base.Start();
            //if (sensor.State != GoState.Ready)
            //{
            //    system.Start();
            //}
            if (IIConfig.IsAsyncMode)
                system.Start();
            {
                //sensor.Start();
                StartSensor();
            }
            //else
            //{
            //    //if (sensor.State == GoState.Ready)
            //    //{
            //    //    sensor.Stop();
            //    //}
            //    StopSensor();
            //}
        }
        protected override void Stop()
@@ -393,7 +514,9 @@
            base.Stop();
            if (IIConfig.IsAsyncMode)
                system.Stop();
            {
                StopSensor();
            }
            if (IIConfig.IsUseAccelerator)
            {
@@ -422,7 +545,7 @@
        }
        volatile bool _snapFlag = false;
        readonly ManualResetEvent _snapHandle = new ManualResetEvent(false);
        readonly AutoResetEvent _snapHandle = new AutoResetEvent(false);
        GoDataSet _currentData = null;
        /// <summary>
@@ -431,6 +554,7 @@
        /// <param name="data"></param>
        private void onData(KObject data)
        {
            LogAsync(DateTime.Now, $"扫描图像输出", "");
            GoDataSet dataSet = (GoDataSet)data;
            if (IIConfig.IsHardwareTrigger)
@@ -451,11 +575,13 @@
            }
            else
            {
                if (_snapFlag)
                //if (_snapFlag)
                {
                    _snapFlag = false;
                    _currentData = dataSet.Clone<GoDataSet>();
                    _currentData = dataSet;
                    _snapHandle.Set();
                }
            }
@@ -476,8 +602,6 @@
            if (set == null)
                return;
            set.Image = map;
            await Task.Run(() =>
            {
                lock (set.SaveLock)
@@ -491,6 +615,8 @@
                            //SaveImageByNameAndType(map, set.Id, set.ImageSaveOption.ImageFormat, imgDir);
                            string filePath = Path.Combine(imgDir, $"{set.Id}.tif");
                            set.HImage_2.WriteImage("tiff", 0, filePath);
                            set.HImage_2.Dispose();
                            set.HImage_2 = null;
                        }
                        catch (Exception ex)
                        {
@@ -521,11 +647,6 @@
                    if (set.ImageSaveOption.AddtionalSaveType.Contains(prefix) && !set.IsAddtionalSaved)
                    {
                        string imgDir = CheckImageDirectory(set.ImageSaveOption.ImageSaveSubDirectory, prefix);
                        while (set.Image == null)
                        {
                            Thread.Sleep(50);
                        }
                        try
                        {
@@ -562,10 +683,10 @@
        public override void Dispose()
        {
            base.Dispose();
            //HImage_2?.Dispose();
            //HImage_2 = null;
            HImage_2?.Dispose();
            HImage_2 = null;
            base.Dispose();
        }
    }
}