CodeManager.cs
15.9 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
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;
namespace DeviceLibrary
{
public class CodeManager
{
public static string CodeType = Setting_Init.CameraScan_CodeType;
private static int QRCodeCount = Setting_Init.CameraScan_QRCodeCount;
private static int CodeTimeOut = Setting_Init.CameraScan_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()
{
string nameStr = Setting_Init.CameraScan_CameraName;
codeTypeList = new List<string>();
HDLogUtil.LogName = "RollingLogFileAppender";
try
{
string[] nameArray = nameStr.Split(spiltChar);
foreach (string str in nameArray)
{
if (str.Trim().Equals(""))
{
continue;
}
//LogUtil.info("加载到配置摄像机名称:" + str.Trim());
cameraNameList.Add(str.Trim());
}
LoadCamera(false);
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);
string cameraStr = "";
foreach (string name in hikNameList)
{
cameraStr += name + spiltChar;
}
cameraStr = cameraStr.Substring(0, cameraStr.Length - 1);
//ConfigAppSettings.SaveValue(Setting_Init.CameraName, cameraStr);
LogUtil.info("未配置扫码相机,默认【" + Setting_Init.CameraScan_CameraName + "】=【" + cameraStr + "】");
}
}
catch (Exception ex)
{
LogUtil.error("解析摄像机配置出错:" + ex.StackTrace);
}
}
/// <summary>
/// 初始化摄像机名称和二维码类型
/// </summary>
public static bool LoadSingle()
{
codeTypeList = new List<string>();
HDLogUtil.LogName = "RollingLogFileAppender";
try
{
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);
LoadCamera(false);
//如果未加载到配置相机,自动配置
if (hikNameList.Count > 0)
{
cameraNameList = new List<string>(hikNameList);
string cameraStr = "";
foreach (string name in hikNameList)
{
cameraStr += name + spiltChar;
}
cameraStr = cameraStr.Substring(0, cameraStr.Length - 1);
//ConfigAppSettings.SaveValue(Setting_Init.CameraName, cameraStr);
LogUtil.info("未配置扫码相机,默认【" + Setting_Init.CameraScan_CameraName + "】=【" + cameraStr + "】");
return true;
}
return false;
}
catch (Exception ex)
{
LogUtil.error("解析摄像机配置出错:" + ex.StackTrace);
}
return false;
}
private 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++;
CloseCamera(cameraName);
LogUtil.info($"bitmap为空重试第{retrytime}次");
Task.Delay(1500).Wait();
goto retry;
}
//HalconDotNet.HOperatorSet.RotateImage()
if (ho_Image == null && !nohalcon)
{
LogUtil.error(" 【" + cameraName + "】取图片失败[" + Camera._cam.ErrInfo + "],关闭相机");
CloseCamera(cameraName);
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)
{
lock (codeList)
{
cc.ForEach((c) =>
{
c.CodeStr = CodeManager.ReplaceCode(c.CodeStr);
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;
}
/// <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.CameraScan_CodeParamPath);
string filePath = Path.Combine(path, codePath + ".dcm");
if (File.Exists(filePath))
{
return filePath;
}
else
{
return "";
}
}
}
}