领胜LDS 键盘AOI检测项目
wells.liu
2020-07-01 dbae9c048fa0cd67c2e1161e5b6b693f87064154
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using HalconDotNet;
using MvCamCtrl.NET;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
 
namespace Bro.Device.HikCamera
{
    [Device("HikCamera", "海康相机", EnumHelper.DeviceAttributeType.Device)]
    public class HikCameraDriver : CameraBase
    {
        #region CameraBase
        public override IOperationConfig GetOperationConfigFromDevice()
        {
            HikCameraOperationConfig opConfig = new HikCameraOperationConfig();
 
            MyCamera.MVCC_FLOATVALUE stParam = new MyCamera.MVCC_FLOATVALUE();
            int nRet = device.MV_CC_GetFloatValue_NET("ExposureTime", ref stParam);
            if (MyCamera.MV_OK == nRet)
            {
                opConfig.Exposure = stParam.fCurValue;
            }
 
            nRet = device.MV_CC_GetFloatValue_NET("Gain", ref stParam);
            if (MyCamera.MV_OK == nRet)
            {
                opConfig.Gain = stParam.fCurValue;
            }
 
            return opConfig;
        }
 
        float _lastExposure = 0;
        float _lastGain = 0;
 
        public override void UploadOperationConfig(IOperationConfig config)
        {
            if (CurrentState != EnumHelper.DeviceState.DSOpen)
                return;
 
            CameraOprerationConfigBase opConfig = config as CameraOprerationConfigBase;
 
            int nRet;
 
            if (opConfig.Exposure != 0 && opConfig.Exposure != _lastExposure)
            {
                device.MV_CC_SetEnumValue_NET("ExposureAuto", 0);
                nRet = device.MV_CC_SetFloatValue_NET("ExposureTime", opConfig.Exposure);
                if (nRet != MyCamera.MV_OK)
                {
                    throw new Exception($"Exposure set failed:{nRet}");
                }
 
                _lastExposure = opConfig.Exposure;
            }
 
            if (opConfig.Gain != 0 && opConfig.Gain != _lastGain)
            {
                device.MV_CC_SetEnumValue_NET("GainAuto", 0);
                nRet = device.MV_CC_SetFloatValue_NET("Gain", opConfig.Gain);
                if (nRet != MyCamera.MV_OK)
                {
                    throw new Exception($"Gain set failed:{nRet}");
                }
 
                _lastGain = opConfig.Gain;
            }
        }
 
        protected override void Init()
        {
            stDevInfo.nTLayerType = MyCamera.MV_GIGE_DEVICE;
            MyCamera.MV_GIGE_DEVICE_INFO stGigEDev = new MyCamera.MV_GIGE_DEVICE_INFO();
            pCallBackFunc = new MyCamera.cbExceptiondelegate(cbExceptiondelegate);
 
            string strCurrentIp = IConfig.CameraIP;// ch:需要连接的相机ip(根据实际填充) 
 
            string strNetExport = IConfig.ComputerIP;   // ch:相机对应的网卡ip(根据实际填充) 
 
            var parts = strCurrentIp.Split('.');
            int nIp1 = Convert.ToInt32(parts[0]);
            int nIp2 = Convert.ToInt32(parts[1]);
            int nIp3 = Convert.ToInt32(parts[2]);
            int nIp4 = Convert.ToInt32(parts[3]);
            stGigEDev.nCurrentIp = (uint)((nIp1 << 24) | (nIp2 << 16) | (nIp3 << 8) | nIp4);
 
            parts = strNetExport.Split('.');
            nIp1 = Convert.ToInt32(parts[0]);
            nIp2 = Convert.ToInt32(parts[1]);
            nIp3 = Convert.ToInt32(parts[2]);
            nIp4 = Convert.ToInt32(parts[3]);
            stGigEDev.nNetExport = (uint)((nIp1 << 24) | (nIp2 << 16) | (nIp3 << 8) | nIp4);
 
            IntPtr stGigeInfoPtr = Marshal.AllocHGlobal(216);
            Marshal.StructureToPtr(stGigEDev, stGigeInfoPtr, false);
            stDevInfo.SpecialInfo.stGigEInfo = new Byte[540];
            Marshal.Copy(stGigeInfoPtr, stDevInfo.SpecialInfo.stGigEInfo, 0, 540);
        }
 
