CodeManager.cs
28.2 KB
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Windows.Forms;
using CodeLibrary;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
using HalconDotNet;
using System.Web;
namespace DeviceLibrary
{
public class CodeManager
{
public static string CodeType = Setting_Init.Camera_CodeType;
private static int QRCodeCount = Setting_Init.Camera_QRCodeCount;
private static int CodeTimeOut = Setting_Init.Camera_CodeTimeOut;
public static List<string> cameraNameList = new List<string>();
public static List<string> codeTypeList = new List<string>();
public static List<string> hikNameList = new List<string>();
public static event EventHandler<Bitmap> camera_event;
private static char spiltChar = '#';
/// <summary>
/// 初始化摄像机名称和二维码类型
/// </summary>
public static void LoadConfig()
{
ConfigHelper.Config.Set("CamTestReel_Test", "Click To Test");
ConfigHelper.AdvanceConfigForm.AddCustomEditor<CameraTest>("CamTestReel_Test");
codeTypeList = new List<string>();
HDLogUtil.LogName = "RollingLogFileAppender";
try
{
LoadCamera(true);
codeTypeList = new List<string>();
string[] codeArray = CodeType.Split(spiltChar);
foreach (string str in codeArray)
{
if (str.Trim().Equals(""))
{
continue;
}
string file = GetCodeParamFilePath(str.Trim());
LogUtil.info("加载到配置二维码类型:" + str.Trim() + ",配置文件:" + file);
codeTypeList.Add(str.Trim());
}
CodeLibrary.HDCodeLearnHelper.LoadConfig("", CodeType);
//如果未加载到配置相机,自动配置
if (cameraNameList.Count <= 0 && hikNameList.Count > 0)
{
cameraNameList = new List<string>(hikNameList);
}
}
catch (Exception ex)
{
LogUtil.error("解析摄像机配置出错:" + ex.StackTrace);
}
}
public static void LoadCamera(bool isReLoad)
{
if (isReLoad || Camera._cam == null)
{
try
{
if (Camera._cam != null)
{
Camera._cam.CloseAll();
}
Camera.Type = CameraType.HIK;
Camera._cam.Load();
}
catch (Exception ex)
{
LogUtil.error("加载HIK相机出错:" + ex.ToString());
}
}
string[] names = Camera._cam.Name;
if (names != null)
{
foreach (string n in names)
{
if (!hikNameList.Contains(n))
{
hikNameList.Add(n);
}
}
// hikNameList.AddRange(names);
foreach (string name in hikNameList)
{
LogUtil.info("加载到HIK相机:" + name);
}
}
}
public static void CloseCamera(string cameraName)
{
Camera._cam.Close(cameraName);
}
public static void CloseAllCamera()
{
Camera._cam.CloseAll();
}
[HandleProcessCorruptedStateExceptions]
public static List<CodeInfo> CameraScan(List<string> cameraNameList)
{
HashSet<string> codestr = new HashSet<string>();
List<CodeInfo> codeList = new List<CodeInfo>();
string bitmapfilename = "";
if (cameraNameList == null || cameraNameList.Count <= 0)
{
throw new Exception("CameraScan方法没有传入相机名称.");
}
try
{
Task[] cameraTask = new Task[cameraNameList.Count()];
for (int ii = 0; ii < cameraNameList.Count(); ii++)
{
var cameraName = cameraNameList[ii];
var idx = ii;
cameraTask[ii] = Task.Run(new Action(() =>
{
int retrytime = 0;
retry:
LogUtil.info($"【" + cameraName + "】开始取图片");
if (cameraName.Trim().Equals(""))
{
return;
}
DateTime startTime = DateTime.Now;
HalconDotNet.HObject ho_Image = null;
Bitmap bmp = null;
try
{
bool nohalcon = true;
ho_Image = Camera._cam.CaptureOnImage(cameraName, out bmp, nohalcon);
if (bmp == null)
{
if (retrytime > 2)
return;
retrytime++;
LoadCamera(true);
LogUtil.info($"bitmap为空重试第{retrytime}次");
Task.Delay(1500).Wait();
goto retry;
}
//HalconDotNet.HOperatorSet.RotateImage()
if (ho_Image == null && !nohalcon)
{
LogUtil.error(" 【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
LoadCamera(true);
return;
}
if (idx == 0)
camera_event?.Invoke(null, bmp);
LogUtil.info(" 【" + cameraName + "】取图片完成,开始扫码");
string r = "";
RemoteDecodeHelper.RemoteDecodeParam remoteDecodeParam = new RemoteDecodeHelper.RemoteDecodeParam
{
codeTypeList = codeTypeList.ToArray(),
codeCount = QRCodeCount,
timeout = CodeTimeOut
};
List<CodeInfo> cc = new List<CodeInfo>();
cc = RemoteDecodeHelper.DecodeRequest(bmp, remoteDecodeParam);
if (cc != null && cc.Count > 0)
{
lock (codeList)
{
cc.ForEach((c) =>
{
//c.CodeStr = CodeManager.ReplaceCode(c.CodeStr);
c.CodeStr = c.CodeStr.Trim();
if (!codestr.Contains(c.CodeStr))
{
codeList.Add(c);
codestr.Add(c.CodeStr);
r += "##" + c.CodeStr;
}
});
}
}
else
{
bitmapfilename = SaveImageToFile("mimo", cameraName, bmp);
}
LogUtil.info(" 【" + cameraName + "】" + " 扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】 :" + r);
}
catch (AccessViolationException e)
{
LogUtil.error(" 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
Camera._cam.Close(cameraName);
// GC.Collect();
}
catch (Exception ex)
{
LogUtil.error(" 扫码出错:" + ex.ToString());
}
finally
{
if (ho_Image != null)
{
ho_Image.Dispose();
}
if (bmp != null)
bmp.Dispose();
}
}));
Task.Delay(ii * 700).Wait();
}
while (!cameraTask[0].IsCompleted || !cameraTask[1].IsCompleted)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
catch (AccessViolationException e)
{
LogUtil.error(" 扫码出现AccessViolationException异常:" + e.ToString());
//throw new Exception("扫码出现AccessViolationException异常");
// GC.Collect();
}
catch (Exception ex)
{
LogUtil.error(" 扫码出错:" + ex.ToString());
//throw new Exception("扫码出错");
}
return codeList;
}
static bool lastHasReel = false;
public static bool? TestHasRight = null;
static object testLocObj = new object();
[HandleProcessCorruptedStateExceptions]
public static bool? TestHasReel(string cameraName, out string srcimg, out string prcimg)
{
srcimg = "";
prcimg = "";
int retrytime = 0;
if (Monitor.TryEnter(testLocObj))
{
try
{
retry:
string logtxt = $"【" + cameraName + "】开始取图片测试是否有料盘" + "\r\n";
DateTime startTime = DateTime.Now;
Bitmap bmp = null;
bool usebarcode = Setting_Init.CamTestReel_useBarcode;
if (usebarcode)
{
try
{
//bmp = new Bitmap(@"D:\logs\10-30-51-138.bmp");
bmp = Camera._cam.GrabOne(cameraName);
if (bmp == null)
{
if (retrytime > 2)
return null;
retrytime++;
Camera._cam.Close(cameraName);
//LoadCamera(true);
LogUtil.info($"bitmap为空重试第{retrytime}次");
Thread.Sleep(2000);
goto retry;
}
logtxt += $"【" + cameraName + "】获取到图像" + "\r\n";
string code = Setting_Init.CamTestReel_barcode;
int codeThreshold = Setting_Init.CamTestReel_barcodeThreshold;
//if (ConfigHelper.Config.Get("CamTestReel_debug", false))
// srcimg = SaveImageToFile("test", cameraName, bmp);
bool hasReel = false;
RemoteDecodeHelper.RemoteDecodeParam remoteDecodeParam = new RemoteDecodeHelper.RemoteDecodeParam
{
codeTypeList = codeTypeList.ToArray(),
codeCount = QRCodeCount,
timeout = CodeTimeOut
};
List<CodeInfo> cc = RemoteDecodeHelper.DecodeRequest(bmp, remoteDecodeParam);
int count = 0;
if (cc == null) hasReel = true;
else
{
var res = cc.FindAll(s => code.Equals(s.CodeStr));
count = res.Count();
if (res == null || count < codeThreshold)
{
hasReel = true;
}
}
string r = "";
if (cc != null && cc.Count > 0)
{
cc.ForEach((c) =>
{
c.CodeStr = CodeManager.ReplaceCode(c.CodeStr);
r += "#" + c.CodeStr;
});
}
logtxt += $" 一维码扫描结果:{count}[{r}],设置可扫描到条码数量:{codeThreshold},result:{((count < codeThreshold) ? "有料" : "无料")}\r\n";
if (hasReel != lastHasReel)
{
lastHasReel = hasReel;
}
else if (!Setting_Init.CamTestReel_debug)
logtxt = "";
if (Setting_Init.CamTestReel_debug || (TestHasRight.HasValue && TestHasRight.Value != hasReel))
prcimg = SaveImageToFile("test2", cameraName, bmp);
TestHasRight = null;
return hasReel;
}
catch (AccessViolationException e)
{
LogUtil.error(" 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
Camera._cam.Close(cameraName);
return null;
}
catch (Exception ex)
{
LogUtil.error(" 扫码出错:" + ex.ToString());
return null;
}
finally
{
if (bmp != null)
bmp.Dispose();
if (!string.IsNullOrEmpty(logtxt))
LogUtil.info(logtxt);
}
}
else
{
try
{
//bmp = new Bitmap(@"D:\logs\10-30-51-138.bmp");
bmp = Camera._cam.GrabOneImage(cameraName, PixelType.RGB8);
if (bmp == null)
{
if (retrytime > 2)
return null;
retrytime++;
Camera._cam.Close(cameraName);
//LoadCamera(true);
LogUtil.info($"bitmap为空重试第{retrytime}次");
Thread.Sleep(2000);
goto retry;
}
logtxt += $"【" + cameraName + "】获取到图像" + "\r\n";
int totalcover = Setting_Init.CamTestReel_totalcover;
int hl = Setting_Init.CamTestReel_HL;
int hh = Setting_Init.CamTestReel_HH;
int ll = Setting_Init.CamTestReel_LL;
int lh = Setting_Init.CamTestReel_LH;
int sl = Setting_Init.CamTestReel_SL;
int sh = Setting_Init.CamTestReel_SH;
double threshold = Setting_Init.CamTestReel_threshold;
if (Setting_Init.CamTestReel_debug)
srcimg = SaveImageToFile("test", cameraName, bmp);
var b = new Bitmap(bmp.Width / 2, bmp.Height / 2, bmp.PixelFormat);
using (var g = Graphics.FromImage(b))
{
g.InterpolationMode = InterpolationMode.Low;
g.DrawImage(bmp, 0, 0, b.Width, b.Height);
}
ImageLockMode imageLockMode = ImageLockMode.ReadOnly;
if (Setting_Init.CamTestReel_debug)
imageLockMode = ImageLockMode.ReadWrite;
var bd = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), imageLockMode, b.PixelFormat);
var rois = TestRoi.GetRois();
if (rois == null || rois.Count == 0)
{
rois = new List<TestRoi>() { new TestRoi() };
rois[0].CoverCount = totalcover;
rois[0].RoiPath.Add(new Point(0, 0));
rois[0].RoiPath.Add(new Point(bmp.Width, 0));
rois[0].RoiPath.Add(new Point(bmp.Width, bmp.Height));
rois[0].RoiPath.Add(new Point(0, bmp.Height));
}
bool hasReel = false;
for (int i = 0; i < rois.Count; i++)
{
//rois[i].CoverCount = totalcover;
double maskcout = 0;
var roi = rois[i];
var rp = roi.RoiPath.Select(r => new Point(r.X / 2, r.Y / 2)).ToList();
var fp = GetFilledPoints(rp);
var nfp = fp.Where(f => IsPointInPath(f.X, f.Y, rp)).ToList();
foreach (var xy in nfp)
{
int x = (xy.Y * bd.Width + xy.X) * 3;
//Marshal.WriteByte(bd.Scan0, x, 0);
//Marshal.WriteByte(bd.Scan0, x + 1, 0);
//Marshal.WriteByte(bd.Scan0, x + 2, 255);
var cr = (int)Marshal.ReadByte(bd.Scan0, x + 2);
var cg = (int)Marshal.ReadByte(bd.Scan0, x + 1);
var cb = (int)Marshal.ReadByte(bd.Scan0, x);
var h = ColorHelper.RgbToHsv(new ColorRGB(cr, cg, cb));
if (h.H >= hl && h.H <= hh && h.V >= ll && h.V <= lh && h.S >= sl && h.S <= sh)
{
maskcout++;
if (Setting_Init.CamTestReel_debug)
{
Marshal.WriteByte(bd.Scan0, x, 0);
Marshal.WriteByte(bd.Scan0, x + 1, 0);
Marshal.WriteByte(bd.Scan0, x + 2, 255);
}
}
}
double calc = maskcout / (double)roi.CoverCount;
logtxt += $" 检测到Roi[{i}]覆盖面积计数:maskcout:{maskcout}/{roi.CoverCount}={calc}<{threshold},result:{(calc <= threshold ? "有料" : "无料")}\r\n";
if (calc <= threshold)
{
hasReel = true;
break;
}
}
/*
for (int x = 0; x < b.Width * b.Height * 3; x = x + 3)
{
var cr = (int)Marshal.ReadByte(bd.Scan0, x + 2);
var cg = (int)Marshal.ReadByte(bd.Scan0, x + 1);
var cb = (int)Marshal.ReadByte(bd.Scan0, x);
var h = ColorHelper.RgbToHsv(new ColorRGB(cr, cg, cb));
if (h.H >= hl && h.H <= hh && h.V >= ll && h.V <= lh && h.S >= sl && h.S <= sh)
{
maskcout++;
if (ConfigHelper.Config.Get("CamTestReel_debug", false))
{
Marshal.WriteByte(bd.Scan0, x, 0);
Marshal.WriteByte(bd.Scan0, x + 1, 0);
Marshal.WriteByte(bd.Scan0, x + 2, 255);
}
}
}*/
b.UnlockBits(bd);
if (hasReel != lastHasReel)
{
lastHasReel = hasReel;
}
else if (!Setting_Init.CamTestReel_debug)
logtxt = "";
if (Setting_Init.CamTestReel_debug || (TestHasRight.HasValue && TestHasRight.Value != hasReel))
prcimg = SaveImageToFile("test2", cameraName, b);
b.Dispose();
TestHasRight = null;
return hasReel;
}
catch (AccessViolationException e)
{
LogUtil.error(" 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
Camera._cam.Close(cameraName);
return null;
}
catch (Exception ex)
{
LogUtil.error(" 扫码出错:" + ex.ToString());
return null;
}
finally
{
if (bmp != null)
bmp.Dispose();
if (!string.IsNullOrEmpty(logtxt))
LogUtil.info(logtxt);
}
}
}
finally
{
Monitor.Exit(testLocObj);
}
}
else
return null;
}
/// <summary>
///
/// </summary>
/// <param name="imgWidth"></param>
/// <param name="imgHeight"></param>
/// <param name="pX"></param>
/// <param name="pY"></param>
/// <returns>x,y</returns>
static (int, int) PointRoate270(int imgWidth, int imgHeight, int pX, int pY)
{
int x = pY;
int y = imgWidth - pX;
return (x, y);
}
private static string SaveImageToFile(string deviceName, string cameraName, Bitmap bitmap)
{
string date = DateTime.Now.ToString("HH-mm-ss-") + DateTime.Now.Millisecond;
string dire = @"\image\" + deviceName.Trim().Replace('_', '-') + @"\" + cameraName.Trim().Replace('_', '-').Replace(':', '-') + @"\";
string iamgeName = date + ".bmp";
try
{
if (Directory.Exists(dire).Equals(false))
{
Directory.CreateDirectory(dire);
}
bitmap.Save(dire + iamgeName, ImageFormat.Bmp);
//bitmap.Dispose();
LogUtil.info(deviceName + " 【" + cameraName + "】扫码完成,保存图片到【" + dire + iamgeName + "】成功");
}
catch (Exception ex)
{
LogUtil.error("保存" + deviceName + " 【" + cameraName + "】的图片到【" + dire + iamgeName + "】出错" + ex.ToString());
}
return dire + iamgeName;
}
/// <summary>
/// 处理接收后的二维码
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public static string ReplaceCode(string message)
{
message = message.Trim();
message = message.Replace("\r", "");
message = message.Replace("\n", "");
char a = (char)02;
message = message.Replace(a.ToString(), "");
message = message.Trim();
if (!HasChinese(message))
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] bytes = asciiEncoding.GetBytes(message);
List<byte> newBytes = new List<byte>();
foreach (byte by in bytes)
{
int value = (int)by;
if (value.Equals(24) || value.Equals(30) || value.Equals(29) || value.Equals(4))
{
continue;
}
if (!value.Equals(24))
{
newBytes.Add(by);
}
}
message = asciiEncoding.GetString(newBytes.ToArray());
}
return message;
}
public static bool HasChinese(string str)
{
return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
}
public static string GetCodeParamFilePath(string codePath)
{
string appPath = Application.StartupPath;
string path = Path.Combine(appPath, Setting_Init.Camera_CodeParamPath);
string filePath = Path.Combine(path, codePath + ".dcm");
if (File.Exists(filePath))
{
return filePath;
}
else
{
return "";
}
}
private static List<Point> GetFilledPoints(List<Point> points)
{
List<Point> filledPoints = new List<Point>();
// 获取路径的边界框
int minX = int.MaxValue;
int minY = int.MaxValue;
int maxX = int.MinValue;
int maxY = int.MinValue;
foreach (Point point in points)
{
if (point.X < minX)
{
minX = point.X;
}
if (point.Y < minY)
{
minY = point.Y;
}
if (point.X > maxX)
{
maxX = point.X;
}
if (point.Y > maxY)
{
maxY = point.Y;
}
}
// 遍历边界框内的每个像素点
for (int y = minY; y <= maxY; y++)
{
for (int x = minX; x <= maxX; x++)
{
if (IsPointInPath(x, y, points))
{
filledPoints.Add(new Point(x, y));
}
}
}
return filledPoints;
}
private static bool IsPointInPath(int x, int y, List<Point> points)
{
bool inside = false;
for (int i = 0, j = points.Count - 1; i < points.Count; j = i++)
{
if (((points[i].Y > y) != (points[j].Y > y)) &&
(x < (points[j].X - points[i].X) * (y - points[i].Y) / (points[j].Y - points[i].Y) + points[i].X))
{
inside = !inside;
}
}
return inside;
}
}
}