WebCallWork.cs
23.8 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
using Asa.FaceControl;
using BLL;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using Model;
using Newtonsoft.Json;
using SmartScan.Form;
using SmartScan.PlusSettingFrm;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.WebControls;
namespace SmartScan
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
internal class WebCallWork : IWeb
{
public WebCallWork()
{
}
public void CloseApp()
{
LogNet.log.Info("WebService CloseApp 接口被调用");
Common.frmMain.Invoke(new Action(() => { Common.frmMain.Close(); }));
}
public WebResultCamera WorkWithCamera()
{
LogNet.log.Info("WebService WorkWithCamera 接口被调用");
WebCodeAll[] msg = null;
Common.frmMain.Invoke(new Action(() => { msg = Common.frmMain.WebTouchWork(); }));
return new WebResultCamera() { Data = msg };
}
public delegate void GetCameraAi(Dictionary<string, string> content);
public static event GetCameraAi PrintAiing;
public WebResultCamera GetmacroKey()
{
var aa = BLLCommon.macroKey;
return new WebResultCamera { MacroKey = aa };
}
public WebResultCamera GetCamera()
{
//开灯
BLLCommon.lightSource.TurnOn();
Bitmap[] result = Camera.Capture();
Bitmap bmp;
var content = "";
//if (result.Length == 0) return null;
if (result.Length == 0)
{
// 当没有捕获到图像时,从本地加载默认图像
string defaultImagePath = "C:\\Users\\HY\\Desktop\\ocrt.jpg"; // 替换为你的默认图像路径
content = PaddleOCRHelper.StartCplusOcr(defaultImagePath);
//string res = PaddleOCRHelper.StartPythonOcr(defaultImagePath);
if (File.Exists(defaultImagePath))
{
bmp = new Bitmap(defaultImagePath);
}
else
{
return null;
}
}
else
{
try
{
bmp = result[0];
LogNet.log.Info("相机拍照结果result【0】"+bmp);
LogNet.log.Info("ocr开始存图");
Assembly assembly = Assembly.GetExecutingAssembly();
string location = assembly.Location;
string directory = System.IO.Path.GetDirectoryName(location);
string filePath = directory+"\\ocr.png"; // 替换为实际路径
//关灯
//BLLCommon.lightSource.TurnOff();
// 保存图像到文件
SaveBitmapToFile(bmp, filePath);
LogNet.log.Info("ocr存图成功");
//Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialTemplateMatching"), 5);//模版匹配...
content = PaddleOCRHelper.StartCplusOcr(filePath);
LogNet.log.Info("content ocr识别结果:"+content);
}
catch (Exception)
{
bmp = result[0];
LogNet.log.Info("ocr识别解析失败");
}
// string res = PaddleOCRHelper.StartPythonOcr(filePath);
}
scanWork.workCodeInfo= Camera.GetBarCode(bmp);
string base64String = ConvertBitmapToBase64(bmp);
return new WebResultCamera { Msg = base64String,Text= content };
}
private ScanWork scanWork=new();
public WebResultCamera GetPrintAiing(string a)
{
//BLLCommon.extension.Clear();
//scanWork.workCodeInfo = new();
//string[] parts = a.Split(';');
//if (a.StartsWith("[") && a.EndsWith("]"))
//{
// a = a.Substring(1, a.Length - 2);
// Console.WriteLine(a);
//}
var aa = BLLCommon.macroKey;
// 2. 初始化目标字典
Dictionary<string, string> aaa = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);// { { "LOT",null} };
foreach (var key in aa)
{
aaa[key] = ""; // or aaa.Add(key, null);
}
try
{ // 解析JSON字符串
Dictionary<string, string> jsonData = JsonConvert.DeserializeObject<Dictionary<string, string>>(a);
// 解析 JSON 字符串反序列化
//aaa = JsonConvert.DeserializeObject<Dictionary<string, string>>(a);
// 将解析结果映射到目标字典
if (jsonData != null)
{
foreach (var key in aa)
{
if (jsonData.ContainsKey(key))
{
aaa[key] = jsonData[key];
}
}
}
}
catch (JsonException ex)
{
// 如果JSON解析失败,尝试其他格式
LogNet.log.Info("JSON解析失败,尝试其他格式解析");
if (a.Contains(":") && (a.Contains("[") || a.Contains("{")))
{
// 移除可能的括号和引号
string cleaned = a.Trim().Trim('[', ']', '{', '}');
// 处理可能的换行
cleaned = Regex.Replace(cleaned, @"\r\n|\n|\r", ",");
// 移除多余的逗号
cleaned = Regex.Replace(cleaned, @",+", ",");
// 分割成键值对
string[] entries = cleaned.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var entry in entries)
{
if (entry.Contains(":"))
{
string[] keyValue = entry.Split(new[] { ':' }, 2);
if (keyValue.Length == 2)
{
string key = keyValue[0].Trim().Trim('"', '\'');
string value = keyValue[1].Trim().Trim('"', '\'');
if (aaa.ContainsKey(key))
{
aaa[key] = value;
}
}
}
}
LogNet.log.Info("使用类JSON格式成功解析数据");
}
}
try
{
//bool hasMatch = scanWork.MatchingTemplate();
BLLCommon.extension.SetKey("AI",scanWork.originalCodeText, aaa, true, out _);
BLLCommon.extension.Print(true, aaa);
}
catch (Exception ex)
{
LogNet.log.Info("AI打印异常"+ex.ToString());
return new WebResultCamera { Text = "NG" };
}
//Common.frmMain.Invoke(delegate ()
//{
//scanWork.SetKey(hasMatch);
//});
//PrintAiing?.Invoke(aaa);
return new WebResultCamera { Text = "OK" };
}
public static void SaveBitmapToFile(Bitmap bmp, string filePath)
{
try
{
bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception)
{
LogNet.log.Info("ocr存图失败");
}
}
public static string ConvertBitmapToBase64(Bitmap bitmap)
{
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // 保存为PNG格式
byte[] imageBytes = ms.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
public WebResultCode WorkWithCode(Stream json)
{
LogNet.log.Info($"WebService WorkWithCode 接口被调用");
StreamReader sr = new(json);
string input = sr.ReadToEnd();
System.Web.Script.Serialization.JavaScriptSerializer serializer = new();
object[] obj = (object[])serializer.DeserializeObject(input);
string[] str = new string[obj.Length];
for (int i = 0; i < str.Length; i++)
str[i] = obj[i].ToString();
WebCodeText[] msg = null;
Common.frmMain.Invoke(new Action(() => { msg = Common.frmMain.WebTouchWork(str); }));
return new WebResultCode() { Data = msg };
}
public string alive()
{
return "1";
}
public WebResultCode ProcessBitmap(Stream info, string param)
{
BinaryFormatter bf = new BinaryFormatter();
Bitmap bitmap = (Bitmap)bf.Deserialize(info);
try
{
List<CameraVisionLib.Model.BarcodeInfo> workCodeInfo = new();
Dictionary<string, string> workCodeKeyword;// = new(StringComparer.OrdinalIgnoreCase);
bool[] originalCodeIsUsed = null;
workCodeInfo = Camera.GetBarCode(bitmap);
if (workCodeInfo.Count == 0)
return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败" };
BLLCommon.mateEdit.CurrntBitmap = DeepClone(bitmap);
bool rtn = BLLCommon.mateEdit.MatchingTemplate(workCodeInfo, BLLCommon.config.DefaultMaterialName, false, out string mateName, out workCodeKeyword, out AMatch aMatch);
LogNet.log.Info("模板匹配结果1:" + rtn);
WebResultCode webResultCode = null;
Dictionary<string, string> keys = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in workCodeKeyword)
{
// workCodeKeyword[item.Key]= item.Value.Replace("<OCR>", "");
keys.Add(item.Key, item.Value.Replace("<OCR>", ""));
}
if (!BLLCommon.extension.SetKey(mateName,null, keys, rtn, out string errmsg))
{
webResultCode = new WebResultCode() { ErrorCode = -2, Msg = errmsg };
LogNet.log.Info("模板匹配结果2:" + JsonConvert.SerializeObject(webResultCode));
}
if (webResultCode != null || !rtn)
return webResultCode;
LogNet.log.Info("模板匹配结束");
List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
#region 判断是否需要请求http替换数据
workCodeKeyword = WebserverReplaceData(keys);
//bool isReplaceData = ConfigHelper.Config.Get<bool>("WebServer_isReplaceData", false);
//if (isReplaceData)
//{
// LogNet.log.Info("WebServer:开始请求替换数据!");
// InvokePlugin invoke = new InvokePlugin();
// invoke.LoadDLL("DataHandling", LogNet.log);
// if (workCodeKeyword!=null)
// {
// if (workCodeKeyword.Count!=0)
// {
// LogNet.log.Info($"{JsonConvert.SerializeObject(workCodeKeyword)}");
// if (ConfigHelper.Config.Get("WebServer_Isformal", false))
// {
// Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
// if (workCodeKeyword.ContainsKey("PN"))
// {
// keyValuePairs.Add("firmaUrunKodu", workCodeKeyword["PN"]);
// }
// else
// {
// keyValuePairs.Add("firmaUrunKodu", "");
// }
// keyValuePairs.Add("lot", "");
// keyValuePairs.Add("barkodAdet", "1");
// keyValuePairs.Add("userName", "bekoservice");
// keyValuePairs.Add("pass", "beko1209tyu");
// keyValuePairs.Add("printerMacId", "");
// keyValuePairs.Add("basanUserName", "");
// }
// workCodeKeyword = invoke.RequestServer(workCodeKeyword, 1);
// }
// }
//}
#endregion
foreach (var wc in workCodeKeyword)
{
result.Add(new KeyValuePair<string, string>(wc.Key, wc.Value));
}
webResultCode = new WebResultCode() { workCodeKeyword = result, workCodeInfo = workCodeInfo };
LogNet.log.Info("模板匹配结果2:" + JsonConvert.SerializeObject(webResultCode));
return webResultCode;
}
catch (Exception ex)
{
LogNet.log.Error("ProcessBitmap", ex);
return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败:" + ex };
}
finally {
bitmap?.Dispose();
}
}
public static T DeepClone<T>(T _object)
{
try
{
T dstobject;
using (MemoryStream mStream = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mStream, _object);
mStream.Seek(0, SeekOrigin.Begin);//指定当前流的位置为流的开头。
dstobject = (T)bf.Deserialize(mStream);
mStream.Close();
}
return dstobject;
}
catch (Exception e)
{
LogNet.log.Error("DeepClone" , e);
return default;
}
}
public WebResultCode ProcessBitmaps(BitmapData bitmapData)
{
LogNet.log.Info("====开始WebCall匹配=========================");
BLLCommon.mateEdit.CurrntBitmap?.Dispose();
Bitmap bitmap = null;
MemoryStream stream = null;
try
{
if (bitmapData == null)
{
return new WebResultCode() { ErrorCode = -1, Msg = "未接收到任何数据!" };
}
if (bitmapData.ImageData.Length <= 0)
{
return new WebResultCode() { ErrorCode = -1, Msg = "扫码相机未传送图片;" };
}
byte[] imageData = Convert.FromBase64String(bitmapData.ImageData);
stream = new MemoryStream(imageData);
bitmap = new Bitmap(stream);
if (bitmap == null)
{
return new WebResultCode() { ErrorCode = -1, Msg = "图片解析完成为空;" };
}
List<CameraVisionLib.Model.BarcodeInfo> workCodeInfo = new();
if (bitmapData.BarCodeList == null && bitmapData.IsIDCamera)
{
return new WebResultCode() { ErrorCode = -1, Msg = "扫码相机未传来条码数据;" };
}
if (bitmapData.IsIDCamera)
{
bitmapData.BarCodeList.ForEach(barcode =>
{
workCodeInfo.Add(new CameraVisionLib.Model.BarcodeInfo
{
Text = barcode.Text,
//Size = barcode.Size,
Angle = barcode.Angle,
Center = new PointF(barcode.X, barcode.Y),
CodeType = barcode.CodeType,
Distance = barcode.Distance,
});
//LogNet.log.Info($"条码数据类型为{barcode.CodeType}");
});
//LogNet.log.Info($"条码数据[0]类型为{bitmapData.BarCodeList[0].CodeType}");
//if (bitmapData.BarCodeList[0].CodeType== "QR Code")
//{
// isQRCode = true;
// LogNet.log.Info("条码数据为QR Code");
//}
}
else
{
workCodeInfo = Camera.GetBarCode(bitmap);
if (workCodeInfo.Count == 0)
return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败" };
}
BLLCommon.mateEdit.CurrntBitmap = DeepClone(bitmap);
Dictionary<string, string> workCodeKeyword;
bool rtn = BLLCommon.mateEdit.MatchingTemplate(workCodeInfo, BLLCommon.config.DefaultMaterialName, false, out string mateName, out workCodeKeyword, out AMatch aMatch);
BLL.MatchAnalysis.ShowResult();
var point = new Point(-1, -1);
int angle = 0;
LogNet.log.Info("模板匹配结果:" + rtn);
if (rtn)
{
if (aMatch.CodeType == "QR Code")
{
LogNet.log.Info("条码数据为QR Code");
}
LogNet.log.Info($"条码数据类型为{aMatch.CodeType}");
string key = ConfigHelper.Config.Get("Label_Key", "");
workCodeKeyword.TryGetValue(key, out String Value);
LogNet.log.Info("模板匹配结果:" + rtn + $";关键字{key}:{Value};匹配成功条码xy:X={aMatch.Points.X};Y={aMatch.Points.Y},中心点x={bitmapData.X};y={bitmapData.Y},角度={aMatch.Angle},料盘尺寸={bitmapData.PlateW};匹配成功条码:{string.Join(", ", aMatch.IsCodeUsed)}");
point = UsrKeywordlabeling.LabelingAngle(Value, aMatch, new Point(bitmapData.X, bitmapData.Y), bitmapData.IsIDCamera, bitmapData.PlateW, out angle, aMatch.CodeType);
//point =UsrCustomlabeling.LabelingAngle_New(mateName, aMatch, new Point(bitmapData.X, bitmapData.Y), bitmapData.IsIDCamera, bitmapData.PlateW, out angle);
}
Dictionary<string, string> keys = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in workCodeKeyword)
{
keys.Add(item.Key, item.Value.Replace("<OCR>", ""));
}
if (!BLLCommon.extension.SetKey(mateName,null, keys, rtn, out string errmsg))
{
var webResultCode1 = new WebResultCode() { ErrorCode = -2, Msg = errmsg };
LogNet.log.Info("模板匹配结果: " + JsonConvert.SerializeObject(webResultCode1));
return webResultCode1;
}
List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
workCodeKeyword = WebserverReplaceData(keys);
foreach (var wc in workCodeKeyword)
{
result.Add(new KeyValuePair<string, string>(wc.Key, wc.Value));
}
NewPositionAngle newPosition = new NewPositionAngle
{
X = point.X,
Y = point.Y,
Angle = angle,
IsCodeUsed = aMatch.IsCodeUsed
};
LogNet.log.Info($"返回坐标及角度X={newPosition.X};Y={newPosition.Y};角度={newPosition.Angle}");
var webResultCode = new WebResultCode() { workCodeKeyword = result, workCodeInfo = workCodeInfo, PositionAngle = newPosition };
LogNet.log.Info("模板匹配结果: " + JsonConvert.SerializeObject(webResultCode));
return webResultCode;
}
catch (Exception ex)
{
LogNet.log.Error("ProcessBitmaps", ex);
return new WebResultCode() { ErrorCode = -1, Msg = "扫码失败:" + ex };
}
finally {
bitmap?.Dispose();
stream?.Dispose();
}
}
public Dictionary<string, string> WebserverReplaceData(Dictionary<string, string> workCodeKeyword)
{
#region 判断是否需要请求http替换数据
bool isReplaceData = ConfigHelper.Config.Get<bool>("WebServer_isReplaceData", false);
if (isReplaceData)
{
LogNet.log.Info("WebServer:开始请求替换数据!");
InvokePlugin invoke = new InvokePlugin();
invoke.LoadDLL("DataHandling", LogNet.log);
if (workCodeKeyword != null)
{
if (workCodeKeyword.Count != 0)
{
//foreach (var item in workCodeKeyword)
//{
// item.Value= item.Value.Replace("<OCR>", "");
//}
LogNet.log.Info($"识别关键字内容:{JsonConvert.SerializeObject(workCodeKeyword)}");
if (ConfigHelper.Config.Get("WebServer_Isformal", true))
{
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
string firmaUrunKoduValue = "";
if (workCodeKeyword.TryGetValue("PN", out string pnValue) && !string.IsNullOrWhiteSpace(pnValue))
{
firmaUrunKoduValue = pnValue;
}
else if (workCodeKeyword.TryGetValue("firmaUrunKodu", out string firmaUrunKodu) && !string.IsNullOrWhiteSpace(firmaUrunKodu))
{
firmaUrunKoduValue = firmaUrunKodu;
}
keyValuePairs.Add("firmaUrunKodu", firmaUrunKoduValue);
keyValuePairs.Add("lot", "");
keyValuePairs.Add("barkodAdet", "1");
keyValuePairs.Add("userName", "bekoservice");
keyValuePairs.Add("pass", "beko1209tyu");
keyValuePairs.Add("printerMacId", "");
keyValuePairs.Add("basanUserName", "");
workCodeKeyword = invoke.RequestServer(keyValuePairs, 1);
}
else
{
workCodeKeyword = invoke.RequestServer(workCodeKeyword, 1);
}
}
}
}
return workCodeKeyword;
#endregion
}
}
}