        protected override void Pause()
        {
        }
 
        protected override void Resume()
        {
        }
 
        protected override void Start()
        {
            base.Start();
 
            // ch:创建设备 | en: Create device
            nRet = device.MV_CC_CreateDevice_NET(ref stDevInfo);
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Create device failed:{nRet:x8}");
            }
 
            // ch:打开设备 | en:Open device
            nRet = device.MV_CC_OpenDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Open device failed:{nRet:x8}");
            }
 
 
            // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
            if (stDevInfo.nTLayerType == MyCamera.MV_GIGE_DEVICE)
            {
                int nPacketSize = device.MV_CC_GetOptimalPacketSize_NET();
                if (nPacketSize > 0)
                {
                    nRet = device.MV_CC_SetIntValue_NET("GevSCPSPacketSize", (uint)nPacketSize);
                    if (nRet != MyCamera.MV_OK)
                    {
                        Console.WriteLine("Warning: Set Packet Size failed {0:x8}", nRet);
                    }
                }
                else
                {
                    Console.WriteLine("Warning: Get Packet Size failed {0:x8}", nPacketSize);
                }
            }
 
            // ch:注册异常回调函数 | en:Register Exception Callback
            nRet = device.MV_CC_RegisterExceptionCallBack_NET(pCallBackFunc, IntPtr.Zero);
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Register expection callback failed:{nRet}");
            }
            GC.KeepAlive(pCallBackFunc);
 
            // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
            device.MV_CC_SetEnumValue_NET("AcquisitionMode", 2);// ch:工作在连续模式 | en:Acquisition On Continuous Mode
            if (IIConfig.IsContinueMode)
            {
                device.MV_CC_SetEnumValue_NET("TriggerMode", 0);    // ch:连续模式 | en:Continuous
 
                // ch:注册回调函数 | en:Register image callback
                ImageCallback = new MyCamera.cbOutputExdelegate(ImageCallbackFunc);
                nRet = device.MV_CC_RegisterImageCallBackEx_NET(ImageCallback, IntPtr.Zero);
                if (MyCamera.MV_OK != nRet)
                {
                    throw new Exception("Register image callback failed!");
                }
            }
            else
            {
                // ch:设置触发模式为off || en:set trigger mode as off
                nRet = device.MV_CC_SetEnumValue_NET("TriggerMode", 1);
                if (MyCamera.MV_OK != nRet)
                {
                    throw new Exception("Set TriggerMode failed!");
                }
 
                if (IIConfig.IsHardwareTrigger)
                {
                    // ch:触发源选择:0 - Line0; | en:Trigger source select:0 - Line0;
                    //           1 - Line1;
                    //           2 - Line2;
                    //           3 - Line3;
                    //           4 - Counter;
                    //           7 - Software;
                    nRet = device.MV_CC_SetEnumValue_NET("TriggerSource", 0);
                    if (MyCamera.MV_OK != nRet)
                    {
                        throw new Exception("Set Line0 Trigger failed!");
                    }
 
                    // ch:注册回调函数 | en:Register image callback
                    ImageCallback = new MyCamera.cbOutputExdelegate(ImageCallbackFunc);
                    nRet = device.MV_CC_RegisterImageCallBackEx_NET(ImageCallback, IntPtr.Zero);
                    if (MyCamera.MV_OK != nRet)
                    {
                        throw new Exception("Register image callback failed!");
                    }
                }
                else
                {
                    nRet = device.MV_CC_SetEnumValue_NET("TriggerSource", 7);
                    if (MyCamera.MV_OK != nRet)
                    {
                        throw new Exception("Set Software Trigger failed!");
                    }
                }
            }
            // ch:开启抓图 || en: start grab image
            nRet = device.MV_CC_StartGrabbing_NET();
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Start grabbing failed:{nRet:x8}");
            }
 
            IIConfig.PropertyChanged -= IIConfig_PropertyChanged;
            IIConfig.PropertyChanged += IIConfig_PropertyChanged;
        }
 
        private void IIConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsHardwareTrigger" && !IIConfig.IsContinueMode)
            {
                // ch:停止抓图 | en:Stop grab image
                nRet = device.MV_CC_StopGrabbing_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    throw new Exception($"Stop grabbing failed{nRet:x8}");
                }
 
                if (IIConfig.IsHardwareTrigger)
                {
                    // ch:触发源选择:0 - Line0; | en:Trigger source select:0 - Line0;
                    //           1 - Line1;
                    //           2 - Line2;
                    //           3 - Line3;
                    //           4 - Counter;
                    //           7 - Software;
                    nRet = device.MV_CC_SetEnumValue_NET("TriggerSource", 0);
                    if (MyCamera.MV_OK != nRet)
                    {
                        throw new Exception("Set Line0 Trigger failed!");
                    }
 
                    // ch:注册回调函数 | en:Register image callback
                    ImageCallback = new MyCamera.cbOutputExdelegate(ImageCallbackFunc);
                    nRet = device.MV_CC_RegisterImageCallBackEx_NET(ImageCallback, IntPtr.Zero);
                    if (MyCamera.MV_OK != nRet)
                    {
                        throw new Exception("Register image callback failed!");
                    }
                }
                else
                {
                    nRet = device.MV_CC_SetEnumValue_NET("TriggerSource", 7);
                    if (MyCamera.MV_OK != nRet)
                    {
                        throw new Exception("Set Software Trigger failed!");
                    }
                }
 
                // ch:开启抓图 || en: start grab image
                nRet = device.MV_CC_StartGrabbing_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    throw new Exception($"Start grabbing failed:{nRet:x8}");
                }
            }
        }
 
        protected override void Stop()
        {
            IIConfig.PropertyChanged -= IIConfig_PropertyChanged;
 
            base.Stop();
 
            // ch:停止抓图 | en:Stop grab image
            nRet = device.MV_CC_StopGrabbing_NET();
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Stop grabbing failed{nRet:x8}");
            }
 
            // ch:关闭设备 | en:Close device
            nRet = device.MV_CC_CloseDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Close device failed{nRet:x8}");
            }
 
            // ch:销毁设备 | en:Destroy device
            nRet = device.MV_CC_DestroyDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                throw new Exception($"Destroy device failed:{nRet:x8}");
            }
        }
        #endregion
 
        #region HikCamera    
        public MyCamera.cbOutputExdelegate ImageCallback;
        MyCamera.MV_FRAME_OUT _frame = new MyCamera.MV_FRAME_OUT();
        readonly ManualResetEvent _snapHandle = new ManualResetEvent(false);
        bool _snapFlag = false;
        void ImageCallbackFunc(IntPtr pData, ref MyCamera.MV_FRAME_OUT_INFO_EX pFrameInfo, IntPtr pUser)
        {
            if ((IIConfig.IsHardwareTrigger))
            {
                int nWidth = pFrameInfo.nWidth;
                int nHeight = pFrameInfo.nHeight;
 
                HImage hImage = new HImage();
                hImage.GenImage1((HTuple)"byte", nWidth, nHeight, pData);
 
                ImageSet set = new ImageSet
                {
                    HImage = hImage
                };
                set.ImageSaveOption.DataFrom(IConfig.ImageSaveOption);
                NewImageSet(set);
                OnHImageOutput?.BeginInvoke(this, hImage, set.Id, null, null);
 
                Generate8GrayImageByPointer(nWidth, nHeight, pData, set.Id);
            }
            else
            {
                if (_snapFlag)
                {
                    _snapFlag = false;
                    _frame = new MyCamera.MV_FRAME_OUT
                    {
                        stFrameInfo = pFrameInfo,
                        pBufAddr = pData
                    };
                    _snapHandle.Set();
                }
            }
        }
 
        public override void Snapshot()
        {
            MyCamera.MV_FRAME_OUT frameInfo = new MyCamera.MV_FRAME_OUT();
            nRet = MyCamera.MV_OK;
 
            if (!IIConfig.IsContinueMode)
            {
                // ch: 触发命令 || en: Trigger command
                nRet = device.MV_CC_SetCommandValue_NET("TriggerSoftware");
                if (MyCamera.MV_OK != nRet)
                {
                    throw new Exception($"相机拍照触发失败:{nRet}");
                }
 
                nRet = device.MV_CC_GetImageBuffer_NET(ref frameInfo, 1000);
                nRet = device.MV_CC_FreeImageBuffer_NET(ref frameInfo);
            }
            else
            {
                _snapHandle.Reset();
                _snapFlag = true;
                _snapHandle.WaitOne();
                //lock (_imgCallBackLock)
                {
                    frameInfo.stFrameInfo = _frame.stFrameInfo;
                    frameInfo.pBufAddr = _frame.pBufAddr;
                }
            }
 
            // ch:获取一帧图像 | en:Get one image
            if (MyCamera.MV_OK == nRet)
            {
                if (frameInfo.pBufAddr != IntPtr.Zero)
                {
                    if (nRet == MyCamera.MV_OK)
                    {
                        var pFrameInfo = frameInfo.stFrameInfo;
                        uint nWidth = pFrameInfo.nWidth;
                        uint nHeight = pFrameInfo.nHeight;
 
                        //HikToBitmap(pFrameInfo, frameInfo.pBufAddr);
                        Generate8GrayImageByPointer((int)nWidth, (int)nHeight, frameInfo.pBufAddr, "");
                    }
                }
            }
            else
            {
                throw new Exception($"Grap Image Failed:{nRet:x8}");
            }
        }
 
        public override IImageSet Snapshot(IOperationConfig config)
        {
            ImageSet set = new ImageSet();
            InitialImageSet(set, (config as CameraOprerationConfigBase).ImageSaveOption);
 
            MyCamera.MV_FRAME_OUT frameInfo = new MyCamera.MV_FRAME_OUT();
            nRet = MyCamera.MV_OK;
 
            if (!IIConfig.IsContinueMode)
            {
                // ch: 触发命令 || en: Trigger command
                nRet = device.MV_CC_SetCommandValue_NET("TriggerSoftware");
                if (MyCamera.MV_OK != nRet)
                {
                    throw new Exception($"相机拍照触发失败:{nRet}");
                }
 
                nRet = device.MV_CC_GetImageBuffer_NET(ref frameInfo, 500);
                nRet = device.MV_CC_FreeImageBuffer_NET(ref frameInfo);
            }
            else
            {
                _snapHandle.Reset();
                _snapFlag = true;
                _snapHandle.WaitOne();
                {
                    frameInfo.stFrameInfo = _frame.stFrameInfo;
                    frameInfo.pBufAddr = _frame.pBufAddr;
                }
            }
 
            // ch:获取一帧图像 | en:Get one image
            if (MyCamera.MV_OK == nRet)
            {
                if (frameInfo.pBufAddr != IntPtr.Zero)
                {
                    if (nRet == MyCamera.MV_OK)
                    {
                        var pFrameInfo = frameInfo.stFrameInfo;
                        uint nWidth = pFrameInfo.nWidth;
                        uint nHeight = pFrameInfo.nHeight;
 
                        HImage hImage = new HImage();
                        hImage.GenImage1("byte", pFrameInfo.nWidth, pFrameInfo.nHeight, frameInfo.pBufAddr);
 
                        set.HImage = hImage;
 
                        Generate8GrayImageByPointer((int)nWidth, (int)nHeight, frameInfo.pBufAddr, set.Id);
                        return set;
                    }
                }
            }
 
            throw new Exception($"Grap Image Failed:{nRet:x8}");
        }
 
        readonly MyCamera device = new MyCamera();
        MyCamera.MV_CC_DEVICE_INFO stDevInfo = new MyCamera.MV_CC_DEVICE_INFO();
        int nRet = MyCamera.MV_OK;
        MyCamera.cbExceptiondelegate pCallBackFunc;
 
        public HikCameraInitialConfig IIConfig
        {
            get => InitialConfig as HikCameraInitialConfig;
        }
 
        // ch:回调函数 | en:Callback function
        private void cbExceptiondelegate(uint nMsgType, IntPtr pUser)
        {
            if (nMsgType == MyCamera.MV_EXCEPTION_DEV_DISCONNECT)
            {
                Thread.Sleep(1000);
 
                Stop();
 
                if (CurrentState != EnumHelper.DeviceState.DSClose)
                {
                    int reTryTimes = 3;
                    do
                    {
                        try
                        {
                            Start();
                            reTryTimes = -1;
                        }
                        catch (Exception ex)
                        {
                            reTryTimes--;
 
                            if (reTryTimes > 0)
                            {
                                //OnLog?.Invoke(DateTime.Now, this, "重新连接相机异常\r\n" + ex.GetExceptionMessage());
                                LogAsync(DateTime.Now, "重新连接异常", ex.GetExceptionMessage());
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                    } while (reTryTimes > 0);
                }
            }
        }
        #endregion
    }
}