CodeManager.cs
26.5 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
using AGVLib;
using CodeLibrary;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OnlineStore.DeviceLibrary
{
public class CodeManager
{
public static List<string> codeTypeList = new List<string>();
public static List<string> balserNameList = new List<string>();
public static List<string> hikNameList = new List<string>();
private static int QRCodeCount = ConfigAppSettings.GetIntValue(Setting_Init.QRCodeCount);
private static char spiltChar = '#';
/// <summary>
/// 初始化摄像机名称和二维码类型
/// </summary>
public static void LoadConfig()
{
string codeStr = ConfigAppSettings.GetValue(Setting_Init.CodeType, "Data Matrix ECC 200#QR Code");
codeTypeList = new List<string>();
HDLogUtil.LogName = "RollingLogFileAppender";
try
{
string[] codeArray = codeStr.Split(spiltChar);
foreach (string str in codeArray)
{
if (str.Trim().Equals(""))
{
continue;
}
LogUtil.info("加载到配置二维码类型:" + str.Trim());
codeTypeList.Add(str.Trim());
}
LoadCamera(false);
CodeLibrary.HDCodeLearnHelper.LoadConfig("", codeStr);
//CodeLibrary.EyemDecode.InitModel();
}
catch (Exception ex)
{
LogUtil.error("解析摄像机配置出错:", ex);
}
}
private static void LoadCamera(bool isReLoad)
{
string[] names = null;
if (isReLoad || Camera._cam == null)
{
try
{
if (Camera._cam != null)
{
Camera._cam.CloseAll();
}
Camera.Type = CameraType.HIK;
Camera._cam.Load();
names = Camera._cam.Name;
}
catch (Exception ex)
{
LogUtil.error("加载HIK相机出错:", ex);
}
}
//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();
}
public static List<string> CameraScan(string cameraName, string deviceName, bool findRightCodeBreak = false, int timeOut = 1500)
{
List<string> nameList = new List<string>() { cameraName };
return CameraScan(nameList, deviceName, findRightCodeBreak, timeOut);
}
private static int ScanCount = 0;
private static int codeCount = ConfigAppSettings.GetIntValue(Setting_Init.CodeCount, 3);
private static int codeTimeout = ConfigAppSettings.GetIntValue(Setting_Init.ScanCodeTimeout, 3000);
[HandleProcessCorruptedStateExceptions]
static List<string> CameraScan(List<string> cameraList, string deviceName, bool findRightCodeBreak = false, int timeOut = 1500)
{
bool isPreScan = deviceName.EndsWith("预扫码");
isPreScan = false;
List<string> codeList = new List<string>();
if (cameraList == null || cameraList.Count <= 0)
{
return codeList;
}
try
{
foreach (string cameraName in cameraList)
{
if (cameraName.Trim().Equals(""))
{
continue;
}
ScanCount++;
DateTime startTime = DateTime.Now;
if (deviceName != "")
{
LogUtil.info(deviceName + " 【" + cameraName + "】开始取图片");
}
Bitmap bmp = null;
HalconDotNet.HObject ho_Image = null;
bool findRightCode = false;
try
{
ho_Image = Camera._cam.CaptureOnImage(cameraName, out bmp);
if (ho_Image == null)
{
LogUtil.error(deviceName + " 【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
CloseCamera(cameraName);
LoadCamera(true);
continue;
}
LogUtil.info(deviceName + " 【" + cameraName + "】取图片完成,开始扫码");
string r = "";
if (!isPreScan)
{
try
{
List<CodeInfo> cc = new List<CodeInfo>();
RemoteDecodeHelper.RemoteDecodeParam remoteDecodeParam = new RemoteDecodeHelper.RemoteDecodeParam
{
codeTypeList = codeTypeList.ToArray(),
codeCount = codeCount,
timeout = codeTimeout
};
cc = RemoteDecodeHelper.DecodeRequest(ho_Image, remoteDecodeParam);
if (cc != null)
{
foreach (CodeInfo c in cc)
{
string str = CodeManager.ReplaceCode(c.CodeStr);
if (!codeList.Contains(str))
{
codeList.Add(str);
r = r + "##remote|" + c.CodeType + "|" + str;
if (!findRightCode)
{
findRightCode = HasRightCode(str);
}
}
}
}
}
catch (Exception ex)
{
LogUtil.error(deviceName + " RemoteDecodeHelper扫码出错:" + ex.ToString());
}
}
LogUtil.info(deviceName + " 【" + cameraName + "】扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】[" + findRightCode + "]" + ScanCount + " :" + r);
if (!findRightCode)
{
SaveNGImageToFile(deviceName, cameraName, bmp);
}
else
{
SaveOKImageToFile(deviceName, cameraName, bmp);
}
}
catch (AccessViolationException e)
{
LogUtil.error(deviceName + " 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
Camera._cam.Close(cameraName);
LoadCamera(true);
// GC.Collect();
}
catch (Exception ex)
{
LogUtil.error(deviceName + " 扫码出错:" + ex.ToString());
}
finally
{
if (ho_Image != null)
{
ho_Image.Dispose();
ho_Image = null;
}
// GC.Collect();
Task.Delay(10);
}
}
}
catch (AccessViolationException e)
{
LogUtil.error(deviceName + " 扫码出现AccessViolationException异常,关闭所有相机:" + e.ToString());
Camera._cam.CloseAll();
//GC.Collect();
}
catch (Exception ex)
{
LogUtil.error(deviceName + " 扫码出错:" + ex.ToString());
}
return codeList;
}
/// <summary>
/// 贴标扫码相机使用
/// </summary>
/// <param name="cameraNameList"></param>
/// <returns>(二维码信息,图片路径)</returns>
/// <exception cref="Exception"></exception>
[HandleProcessCorruptedStateExceptions]
public static (List<CodeInfo>, string) CameraScan(List<string> cameraNameList)
{
List<CodeInfo> codeList = new List<CodeInfo>();
string bitmapfilename = "";
if (cameraNameList == null || cameraNameList.Count <= 0)
{
throw new Exception("CameraScan方法没有传入相机名称.");
}
try
{
for (int i = 0; i < cameraNameList.Count(); i++)
{
var cameraName = cameraNameList[i];
if (cameraName.Trim().Equals(""))
{
continue;
}
DateTime startTime = DateTime.Now;
LogUtil.info(" 【" + cameraName + "】开始取图片");
HalconDotNet.HObject ho_Image = null;
Bitmap bmp = null;
try
{
bool nohalcon = false;
ho_Image = Camera._cam.CaptureOnImage(cameraName, out bmp, nohalcon);
//HalconDotNet.HOperatorSet.RotateImage()
if (ho_Image == null && !nohalcon)
{
LogUtil.error(" 【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
CloseCamera(cameraName);
LoadCamera(true);
continue;
}
LogUtil.info(" 【" + cameraName + "】取图片完成,开始扫码");
string r = "";
//bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
//List<CodeInfo> tlci = EyemDecode2.Decoder(ref bmp);
//foreach (CodeInfo code in tlci)
//{
// LogUtil.info(" 【" + cameraName + "】[eyemDecode]" + code.CodeType + "(X: " + code.X + ",Y: " + code.Y + ") " + code.CodeStr);
// //string str = CodeManager.ReplaceCode(code.CodeStr);
// lock (codeList)
// {
// if (!codeList.Contains(code))
// {
// codeList.Add(code);
// r = r + "##" + code.CodeStr;
// }
// }
//}
List<CodeInfo> cc = new List<CodeInfo>();
RemoteDecodeHelper.RemoteDecodeParam remoteDecodeParam = new RemoteDecodeHelper.RemoteDecodeParam
{
codeTypeList = codeTypeList.ToArray(),
codeCount = codeCount,
timeout = codeTimeout
};
cc = RemoteDecodeHelper.DecodeRequest(ho_Image, remoteDecodeParam);
if (cc != null)
{
foreach (CodeInfo c in cc)
{
c.CodeStr = CodeManager.ReplaceCode(c.CodeStr);
if (!codeList.Contains(c))
{
codeList.Add(c);
// r = r + "##halcon|" + c.CodeType + "|" + c.CodeStr;
LogUtil.info(" 【" + cameraName + "】[remote]" + c.CodeType + "(X: " + c.X + ",Y: " + c.Y + ") " + c.CodeStr);
//if (!findRightCode)
//{
// findRightCode = HasRightCode(c.CodeStr);
//}
}
}
}
//foreach (string codeType in codeTypeList)
//{
// //判断是否是一维码
// if (codeType.ToLower().Equals("barcode"))
// {
// cc = HDCodeHelper.DecodeBarCode(ho_Image);
// }
// else
// {
// cc = HDCodeHelper.DecodeCode(ho_Image, codeType, GetCodeParamFilePath(codeType), QRCodeCount, 3000);
// cc.ForEach((x) => { x.CodeType = codeType; });
// }
// LogUtil.info(" 【" + cameraName + "】[Halcon]" + codeType + "," + QRCodeCount + "," + cc.Count);
// foreach (CodeInfo c in cc)
// {
// LogUtil.info(" 【" + cameraName + "】[Halcon]" + c.CodeType + "(X: " + c.X + ",Y: " + c.Y + ") " + c.CodeStr);
// c.CodeStr = CodeManager.ReplaceCode(c.CodeStr);
// lock (codeList)
// {
// if (!codeList.Contains(c))
// {
// codeList.Add(c);
// r = r + "##" + c.CodeStr;
// }
// }
// }
//}
//if (codeList.Count() == 0)
//{
bitmapfilename = SaveOKImageToFile("XLRClient", cameraName, bmp);
// }
LogUtil.info(" 【" + cameraName + "】" + " 扫码完成【" + FormUtil.GetSpanStr(DateTime.Now - startTime) + "】 :" + r);
}
catch (AccessViolationException e)
{
LogUtil.error(" 扫码出现AccessViolationException异常,关闭相机【" + cameraName + "】:" + e.ToString());
Camera._cam.Close(cameraName);
LoadCamera(true);
// GC.Collect();
}
catch (Exception ex)
{
LogUtil.error(" 扫码出错:" + ex.ToString());
}
finally
{
if (ho_Image != null)
{
ho_Image.Dispose();
}
if (bmp != null)
bmp.Dispose();
}
}
}
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, bitmapfilename);
}
static int CntImgs = ConfigAppSettings.GetIntValue("SaveImgCnt", 100);
private static string SaveNGImageToFile(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(':', '-') + @"\NG\";
string iamgeName = date + ".bmp";
try
{
if (Directory.Exists(dire).Equals(false))
{
Directory.CreateDirectory(dire);
}
Bitmap bit = (Bitmap)bitmap.Clone();
//deleteFiles(dire);
bit.Save(dire + iamgeName, ImageFormat.Bmp);
bit.Dispose();
LogUtil.info(deviceName + " 【" + cameraName + "】保存NG图片到【" + dire + iamgeName + "】成功");
}
catch (Exception ex)
{
LogUtil.error("保存" + deviceName + " 【" + cameraName + "】NG图片到【" + dire + iamgeName + "】出错" + ex.ToString());
}
return dire + iamgeName;
}
private static string SaveOKImageToFile(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(':', '-') + @"\OK\";
string iamgeName = date + ".bmp";
try
{
if (Directory.Exists(dire).Equals(false))
{
Directory.CreateDirectory(dire);
}
using (Bitmap bit = (Bitmap)bitmap.Clone())
{
deleteFiles(dire);
bit.Save(dire + iamgeName, ImageFormat.Bmp);
// bit.Dispose();
}
LogUtil.info(deviceName + " 【" + cameraName + "】保存OK图片到【" + dire + iamgeName + "】成功");
}
catch (Exception ex)
{
LogUtil.error("保存" + deviceName + " 【" + cameraName + "】OK图片到【" + dire + iamgeName + "】出错" + ex.ToString());
}
return dire + iamgeName;
}
static void deleteFiles(string dire)
{
try
{
string[] imgFiles = Directory.GetFiles(dire);
if (imgFiles.Length <= CntImgs)
{
return;
}
FileInfo fileInfo;
List<FileInfo> files = new List<FileInfo>();
foreach (var item in imgFiles)
{
fileInfo = new FileInfo(item);
files.Add(fileInfo);
}
do
{
FileInfo oldFile = files[0];
foreach (var item in files)
{
if ((item.CreationTime - oldFile.CreationTime).TotalSeconds < 0)
{
oldFile = item;
}
}
oldFile?.Delete();
files.Remove(oldFile);
}
while (files.Count > CntImgs);
}
catch (Exception ex)
{
LogUtil.error("删除文件失败", ex);
}
}
public static void DelImg(string deviceName, string imgPath)
{
try
{
if (File.Exists(imgPath))
{
File.Delete(imgPath);
LogUtil.info(deviceName + "删除图片【" + imgPath + "】成功");
}
}
catch (Exception ex)
{
LogUtil.error("删除" + deviceName + "图片【" + imgPath + "】出错" + ex.ToString());
}
}
private static int SaveErrorImageToFile = ConfigAppSettings.GetIntValue(Setting_Init.SaveErrorImageToFile);
//private static void SaveImageToFile(string deviceName, string cameraName, HalconDotNet.HObject bitmap)
//{
// string date = deviceName.Trim().Replace('_', '-') + "-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0');
// string dire = @"D:\image\" + deviceName.Trim().Replace('_', '-') + @"\" + cameraName.Trim().Replace('_', '-').Replace(':', '-') + @"\";
// string imageName = date + ".bmp";
// try
// {
// if (!Directory.Exists(dire))
// {
// Directory.CreateDirectory(dire);
// }
// bitmap.WriteObject(dire + imageName);
// LogUtil.info(deviceName + " 【" + cameraName + "】扫码失败,保存图片到【" + dire + imageName + "】成功");
// }
// catch (Exception ex)
// {
// LogUtil.error("保存" + deviceName + " 【" + cameraName + "】的图片到【" + dire + imageName + "】出错" + ex.ToString());
// }
//}
//private static void SaveImageToFile(string deviceName, string cameraName, Bitmap bitmap)
//{
// string date = deviceName.Trim().Replace('_', '-') + "-" + DateTime.Now.ToString("yyyyMMdd-HHmmss-") + DateTime.Now.Millisecond;
// string dire = @"D:\image\" + deviceName.Trim().Replace('_', '-') + @"\" + cameraName.Trim().Replace('_', '-').Replace(':', '-') + @"\";
// string imageName = date + ".bmp";
// try
// {
// Bitmap bit = (Bitmap)bitmap.Clone();
// if (Directory.Exists(dire).Equals(false))
// {
// Directory.CreateDirectory(dire);
// }
// bit.Save(dire + imageName, ImageFormat.Bmp);
// LogUtil.info(deviceName + " 【" + cameraName + "】扫码失败,保存图片到【" + dire + imageName + "】成功");
// }
// catch (Exception ex)
// {
// LogUtil.error("保存" + deviceName + " 【" + cameraName + "】的图片到【" + dire + imageName + "】出错" + ex.ToString());
// }
//}
public static bool HasRightCode(params string[] codes)
{
//640104 * 3331001202 * 210417624 * 600 * 0011
//分号分割后长度=4,L,E,B,R
//138S00014-019494|QI6RT63-2227|15000|H130194944122001BS|SAMSUNG|##=7x8=QI6RT63/CL03A105MO3NRNH/0538/15000##
// RI & PN & QTY & 4 & BATCH & 5 & 6 & 7 & 8
// RI & PN & QTY & PRODATEyyyy - MM - dd & 5 & 6 & 7 & 8 & 9
try
{
foreach (string code in codes)
{
string[] strarray = code.Split('|');
if (strarray.Length >= 3)
{
try
{
if (!string.IsNullOrEmpty(strarray[3]))
{
return true;
}
int QTY = Convert.ToInt32(strarray[2].Trim());
if (QTY > 0)
{
return true;
}
}
catch (Exception ex)
{
return false;
}
}
}
}
catch (Exception ex)
{
}
return false;
}
static string codeParampath = ConfigAppSettings.GetValue(Setting_Init.CodeParamPath, "\\CodeParam\\");
public static string GetCodeParamFilePath(string codePath)
{
string appPath = Application.StartupPath;
string path = appPath + codeParampath;
string filePath = path + codePath + ".dcm";
if (File.Exists(filePath))
{
return filePath;
}
else
{
return "";
}
}
/// <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();
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 string ProcessCode(List<string> codeList)
{
string code = "";
foreach (string cc in codeList)
{
if (string.IsNullOrEmpty(cc))
{
continue;
}
code += cc + "##";
}
return ReplaceCode(code);
}
}
}