革博士程序V1仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2441 lines
134 KiB

  1. using IKapC.NET;
  2. using LeatherApp.Device;
  3. using LeatherApp.Device.CamerUtil;
  4. using LeatherApp.Interface;
  5. using LeatherApp.Utils;
  6. using Models;
  7. using Newtonsoft.Json;
  8. using Newtonsoft.Json.Linq;
  9. using OpenCvSharp;
  10. using OpenCvSharp.Extensions;
  11. using S7.Net;
  12. using SqlSugar;
  13. using Sunny.UI;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Generic;
  17. using System.ComponentModel;
  18. using System.Data;
  19. using System.Diagnostics;
  20. using System.Drawing;
  21. using System.Drawing.Imaging;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Reflection;
  25. using System.Text;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using System.Windows.Forms;
  29. namespace LeatherApp.Page
  30. {
  31. public partial class FHome : UIPage
  32. {
  33. private WarningEnum warningLevel;//警告等级
  34. private CurrentStateEnum currentState;//当前状态
  35. private DevContainer devContainer = new DevContainer();
  36. private Service.ProductService svcProduct = new Service.ProductService();
  37. private Service.RecordsService svcRecord = new Service.RecordsService();
  38. private bool defectPauseForUser = false;
  39. //private Models.Product currProductModel = null;//当前产品
  40. //private Models.Records record = null;
  41. private Stopwatch pStopWatch=new Stopwatch();//计算速度用,暂停时停止计数
  42. private object lockScanPhoto = new object();
  43. private object lockCurrKey = new object();
  44. private int currKey=0;
  45. private Hashtable htTask = new Hashtable();//默认单线程写入不用lock, 多线程安全同步读取用Synchronized
  46. //无产品编码时加载
  47. FProductInfo frmProduct;
  48. private double ThnDieLen = 0;
  49. private Dictionary<int, Mat> defectTag = new Dictionary<int, Mat>();
  50. //裁切偏移
  51. private double OffsetCut = 0.2;
  52. //云端
  53. private CloudMgr cloudMgr = new CloudMgr();
  54. private bool init_Cloud;
  55. //
  56. private bool _residueWarnningLenStop;
  57. public FHome(FProductInfo frm)
  58. {
  59. InitializeComponent();
  60. frmProduct = frm;
  61. if(Config.Camer_Name == CamerDevNameEnum.埃科)
  62. IKapCLib.ItkManInitialize();
  63. #region dataGridView设置
  64. uiDataGridView1.AllowUserToAddRows = uiDataGridView1.AllowUserToDeleteRows = false;//用户添加删除行
  65. uiDataGridView1.AllowUserToResizeRows = false;//用户调整行大小
  66. uiDataGridView1.AllowUserToResizeColumns = false;//用户调整列大小
  67. uiDataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//只可选中整行,不是单元格
  68. //显示行号与列宽度自动调整
  69. uiDataGridView1.RowHeadersVisible = true;
  70. uiDataGridView1.RowHeadersWidth = 60;
  71. uiDataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  72. uiDataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  73. uiDataGridView1.RowPostPaint += (sender, e) =>//序号列头
  74. {
  75. Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.uiDataGridView1, sender, e);
  76. //Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, uiDataGridView1.RowHeadersWidth - 4, e.RowBounds.Height);
  77. //TextRenderer.DrawText(e.Graphics, (e.RowIndex).ToString(), uiDataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, uiDataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  78. };
  79. for (int i = 0; i < uiDataGridView1.Columns.Count; i++)//禁止点击列头排序
  80. uiDataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  81. ////行列交叉处标题
  82. //if (dataGridView1.RowHeadersVisible) dataGridView1.TopLeftHeaderCell.Value = "SPH/CYL";
  83. //事件
  84. //this.uiDataGridView1.DataBindingComplete += this.uiDataGridView1_DataBindingComplete;//bing data时发生,可修改单元格内容
  85. //this.uiDataGridView1.SelectIndexChange += uiDataGridView1_SelectIndexChange;//选择行时发行
  86. this.uiDataGridView1.CellClick += uiDataGridView1_CellClick; ;
  87. #endregion
  88. this.ucColorListDefect.ColorChanged = (xcode, xcolor) =>
  89. {
  90. try
  91. {
  92. var item=Config.getDefectItem(xcode);
  93. if(item != null)
  94. {
  95. item["color"] = xcolor;
  96. Config.SaveDefectItemList(Config.defectItemList);
  97. }
  98. }
  99. catch (Exception ex)
  100. {
  101. this.AddTextEvent(DateTime.Now,"事件", "缺陷颜色修改后保存失败!");
  102. }
  103. };
  104. }
  105. private void uiDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
  106. {
  107. if (e.RowIndex < 0 || currKey == 0)
  108. return;
  109. Records record = Hashtable.Synchronized(htTask)[currKey] as Records;
  110. //var defectInfo = record.DefectInfoList[record.DefectInfoList.Count - e.RowIndex-1];//按顺序索引引用
  111. var defectInfo = record.DefectInfoList.FirstOrDefault(m => m.uid == (long)this.uiDataGridView1.CurrentRow.Cells["colUid"].Value);
  112. if(defectInfo == null)
  113. {
  114. UIMessageTip.ShowError("此记录已不存在!", 1000);
  115. return;
  116. }
  117. this.picDefectImage.loadImage(defectInfo.image);
  118. //选中
  119. this.Invoke(new System.Action(() =>
  120. {
  121. if (lineChartDefect.Option.Series != null && lineChartDefect.Option.Series.ContainsKey("SELECT"))
  122. {
  123. lineChartDefect.Option.Series["SELECT"].Clear();
  124. lineChartDefect.Option.Series["SELECT"].Add( defectInfo.CentreX, defectInfo.CentreY / 100);
  125. lineChartDefect.Refresh();
  126. }
  127. }));
  128. }
  129. private void lineChartDefect_Click(object sender, EventArgs e)
  130. {
  131. if (lineChartDefect.Option.Series != null && lineChartDefect.Option.Series.ContainsKey("SELECT") && lineChartDefect.Option.Series["SELECT"].DataCount > 0)
  132. {
  133. lineChartDefect.Option.Series["SELECT"].Clear();
  134. lineChartDefect.Refresh();
  135. }
  136. }
  137. #region 内部方法
  138. private void resetUIValue(bool resetCurrKey=true)
  139. {
  140. firstTest = true;
  141. if(resetCurrKey)
  142. currKey = 0;
  143. pStopWatch.Reset();
  144. this.Invoke(new System.Action(() =>
  145. {
  146. lblLen.Text = "0米";
  147. lblSpeed.Text = "速度:0米/分";
  148. this.uilbKF.Text = $"当前幅宽:0cm";
  149. txtBarCodeName.Text = txtBatchId.Text = txtReelId.Text = "";
  150. numErpLen.Text = "0";
  151. this.lineChartDefect.SetOption(new UILineOption());
  152. this.lineChartFaceWidth.SetOption(new UILineOption());
  153. this.uiDataGridView1.DataSource = null;
  154. this.uiDataGridView1.Rows.Clear();
  155. this.lstboxLog.Items.Clear();
  156. this.picDefectImage.clear();
  157. this.picScanner1.Image = this.picScanner2.Image = null;
  158. picScanner1.Refresh();
  159. picScanner2.Refresh();
  160. }));
  161. }
  162. /// <summary>
  163. /// 全局中断
  164. /// </summary>
  165. private void globalBreakEvent(int portIndex, byte data)
  166. {
  167. AddTextEvent(DateTime.Now,"I/0状态", $"{portIndex}:{Convert.ToString(data, 2)}");
  168. if (compareIOInput(CMDName.启动按钮) && this.btnStart.Enabled)
  169. {
  170. this.devContainer.devIOCard.writeBitState(0, 0, true);
  171. this.startCommand();
  172. Task.Run(async () =>
  173. {
  174. await Task.Delay(500);
  175. this.devContainer.devIOCard.writeBitState(0, 0, false);
  176. });
  177. }
  178. else if (compareIOInput(CMDName.暂停按钮) && this.btnPause.Enabled)
  179. {
  180. this.devContainer.devIOCard.writeBitState(0, 1, true);
  181. this.pauseCommand();//true 输出暂停不会触发输入暂停
  182. Task.Run(async () =>
  183. {
  184. await Task.Delay(500);
  185. this.devContainer.devIOCard.writeBitState(0, 1, false);
  186. });
  187. }
  188. //else if (compareIOInput(CMDName.复位按钮) && this.tsbtnReset.Enabled)
  189. // resetCommand();
  190. //else if (!this.disableBuzzer && compareIOInput(CMDName.门磁告警输入))
  191. // warning(WarningEnum.Low, true);
  192. //else if (!this.disableBuzzer && compareIOInput(CMDName.喷墨告警输入))
  193. // warning(WarningEnum.Low, true);
  194. }
  195. private bool compareIOInput(CMDName key)
  196. {
  197. JObject joJson = Config.CMDProcess[key];
  198. IODirectionEnum direction = (IODirectionEnum)joJson.Value<int>("Direction");
  199. if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出)
  200. {
  201. return Util.compareIOInput(
  202. joJson.Value<JArray>("IN_OP_SHOW").ToObject<List<string>>().ToArray(),
  203. devContainer.devIOCard.DIData);
  204. }
  205. return false;
  206. }
  207. /// <summary>
  208. /// 报警,只响应low,high
  209. /// </summary>
  210. private void warning(WarningEnum level, bool buzzer = true)
  211. {
  212. if (level == WarningEnum.Normal)
  213. return;
  214. //lock (myLock)
  215. warningLevel = level;
  216. //if ((int)level >= (int)WarningEnum.Low)//暂停
  217. {
  218. //currentState = CurrentStateEnum.暂停;
  219. if (!Config.StopPLC)
  220. this.devContainer.devPlc.pauseDev();
  221. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  222. {
  223. this.devContainer.devIOCard.writeBitState(0, 1, true);
  224. Task.Run(async () =>
  225. {
  226. await Task.Delay(500);
  227. this.devContainer.devIOCard.writeBitState(0, 1, false);
  228. });
  229. }
  230. pauseCommand(buzzer);
  231. }
  232. //else if (level == WarningEnum.High)//急停
  233. //{
  234. // currentState = CurrentStateEnum.急停;
  235. // devContainer.devAxis.stopNow();
  236. // stopNowCommand();
  237. //}
  238. //启用报警消除按钮
  239. //this.Invoke(new System.Action(() =>
  240. //{
  241. // tsbtnWarning.Enabled = true;
  242. //}));
  243. }
  244. /// <summary>
  245. /// 重新生成缺陷分布(cm2M在内部转换)
  246. /// </summary>
  247. /// <param name="lstDefectInfo">Records.DefectInfoList</param>
  248. /// <param name="XSizeRange">幅宽</param>
  249. /// <param name="YSizeRange">卷长度</param>
  250. private void reDrawDefectPoints(List<DefectInfo> lstDefectInfo, double[] XSizeRange=null, double[] YSizeRange=null,bool addSelRect=true)
  251. {
  252. UILineOption option;
  253. //AddTextEvent(DateTime.Now,$"绘图", $"缺陷分布, W={string.Join(", ", XSizeRange)},H={string.Join(", ", YSizeRange)}, LastData={JsonConvert.SerializeObject(lstDefectInfo[lstDefectInfo.Count - 1])}");
  254. var lstData = lstDefectInfo.OrderBy(m => m.Code).ThenBy(m => m.Code).ToList();
  255. if (XSizeRange == null || YSizeRange == null)
  256. option = this.lineChartDefect.Option;
  257. else
  258. {
  259. if (YSizeRange[0] == YSizeRange[1])
  260. {
  261. YSizeRange[0] -= YSizeRange[0] / 10f;
  262. YSizeRange[1] += YSizeRange[1] / 10f;
  263. }
  264. YSizeRange[0] /= 100;
  265. YSizeRange[1] /= 100;
  266. option = new UILineOption();
  267. option.XAxis.Name = "面宽(cm)";
  268. option.YAxis.Name = "长度(米)";
  269. //option.Grid.Top = 20;//边距
  270. option.Grid.Right = 20;//边距
  271. //X轴数据类型
  272. option.XAxisType = UIAxisType.Value;
  273. //设置X/Y轴显示范围
  274. option.XAxis.SetRange(XSizeRange[0], XSizeRange[1]);
  275. option.YAxis.SetRange(YSizeRange[0], YSizeRange[1]);
  276. //坐标轴显示小数位数
  277. option.XAxis.AxisLabel.DecimalPlaces = option.YAxis.AxisLabel.DecimalPlaces = 1;
  278. //X/Y轴画参考线
  279. //option.YAxisScaleLines.Add(new UIScaleLine("上限", 3.5, Color.Red));
  280. //option.YAxisScaleLines.Add(new UIScaleLine("下限", 2.2, Color.Gold));
  281. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(3).DateTimeString(), dt.AddHours(3), Color.Red));
  282. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(6).DateTimeString(), dt.AddHours(6), Color.Red));
  283. option.ToolTip.Visible = true;
  284. //option.ToolTip.Formatter = "怎么自定义X,Y显示名称??{X}";
  285. option.Title = new UITitle();
  286. option.Title.Text = "";
  287. option.Title.SubText = "";
  288. }
  289. option.Series.Clear();
  290. string preCode = "";
  291. UILineSeries series=null;
  292. foreach (var item in lstData)
  293. {
  294. if (preCode != item.Code)//加一组新类型及样式
  295. {
  296. preCode = item.Code;
  297. var one = Config.getDefectItem(item.Code);
  298. if (one == null)
  299. {
  300. AddTextEvent(DateTime.Now,$"绘图", $"getDefectItem({item.Code}) is null!");
  301. continue;
  302. }
  303. JObject objItem= one as JObject;
  304. Color color = ColorTranslator.FromHtml(objItem.Value<string>("color"));
  305. series = option.AddSeries(new UILineSeries(objItem.Value<string>("name"), color));//加一组
  306. series.Symbol = UILinePointSymbol.Star;
  307. series.SymbolSize = 4;
  308. series.SymbolLineWidth = 2;
  309. series.ShowLine = false;
  310. series.SymbolColor = color;
  311. //数据点显示小数位数(针对当前UILineSeries)
  312. series.XAxisDecimalPlaces = 1;
  313. series.YAxisDecimalPlaces = 2;
  314. //series.Smooth = false;
  315. }
  316. series.Add( item.CentreX, item.CentreY / 100); //cm -> m
  317. }
  318. ////加一组框选
  319. if (addSelRect && !option.Series.ContainsKey("SELECT"))
  320. {
  321. series=option.AddSeries(new UILineSeries("SELECT", Color.Red));
  322. series.Symbol = UILinePointSymbol.Circle;
  323. series.SymbolSize = 6;
  324. series.SymbolLineWidth = 3;
  325. series.ShowLine = false;
  326. series.SymbolColor = Color.Red;
  327. //数据点显示小数位数(针对当前UILineSeries)
  328. series.XAxisDecimalPlaces = 1;
  329. series.YAxisDecimalPlaces = 2;
  330. //series.Add(1, 1);
  331. }
  332. //====
  333. //option.GreaterWarningArea = new UILineWarningArea(3.5);
  334. //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold);
  335. this.BeginInvoke(new System.Action(() =>
  336. {
  337. this.lineChartDefect.SetOption(option);
  338. //series.UpdateYData();//按序号更新Y轴值(可设置值超出范围用于闪烁)
  339. }));
  340. }
  341. /// <summary>
  342. /// 重新门幅宽度
  343. /// </summary>
  344. /// <param name="points"></param>
  345. /// <param name="XSizeRange">卷长度</param>
  346. /// <param name="YSizeRange">幅宽</param>
  347. private void reDrawFaceWidth(List<float[]> points, double[] XSizeRange, double[] YSizeRange)
  348. {
  349. //AddTextEvent(DateTime.Now,$"绘图", $"门幅宽度, W={string.Join(", ", XSizeRange)},H={string.Join(", ", YSizeRange)}, LastData={JsonConvert.SerializeObject(points[points.Count-1])}");
  350. if(YSizeRange[0]== YSizeRange[1])
  351. {
  352. YSizeRange[0] -= YSizeRange[0] / 10f;
  353. YSizeRange[1] += YSizeRange[1] / 10f;
  354. }
  355. XSizeRange[0] /= 100;
  356. XSizeRange[1] /= 100;
  357. //防止超限
  358. XSizeRange[1] += 0.01;
  359. YSizeRange[1] += 0.1;
  360. UILineOption option = new UILineOption();
  361. option.XAxis.Name = "长度(米)";
  362. option.YAxis.Name = "面宽(cm)";
  363. option.Grid.Top = 20;
  364. option.Grid.Right = 20;
  365. //X轴数据类型
  366. option.XAxisType = UIAxisType.Value;
  367. //设置X/Y轴显示范围
  368. option.XAxis.SetRange(XSizeRange[0], XSizeRange[1]);
  369. option.YAxis.SetRange(YSizeRange[0], YSizeRange[1]);
  370. //坐标轴显示小数位数
  371. option.XAxis.AxisLabel.DecimalPlaces = option.YAxis.AxisLabel.DecimalPlaces = 1;
  372. //X/Y轴画参考线
  373. //option.YAxisScaleLines.Add(new UIScaleLine("上限", 3.5, Color.Red));
  374. //option.YAxisScaleLines.Add(new UIScaleLine("下限", 2.2, Color.Gold));
  375. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(3).DateTimeString(), dt.AddHours(3), Color.Red));
  376. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(6).DateTimeString(), dt.AddHours(6), Color.Red));
  377. option.ToolTip.Visible = true;
  378. //option.ToolTip.Formatter = "怎么自定义X,Y显示名称??{X}";
  379. option.Title = new UITitle();
  380. option.Title.Text = "";
  381. option.Title.SubText = "";
  382. Color color = Color.Blue;
  383. UILineSeries series = null;
  384. series = option.AddSeries(new UILineSeries("面宽", color));
  385. series.Symbol = UILinePointSymbol.Circle;
  386. series.ShowLine = true;
  387. series.SymbolSize = 1;//4
  388. series.SymbolLineWidth = 1;//2
  389. series.SymbolColor = color;
  390. //数据点显示小数位数(针对当前UILineSeries)
  391. series.XAxisDecimalPlaces = 2;
  392. series.YAxisDecimalPlaces = 1;
  393. float x;
  394. foreach (var item in points)
  395. {
  396. x = item[0] / 100; //cm -> m
  397. series.Add(x, item[1]);
  398. if (x < XSizeRange[0]) AddTextEvent(DateTime.Now,$"绘图", $"门幅宽度超限 1!!!! {x}<{XSizeRange[0]}",WarningEnum.High);
  399. if (x > XSizeRange[1]) AddTextEvent(DateTime.Now,$"绘图", $"门幅宽度超限 2!!!! {x}>{XSizeRange[1]}", WarningEnum.High);
  400. if (item[1] < YSizeRange[0]) AddTextEvent(DateTime.Now,$"绘图", $"门幅宽度超限 3!!!! {item[1]}<{YSizeRange[0]}", WarningEnum.High);
  401. if (item[1] > YSizeRange[1]) AddTextEvent(DateTime.Now,$"绘图", $"门幅宽度超限 4!!!! {item[1]}>{YSizeRange[1]}", WarningEnum.High);
  402. }
  403. //====
  404. //option.GreaterWarningArea = new UILineWarningArea(3.5);
  405. //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold);
  406. this.BeginInvoke(new System.Action(() =>
  407. {
  408. this.lineChartFaceWidth.SetOption(option);
  409. }));
  410. }
  411. private delegate void AddTextDelegate(DateTime time,string tag, string msg, WarningEnum level, bool Show);
  412. private void AddTextEvent(DateTime now, string tag, string msg, WarningEnum level = WarningEnum.Normal, bool Show = true)
  413. {
  414. try
  415. {
  416. if (InvokeRequired)
  417. {
  418. Invoke(new AddTextDelegate(AddTextEvent), new object[]
  419. {
  420. now,
  421. tag,
  422. msg,
  423. level,
  424. Show
  425. });
  426. }
  427. else
  428. {
  429. if (tag != null && tag != "")
  430. tag = $" - [{tag}]";
  431. //var now = DateTime.Now;
  432. msg = now.ToString("HH:mm:ss fff") + tag + " - " + msg;
  433. //cont = MyHelper.subString(cont, 300);
  434. //写日志,warn和error日志直接写
  435. writeLog(now, level, msg);
  436. //
  437. //if (type > 0)
  438. // cont = $"<color=\"{(type == 1 ? "Yellow" : "Red")}\">{cont}</color>";
  439. if (Show)
  440. {
  441. //msg = (level == WarningEnum.Normal ? "B" : level == WarningEnum.Low ? "Y" : "R") + msg;
  442. msg = (level == WarningEnum.Normal ? "" : level == WarningEnum.Low ? "Y" : "R") + msg;
  443. //this.Invoke(new System.Action(() =>
  444. //{
  445. if (this.lstboxLog.Items.Count > 1000)
  446. this.lstboxLog.Items.Clear();
  447. lstboxLog.Items.Insert(0, msg);
  448. //}));
  449. }
  450. //日志滚动
  451. //lstLog.SelectedIndex = lstLog.Items.Count - 1;
  452. //开启云端
  453. if ((init_Cloud) && (level != WarningEnum.Normal))
  454. {
  455. //上传报警状态和信息
  456. string statusStr = level == WarningEnum.Normal ? "正常" : level == WarningEnum.Low ? "警告" : "系统报警";
  457. cloudMgr.SendTopic("device/attributes", $"{{\"status\": \"{statusStr}\", \"alm\": \"{tag}-{msg}\", " +
  458. $"\"name\": \"{Config.CloudThisName}\"}}");
  459. }
  460. }
  461. }
  462. catch (Exception ex)
  463. {
  464. //MessageBox.Show("AddTextEvent ex=(" + ex.Message + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
  465. }
  466. }
  467. private void writeLog(DateTime now, WarningEnum level, string text)
  468. {
  469. string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\";
  470. //if (type == 0) directory = Application.StartupPath + "\\Log\\Info\\";
  471. //else if (type == 1) directory = Application.StartupPath + "\\Log\\Warn\\";
  472. //else directory = Application.StartupPath + "\\Log\\Error\\";
  473. if (!System.IO.Directory.Exists(directory))
  474. System.IO.Directory.CreateDirectory(directory);
  475. File.AppendAllText(directory + now.ToString("yyyyMMdd") + ".log", text + "\r\n");
  476. }
  477. #endregion
  478. private void FHome_Load(object sender, EventArgs e)
  479. {
  480. ucColorListDefect.initData(Config.defectItemList);
  481. this.lineChartDefect.SetOption(new UILineOption());
  482. this.lineChartFaceWidth.SetOption(new UILineOption());
  483. //判断是否连接云端
  484. if(Config.cloud_open >0)
  485. {
  486. AddTextEvent(DateTime.Now, "设备启动", $"连接云端");
  487. if (cloudMgr.ConnectCloud(Config.cloud_ip, Config.cloud_port,
  488. Config.cloud_username, Config.cloud_password))
  489. {
  490. init_Cloud = true;
  491. AddTextEvent(DateTime.Now, "云端数据", $"开启云端连接");
  492. //开启云端
  493. if (init_Cloud)
  494. {
  495. //上传报警状态和信息
  496. string statusStr = "正常" ;
  497. cloudMgr.SendTopic("device/attributes", $"{{\"status\": \"{statusStr}\", \"alm\": \"系统运行-正常启动软件\", " +
  498. $"\"name\": \"{Config.CloudThisName}\"}}");
  499. }
  500. }
  501. else
  502. AddTextEvent(DateTime.Now, "云端数据", "云端连接失败!", WarningEnum.Low);
  503. }
  504. }
  505. private void FHome_Shown(object sender, EventArgs e)
  506. {
  507. //picScanner1.BackColor = Color.Red;
  508. //picScanner2.BackColor = Color.Green;
  509. picScanner1.Width = picScanner2.Width = pnlScannerImg.ClientSize.Width / 2 - 5;
  510. picScanner2.Left = picScanner1.Width + 5;
  511. uilbKF.Top = 8;
  512. }
  513. //开机
  514. private void btnOpen_Click(object sender, EventArgs e)
  515. {
  516. //this.txtNote.Text = (currProductModel == null ? "NO" : currProductModel.Name);
  517. Config.LoadAllConfig();
  518. //设置程序最小/大线程池
  519. // Get the current settings.
  520. int minWorker, minIOC;
  521. ThreadPool.GetMinThreads(out minWorker, out minIOC);
  522. ThreadPool.SetMinThreads(25, minIOC);
  523. //ThreadPool.SetMaxThreads(256, 256);
  524. //DefectLib dl = new DefectLib();
  525. //dl.start();
  526. //加载寻边模型
  527. OpenCVUtil.LoadEdgeMode();
  528. this.btnOpen.Enabled = false;
  529. this.resetUIValue();
  530. AddTextEvent(DateTime.Now,"设备启动", $"正在启动硬件设备(版本:v{ Assembly.GetExecutingAssembly().GetName().Version.ToString()})。。。");
  531. warningLevel = WarningEnum.Normal;
  532. this.btnStart.Enabled = this.btnEnd.Enabled = this.btnPause.Enabled = false;
  533. //后台线程回调事件
  534. devContainer = new DevContainer();
  535. devContainer.StateChange = (state, msg) =>
  536. {
  537. if (state)
  538. {
  539. currentState = CurrentStateEnum.初始;
  540. AddTextEvent(DateTime.Now,"设备启动", $"启动成功,请点开始验布按钮!");
  541. //全局中断
  542. devContainer.devIOCard.INEvent = globalBreakEvent;
  543. // I/O reset后,输出默认状态
  544. if (devContainer.devIOCard.IsInit)
  545. {
  546. AddTextEvent(DateTime.Now,"复位", $"I/O复位...");
  547. if (!devContainer.devIOCard.reset())
  548. {
  549. AddTextEvent(DateTime.Now,"复位", "I/O板卡复位失败!", WarningEnum.High);
  550. return;
  551. }
  552. if (!devContainer.io_output(CMDName.IO默认输出))
  553. {
  554. //AddTextEvent(DateTime.Now,"复位", "I/O板卡复位默认值失败!", WarningEnum.High);
  555. //return;
  556. }
  557. int portIndex = 0;
  558. foreach(var data in devContainer.devIOCard.DIData)
  559. AddTextEvent(DateTime.Now,"I/0状态", $"DIData: {portIndex++}-{Convert.ToString(data, 2)}");
  560. }
  561. devContainer.OutDebugEvent = (tag, debugInfo) =>
  562. {
  563. AddTextEvent(DateTime.Now,tag, debugInfo);
  564. };
  565. //
  566. this.Invoke(new System.Action(() =>
  567. {
  568. this.btnOpen.Enabled = false;
  569. this.btnClose.Enabled = true;
  570. this.btnStart.Enabled = true;
  571. this.tcbarLightValue.Enabled = true;
  572. tcbarLightValue.Value=devContainer.devLight.getDigitalValue(1);
  573. }));
  574. devContainer.libPhoto.QueueCountEvent = (count) =>
  575. {
  576. this.BeginInvoke(new System.Action(() =>
  577. {
  578. this.lblWaitImageCount.Text = count.ToString();
  579. }));
  580. };
  581. devContainer.libDefect.QueueCountEvent = (type, count) =>
  582. {
  583. this.BeginInvoke(new System.Action(() =>
  584. {
  585. switch (type)
  586. {
  587. case 0: this.lblDefectQueue0.Text = count.ToString(); break;
  588. case 1: this.lblDefectQueue1.Text = count.ToString(); break;
  589. case 2: this.lblDefectQueue2.Text = count.ToString(); break;
  590. }
  591. }));
  592. };
  593. //在【暂停】和【运行中】时都可以扫码,扫码后即开始即结束上一卷(如存在),自动开始下一卷,等待相机照片回调
  594. devContainer.devCodeScanner.ScanerEvent = (barCode) =>
  595. {
  596. int errCode = 0;
  597. try
  598. {
  599. //AddTextEvent(DateTime.Now,"扫码", $"{code}:{currentState.ToString()}");
  600. if (!devContainer.state || string.IsNullOrWhiteSpace(barCode)
  601. || (currentState != CurrentStateEnum.运行中 && currentState != CurrentStateEnum.暂停))
  602. return;
  603. string barCodeName="",len = "0", batchId = "", reelId = "";
  604. if (!string.IsNullOrWhiteSpace(Config.ErpDBConStr) && !string.IsNullOrWhiteSpace(Config.ErpSql) && !string.IsNullOrWhiteSpace(barCode))
  605. {
  606. AddTextEvent(DateTime.Now,"扫码", $"产品条码({barCode})到ERP查询对应数据...", WarningEnum.Normal);
  607. var rowData = this.loadErpData(barCode);
  608. if (rowData == null)
  609. {
  610. AddTextEvent(DateTime.Now,"扫码", $"产品条码({barCode})无对应ERP数据,不做响应!", WarningEnum.Low);
  611. return;
  612. }
  613. barCodeName = rowData[0].ToString();
  614. if (rowData.ItemArray.Length > 1) len = rowData[1].ToString();
  615. if (rowData.ItemArray.Length > 2) batchId = rowData[2].ToString();
  616. if (rowData.ItemArray.Length > 3) reelId = rowData[3].ToString();
  617. }
  618. else
  619. barCodeName = barCode;//没有ERP对应关系时直接使用条码做为品名
  620. errCode = 1;
  621. //SHNY-PX-6-***
  622. string[] codes = barCodeName.Split(new char[] { '-' });
  623. if (codes.Length < 4)
  624. {
  625. AddTextEvent(DateTime.Now,"扫码", $"产品品名({barCodeName})格式错误,不做响应!", WarningEnum.Low);
  626. return;
  627. }
  628. //新开始
  629. this.resetUIValue(false);
  630. errCode = 2;
  631. //加载新产品
  632. string pcode = "1-" + codes[2];
  633. if (codes[1] == "0" || Config.SuedeList1.Contains(codes[1]))
  634. pcode = "0-" + codes[2];
  635. #if false
  636. else
  637. pcode = codes[1] + "-" + codes[2];
  638. #elif HX_LOD
  639. else
  640. pcode = "1-" + codes[2];
  641. #else
  642. else if (codes[1] == "1" || Config.SuedeList2.Contains(codes[1]))
  643. pcode = "1-" + codes[2];
  644. else if (codes[1] == "2" || Config.SuedeList3.Contains(codes[1]))
  645. pcode = "2-" + codes[2];
  646. else if (codes[1] == "3" || Config.SuedeList4.Contains(codes[1]))
  647. pcode = "3-" + codes[2];
  648. else if (codes[1] == "4" || Config.SuedeList5.Contains(codes[1]))
  649. pcode = "4-" + codes[2];
  650. else if (codes[1] == "5" || Config.SuedeList6.Contains(codes[1]))
  651. pcode = "5-" + codes[2];
  652. else
  653. pcode = "1-" + codes[2];
  654. #endif
  655. var productInfo = svcProduct.GetModelNav(pcode); //frmProduct.loadProduct(code);
  656. Records record;
  657. lock (lockCurrKey)
  658. {
  659. errCode = 3;
  660. //保存,这里队列图片可能还未检测完
  661. if (currKey > 0)
  662. {
  663. string szBatchId, szReelId;
  664. double ldErpLen;
  665. szBatchId = txtBatchId.Text.Trim();
  666. szReelId = txtReelId.Text.Trim();
  667. ldErpLen = Convert.ToDouble(numErpLen.Text.Trim());
  668. //BatchId = code,//code[2]
  669. //ReelId = "1",//code[3]
  670. int mykey = currKey;
  671. Task.Run(() => { saveCurrRecord(mykey, szBatchId, szReelId, ldErpLen); });
  672. currKey = 0;
  673. }
  674. if (productInfo == null)
  675. {
  676. AddTextEvent(DateTime.Now,"扫码", $"编码({pcode})对应配方不存在,请先添加产品配方设置,暂停设备!", WarningEnum.High);
  677. warning(WarningEnum.Low);//暂停
  678. this.BeginInvoke(new System.Action(() =>
  679. {
  680. frmProduct.loadProduct(pcode);//转到新建编码
  681. }));
  682. return;
  683. }
  684. errCode = 4;
  685. var now = DateTime.Now;
  686. currKey = now.Hour * 10000 + now.Minute * 100 + now.Second;
  687. _residueWarnningLenStop = false;
  688. //var materialItem = codes[0]+"-"+ codes[1];
  689. var colorItem = Config.getColorItem(int.Parse(codes[2]));
  690. record = new Records()
  691. {
  692. currKey = currKey,
  693. ProductId = productInfo.Id,
  694. ProductInfo = productInfo,//后面计算合格时用
  695. Color = (colorItem == null ? "未知" : colorItem["name"].ToString()),
  696. Material = codes[0] + "-" + codes[1],// (materialItem == null ? "未知" : materialItem["name"].ToString()),
  697. BarCode = barCode,
  698. BarCodeName = barCodeName,
  699. ErpLen=double.Parse(len),
  700. BatchId=batchId,
  701. ReelId=reelId,
  702. ModifyUserCode = Config.loginUser.Code,
  703. CreateUserCode = Config.loginUser.Code,
  704. };
  705. htTask.Add(currKey, record);
  706. }
  707. errCode = 8;
  708. //
  709. errCode = 9;
  710. AddTextEvent(DateTime.Now,"扫码", $"品名({barCodeName}),加载产品信息({productInfo.Code})完成,加载配方(光源={productInfo.LightValue},曝光={productInfo.ExposureTime},增益={productInfo.Gain})...");
  711. errCode = 10;
  712. if (productInfo.LightValue > 0)//光源 - 通道0
  713. devContainer.devLight.setDigitalValue(1, productInfo.LightValue);
  714. errCode = 11;
  715. if (productInfo.ExposureTime > 0 || productInfo.Gain > 0)//相机曝光 增益
  716. {
  717. devContainer.devCamer1.setParam((float)(productInfo.ExposureTime > 0 ? productInfo.ExposureTime : -1), (float)(productInfo.Gain > 0 ? productInfo.Gain : -1));
  718. devContainer.devCamer2.setParam((float)(productInfo.ExposureTime > 0 ? productInfo.ExposureTime : -1), (float)(productInfo.Gain > 0 ? productInfo.Gain : -1));
  719. }
  720. errCode = 15;
  721. AddTextEvent(DateTime.Now,"扫码", $"品名({barCodeName}),配方设置完成:光源={productInfo.LightValue},曝光={productInfo.ExposureTime}");
  722. //注意,这里和修改页共享操作(UI操作),注意冲突
  723. this.Invoke(new System.Action(() =>
  724. {
  725. this.txtBarCode.Text = "";
  726. this.txtBarCodeName.Text= barCodeName;
  727. //txtBatchId.Text = record.BatchId;
  728. //txtReelId.Text = record.ReelId;
  729. this.numErpLen.Text = len;
  730. this.txtBatchId.Text = batchId;
  731. this.txtReelId.Text = reelId;
  732. //暂时全部放开
  733. //this.btnStart.Enabled = true;
  734. //this.btnEnd.Enabled = true;
  735. this.btnPause.Enabled = true;
  736. //
  737. this.swcDefectPauseForUser.Active = this.defectPauseForUser = productInfo.DefectPauseForUser;
  738. }));
  739. //
  740. pStopWatch.Restart();
  741. errCode = 19;
  742. }
  743. catch (Exception ex)
  744. {
  745. AddTextEvent(DateTime.Now,"扫码", $"异常({errCode}):{ex.Message}", WarningEnum.High);
  746. }
  747. };
  748. //相机回调出照片
  749. devContainer.devCamer1.ScanEvent = callBackScanMatEvent;
  750. devContainer.devCamer2.ScanEvent = callBackScanMatEvent;
  751. //devContainer.devScannerGentl1.ScanEventPath = callBackScanPathEvent;
  752. //devContainer.devScannerGentl2.ScanEventPath = callBackScanPathEvent;
  753. devContainer.devCamer1.PhotoNumCacheEvent = (num) =>
  754. {
  755. this.BeginInvoke(new System.Action(() =>
  756. {
  757. this.lblScanner1Cache.Text =num.ToString();
  758. }));
  759. };
  760. devContainer.devCamer2.PhotoNumCacheEvent = (num) =>
  761. {
  762. this.BeginInvoke(new System.Action(() =>
  763. {
  764. this.lblScanner2Cache.Text = num.ToString();
  765. }));
  766. };
  767. devContainer.devPlc.RuningStateChangeEvent = (runningState) =>
  768. {
  769. AddTextEvent(DateTime.Now,"PLC", $"当前状态为:{(runningState ? "运行中" : "暂停")}");
  770. if (runningState)
  771. this.startCommand();
  772. else
  773. this.pauseCommand();
  774. };
  775. //devContainer.devIOCard.INEvent = (i,value) =>
  776. //{
  777. // AddTextEvent(DateTime.Now,"I/O", $"INEvent 当前值:{i}-{value}");
  778. // if (compareIOInput(CMDName.启动按钮))
  779. // {
  780. // this.startCommand();
  781. // }
  782. // else if (compareIOInput(CMDName.暂停按钮))
  783. // {
  784. // this.pauseCommand(true);
  785. // }
  786. //};
  787. }
  788. else
  789. {
  790. AddTextEvent(DateTime.Now,"设备启动", $"启动失败,{msg}", WarningEnum.High);
  791. this.Invoke(new System.Action(() =>
  792. {
  793. this.btnOpen.Enabled = true;
  794. this.btnClose.Enabled = false;
  795. }));
  796. }
  797. };
  798. devContainer.WarningEvent = (now,level, msg) =>
  799. {
  800. AddTextEvent(DateTime.Now,$"设备事件{Thread.CurrentThread.ManagedThreadId}", msg, level, false);
  801. if (level == WarningEnum.High)
  802. Task.Run(() => warning(level, true));
  803. };
  804. devContainer.start(this.picScanner1, this.picScanner2);
  805. //devContainer.start(IntPtr.Zero,IntPtr.Zero);
  806. }
  807. private DataRow loadErpData(string barCode)
  808. {
  809. var paramList = new List<SugarParameter>() {
  810. new SugarParameter("@code", barCode)
  811. };
  812. Stopwatch stopwatch = Stopwatch.StartNew();
  813. var data = Utils.DBUtils.execSql(Config.ErpSql, paramList);
  814. if (data != null && data.Rows.Count < 1)
  815. {
  816. AddTextEvent(DateTime.Now,"Erp查询结果", $"{barCode}: 时长={stopwatch.ElapsedMilliseconds}ms, 无数据!", WarningEnum.Normal);
  817. return null;
  818. }
  819. AddTextEvent(DateTime.Now,"Erp查询结果", $"{barCode}: 时长={stopwatch.ElapsedMilliseconds}ms, {JsonConvert.SerializeObject(data.Rows[0])}", WarningEnum.Normal);
  820. return data.Rows[0];
  821. //Task.Run(() =>
  822. //{
  823. // try
  824. // {
  825. // var paramList = new List<SugarParameter>() {
  826. // new SugarParameter("@code", code)
  827. // };
  828. // Stopwatch stopwatch = Stopwatch.StartNew();
  829. // var data = Utils.DBUtils.execSql(Config.ErpSql, paramList);
  830. // AddTextEvent(DateTime.Now,"Erp查询结果", $"{code}: 时长={stopwatch.ElapsedMilliseconds}ms, {JsonConvert.SerializeObject(data.Rows[0])}", WarningEnum.Normal);
  831. // if (data != null && data.Rows.Count > 0)
  832. // {
  833. // this.Invoke(new System.Action(() =>
  834. // {
  835. // this.numErpLen.Text = data.Rows[0][0].ToString();
  836. // if (data.Columns.Count > 1) this.txtBatchId.Text = data.Rows[0][1].ToString();
  837. // if (data.Columns.Count > 2) this.txtReelId.Text = data.Rows[0][2].ToString();
  838. // }));
  839. // }
  840. // }
  841. // catch (Exception ex)
  842. // {
  843. // AddTextEvent(DateTime.Now,"Erp查询异常", $"{code}:{ex.Message}", WarningEnum.Low);
  844. // }
  845. //});
  846. }
  847. private class ScanPhotoInfo
  848. {
  849. /// <summary>
  850. ///
  851. /// </summary>
  852. /// <param name="_devIndex"></param>
  853. /// <param name="_photoIndex">1-n 第1张会把1改为0</param>
  854. /// <param name="_path"></param>
  855. public ScanPhotoInfo(int _devIndex,int _photoIndex,string _path)
  856. {
  857. devIndex = _devIndex;
  858. photoIndex = _photoIndex;
  859. path = _path;
  860. }
  861. public ScanPhotoInfo(int _devIndex, int _photoIndex, Mat _mat)
  862. {
  863. devIndex = _devIndex;
  864. photoIndex = _photoIndex;
  865. mat = _mat;
  866. }
  867. public int devIndex { get; set; }
  868. /// <summary>
  869. /// 0-n
  870. /// </summary>
  871. public int photoIndex { get; set; }
  872. public string path { get; set; }
  873. public Mat mat { get; set; }
  874. }
  875. //private List<Queue<ScanPhotoInfo>> scanPhotoQueue1 = new List<Queue<ScanPhotoInfo>>();
  876. /// <summary>
  877. /// 存放相机1/2的实时图像(3-多容错1帧)
  878. /// </summary>
  879. private ScanPhotoInfo[] scanPhotos=new ScanPhotoInfo[3];
  880. private void callBackScanPathEvent(int num, string path, int devIndex) //ScanEvent
  881. {
  882. AddTextEvent(DateTime.Now,"拍照", $"相机({devIndex})采集图索到图像({num}):{path}!");
  883. }
  884. bool firstTest = true;
  885. /// <summary>
  886. ///
  887. /// </summary>
  888. /// <param name="num">1-n</param>
  889. /// <param name="matone"></param>
  890. /// <param name="devIndex"></param>
  891. private void callBackScanMatEvent(int num, Mat matone, int devIndex) //ScanEvent
  892. {
  893. int errStep = 0;
  894. try
  895. {
  896. if (Config.Camer_Name == CamerDevNameEnum.埃科)
  897. {
  898. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"采集卡({devIndex}),图像({num})", WarningEnum.Low, false);
  899. Cv2.Flip(matone, matone, FlipMode.XY);//翻转
  900. Bitmap bitmap = BitmapConverter.ToBitmap(matone);
  901. this.BeginInvoke(new Action(() =>
  902. {
  903. //bitmap.Save($"d:\\{devIndex}_{num}.bmp", ImageFormat.Bmp);
  904. //显示图片
  905. if (devIndex == 0)
  906. {
  907. picScanner2.Image = bitmap;
  908. picScanner2.Refresh();
  909. }
  910. else
  911. {
  912. picScanner1.Image = bitmap;
  913. picScanner1.Refresh();
  914. }
  915. }));
  916. }
  917. errStep = 1;
  918. if (!devContainer.state || (currentState != CurrentStateEnum.运行中 && currentState != CurrentStateEnum.暂停))
  919. {
  920. matone.Dispose();
  921. return;
  922. }
  923. errStep = 2;
  924. lock (lockCurrKey)
  925. {
  926. if (currKey == 0 || !htTask.ContainsKey(currKey))
  927. {
  928. lock (lockScanPhoto)
  929. {
  930. if (scanPhotos[0] != null || scanPhotos[1] != null)
  931. scanPhotos[0] = scanPhotos[1] = scanPhotos[2] = null;
  932. }
  933. matone.Dispose();
  934. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"(图像{num})-未扫码,采集卡({devIndex}),图像丢弃!", WarningEnum.Low);
  935. return;
  936. }
  937. }
  938. errStep = 3;
  939. Records curRecord = Hashtable.Synchronized(htTask)[currKey] as Records;
  940. Device.PhotoLib.PhotoTask task;
  941. Mat myMat = matone;//.Clone();
  942. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"(图像{num})-采集卡({devIndex}),size:({myMat.Width}*{myMat.Height})({(myMat == null ? "A" : "B")})", WarningEnum.Low, false);
  943. //AddTextEvent(DateTime.Now,"拍照", $"Dev={devIndex},图像{num}-2");
  944. lock (lockScanPhoto)//多线程操作
  945. {
  946. if (scanPhotos[2] != null && scanPhotos[2].photoIndex == num)
  947. {
  948. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"相机图像不同步,急停中止(需停机重新开始,不可继续)!!!", WarningEnum.High);
  949. warning(WarningEnum.High);
  950. //重置...
  951. }
  952. if (scanPhotos[devIndex] != null) //添加一张容错
  953. {
  954. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"(图像{num})-采集卡({devIndex}) 容错一张图到队列!", WarningEnum.Low);
  955. scanPhotos[2] = new ScanPhotoInfo(devIndex, num, myMat);
  956. return;
  957. }
  958. errStep = 4;
  959. //--
  960. scanPhotos[devIndex] = new ScanPhotoInfo(devIndex, num, myMat);
  961. if (scanPhotos[0] == null || scanPhotos[1] == null)
  962. return;
  963. //
  964. //if (scanPhotos[0].photoIndex != scanPhotos[1].photoIndex)
  965. //{
  966. // if (scanPhotos[0].photoIndex > scanPhotos[1].photoIndex)
  967. // {
  968. // AddTextEvent(DateTime.Now,$"拍照{Thread.CurrentThread.ManagedThreadId}", $"(图像{num})-索引不一致),丢弃采集卡({scanPhotos[1].devIndex})中较小索引图像({scanPhotos[1].photoIndex})!", WarningEnum.High);
  969. // scanPhotos[1] = null;
  970. // }
  971. // else
  972. // {
  973. // AddTextEvent(DateTime.Now,$"拍照{Thread.CurrentThread.ManagedThreadId}", $"(图像{num})-索引不一致),丢弃采集卡({scanPhotos[0].devIndex})中较小索引图像({scanPhotos[0].photoIndex})!", WarningEnum.High);
  974. // scanPhotos[0] = null;
  975. // }
  976. // if (num > 1)
  977. // {
  978. // AddTextEvent(DateTime.Now,$"拍照{Thread.CurrentThread.ManagedThreadId}", $"相机图像不同步,急停中止(需停机重新开始,不可继续)!!!", WarningEnum.High);
  979. // warning(WarningEnum.High);
  980. // //重置...
  981. // }
  982. // return;
  983. //}
  984. //curRecord置新时,相机里最后一张图还是上次的计数器devIndex累计
  985. if (curRecord.ScannerPhotoCount == 0 && num >= 1)
  986. {
  987. devContainer.devCamer1.resetScanIndex();
  988. devContainer.devCamer2.resetScanIndex();
  989. scanPhotos[0].photoIndex = scanPhotos[1].photoIndex = 0;
  990. if (scanPhotos[2] != null)
  991. scanPhotos[2].photoIndex = 1;
  992. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"新任务开始,Dev={devIndex},图像({num})重置为图像(0)");
  993. }
  994. task = new Device.PhotoLib.PhotoTask()
  995. {
  996. scanPhotos0 = scanPhotos[0],
  997. scanPhotos1 = scanPhotos[1],
  998. };
  999. scanPhotos[0] = scanPhotos[1] = null;
  1000. if (scanPhotos[2] != null)//容错图前移到正常位置
  1001. {
  1002. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"(图像{scanPhotos[2].photoIndex})-采集卡({scanPhotos[2].devIndex}) 容错队列图前移。");
  1003. scanPhotos[scanPhotos[2].devIndex] = scanPhotos[2];
  1004. scanPhotos[2] = null;
  1005. }
  1006. curRecord.ScannerPhotoCount++;
  1007. errStep = 5;
  1008. }
  1009. //长度剩余提醒
  1010. if (Config.residueWarnningLen > 0 && curRecord.ErpLen > 0 && Config.residueWarnningLen >= curRecord.ErpLen - curRecord.Len)
  1011. {
  1012. AddTextEvent(DateTime.Now, $"告警{Thread.CurrentThread.ManagedThreadId}", $"已达剩余长度不足提醒!({curRecord.ErpLen - curRecord.Len}<={Config.residueWarnningLen})", WarningEnum.High);
  1013. #region 剩余提示暂停
  1014. if (!_residueWarnningLenStop)
  1015. {
  1016. _residueWarnningLenStop = true;
  1017. AddTextEvent(DateTime.Now, $"暂停{Thread.CurrentThread.ManagedThreadId}", $"已达剩余长度不足提醒!({curRecord.ErpLen - curRecord.Len}<={Config.residueWarnningLen}),进入暂停。");
  1018. if (!Config.StopPLC)
  1019. this.devContainer.devPlc.pauseDev();
  1020. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1021. {
  1022. //只是设备暂停,APP没暂停
  1023. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1024. devContainer.io_output(CMDName.黄灯输出);
  1025. devContainer.devIOCard.writeBitState(0, 1, true);
  1026. Task.Run(async () =>
  1027. {
  1028. await Task.Delay(500);
  1029. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1030. });
  1031. }
  1032. this.BeginInvoke(new System.Action(() =>
  1033. {
  1034. //warning(WarningEnum.Low, true);//暂停
  1035. MessageBox.Show($"已达剩余长度不足提醒!({curRecord.ErpLen - curRecord.Len}<={Config.residueWarnningLen}),进入暂停。", "警告",MessageBoxButtons.OK, MessageBoxIcon.Warning);
  1036. }));
  1037. }
  1038. #endregion
  1039. }
  1040. errStep = 6;
  1041. //厚度检测提示
  1042. if (curRecord.ProductInfo.OpenThicknessDetection)
  1043. {
  1044. if ((curRecord.Len - ThnDieLen) > curRecord.ProductInfo.ThicknessDetectionStopDis)
  1045. {
  1046. ThnDieLen = curRecord.Len;
  1047. AddTextEvent(DateTime.Now, $"厚度检测{Thread.CurrentThread.ManagedThreadId}", $"位置:{curRecord.Len}; 上次位置:{ThnDieLen}");
  1048. if (!Config.StopPLC)
  1049. this.devContainer.devPlc.pauseDev();
  1050. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1051. {
  1052. //只是设备暂停,APP没暂停
  1053. //devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1054. //devContainer.io_output(CMDName.黄灯输出);
  1055. devContainer.devIOCard.writeBitState(0, 1, true);
  1056. Task.Run(async () =>
  1057. {
  1058. await Task.Delay(500);
  1059. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1060. });
  1061. }
  1062. }
  1063. }
  1064. //
  1065. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"待处理图像队列:{curRecord.ScannerPhotoCount - curRecord.ScannerPhotoFinishCount}张", WarningEnum.Low, false);
  1066. if (task.scanPhotos0 != null && task.scanPhotos1 != null)
  1067. {
  1068. var scanPhoto = task.scanPhotos0 as ScanPhotoInfo;
  1069. curRecord.dicPhoto_Defect.TryAdd(scanPhoto.photoIndex, false);//加入索引,默认无瑕疵
  1070. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"图像索引:{scanPhoto.photoIndex},标识数:{curRecord.dicPhoto_Defect.Count}", WarningEnum.Low, false);
  1071. errStep = 7;
  1072. //暂停:瑕疵二次判断
  1073. if (this.defectPauseForUser)
  1074. {
  1075. int liPhotoIndex = scanPhoto.photoIndex - Config.defectPauseSkipPhotoCount;
  1076. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"Dev={devIndex},图像{scanPhoto.photoIndex} {liPhotoIndex}={scanPhoto.photoIndex}-{Config.defectPauseSkipPhotoCount};{JsonConvert.SerializeObject(curRecord.dicPhoto_Defect)}", WarningEnum.Low, false);
  1077. if (liPhotoIndex >= 0 && curRecord.dicPhoto_Defect[liPhotoIndex])
  1078. {
  1079. List<DefectInfo> lstEditDefect = curRecord.DefectInfoList.Where(m => m.PhotoIndex == liPhotoIndex).ToList();
  1080. AddTextEvent(DateTime.Now, $"暂停{Thread.CurrentThread.ManagedThreadId}", $"(图像{liPhotoIndex})已达观察台,瑕疵二次判断=》({string.Join(",", lstEditDefect.Select(m => m.Code).ToArray())})是否包含在({string.Join(",", curRecord.ProductInfo.DefectPauseOption.ToArray())})中。");
  1081. //瑕疵选项过滤
  1082. if (curRecord.ProductInfo.DefectPauseOption.Count == 0 || lstEditDefect.Where(x => curRecord.ProductInfo.DefectPauseOption.Contains(x.Code)).Count() > 0)
  1083. {
  1084. AddTextEvent(DateTime.Now, $"暂停{Thread.CurrentThread.ManagedThreadId}", $"(图像{liPhotoIndex})需瑕疵二次判断,已达观察台,进入暂停。");
  1085. if (!Config.StopPLC)
  1086. this.devContainer.devPlc.pauseDev();
  1087. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1088. {
  1089. //只是设备暂停,APP没暂停
  1090. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1091. devContainer.io_output(CMDName.黄灯输出);
  1092. devContainer.devIOCard.writeBitState(0, 1, true);
  1093. Task.Run(async () =>
  1094. {
  1095. await Task.Delay(500);
  1096. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1097. });
  1098. }
  1099. errStep = 8;
  1100. //不能使用同步Invoke方式,会使相机超时丢帧
  1101. this.BeginInvoke(new System.Action(() =>
  1102. {
  1103. int liDefectCount = lstEditDefect.Count;
  1104. FHome_Defect frmDefect = new FHome_Defect(lstEditDefect, defectTag[liPhotoIndex]);
  1105. if (frmDefect.ShowDialog() == DialogResult.OK)
  1106. {
  1107. defectTag.Remove(liPhotoIndex);
  1108. string oldCode;
  1109. for (int i = 0; i < this.uiDataGridView1.Rows.Count; i++)
  1110. {
  1111. if ((int)this.uiDataGridView1.Rows[i].Cells["colIndex"].Value != liPhotoIndex)
  1112. continue;
  1113. long uid = (long)this.uiDataGridView1.Rows[i].Cells["colUid"].Value;
  1114. foreach (var row in lstEditDefect)
  1115. {
  1116. AddTextEvent(DateTime.Now, $"暂停{Thread.CurrentThread.ManagedThreadId}", $"修改第({i + 1})行瑕疵名称,{uid} {row.uid}", WarningEnum.Low, false);
  1117. if (row.uid == uid)
  1118. {
  1119. oldCode = this.uiDataGridView1.Rows[i].Cells["colCode"].Value.ToString();
  1120. AddTextEvent(DateTime.Now, $"暂停{Thread.CurrentThread.ManagedThreadId}", $"修改第({i + 1})行瑕疵名称 ({this.uiDataGridView1.Rows[i].Cells["colDefectName"].Value})->({row.Name})");
  1121. this.uiDataGridView1.Rows[i].Cells["colCode"].Value = row.Code;
  1122. this.uiDataGridView1.Rows[i].Cells["colDefectName"].Value = row.Name;
  1123. //this.uiDataGridView1.Refresh();
  1124. if (!string.IsNullOrWhiteSpace(row.TagFilePath))
  1125. File.Move(row.TagFilePath, row.TagFilePath.Replace($"_类别{oldCode}", $"_类别{row.Code}"));//
  1126. break;
  1127. }
  1128. }
  1129. foreach (var item in frmDefect.lstDel)
  1130. {
  1131. if (item.uid == uid)
  1132. {
  1133. this.uiDataGridView1.Rows.RemoveAt(i);
  1134. i--;
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. foreach (var item in frmDefect.lstDel)
  1140. {
  1141. curRecord.DefectInfoList.Remove(item);
  1142. //删除忽略瑕疵小图
  1143. //if (!string.IsNullOrWhiteSpace(item.TagFilePath))
  1144. // File.Delete(item.TagFilePath);
  1145. }
  1146. //double len = (double)this.lblLen.Tag;
  1147. //this.reDrawDefectPoints(curRecord.DefectInfoList, new double[] { 0, Math.Round(curRecord.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len });
  1148. AddTextEvent(DateTime.Now, $"二次检测{Thread.CurrentThread.ManagedThreadId}", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {lstEditDefect.Count},总数{curRecord.DefectInfoList.Count}");
  1149. }
  1150. this.uiMiniPagination1.TotalCount = curRecord.DefectTotalCount = curRecord.DefectInfoList.Count;
  1151. //
  1152. //double len = Math.Round((res.photoIndex + 1) * bmpHeight * 1.0d / Config.cm2px_y + 0.005f, 2);
  1153. this.reDrawDefectPoints(curRecord.DefectInfoList);
  1154. errStep = 9;
  1155. //自动继续运行设备(这里临时暂停后不能再急停,否则无法继续)
  1156. if (!Config.StopPLC)
  1157. this.devContainer.devPlc.runDev();
  1158. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1159. {
  1160. if (!compareIOInput(CMDName.暂停按钮))
  1161. {
  1162. devContainer.io_output(CMDName.绿灯输出);
  1163. devContainer.io_output(CMDName.黄灯输出, false, true, 0);
  1164. this.devContainer.devIOCard.writeBitState(0, 0, true);
  1165. Task.Run(async () =>
  1166. {
  1167. await Task.Delay(500);
  1168. this.devContainer.devIOCard.writeBitState(0, 0, false);
  1169. });
  1170. }
  1171. }
  1172. }));
  1173. }
  1174. }
  1175. }
  1176. errStep = 10;
  1177. //以下判定放置于二次判定之后,因为二次判定可能会忽略部分检测项!!
  1178. //暂停:缺陷超标
  1179. //每百米告警判断???在此还是在收到新照片时触发???
  1180. if (curRecord.ProductInfo.DefectCountLimit > 0 && curRecord.DefectTotalCount >= curRecord.ProductInfo.DefectCountLimit && curRecord.DefectInfoList != null)
  1181. {
  1182. int liPhotoIndex = scanPhoto.photoIndex - Config.defectPauseSkipPhotoCount; //二次判定完的图片index
  1183. int compLen = 100 * 100;//每百米 to cm
  1184. int compCount = compLen * Config.cm2px_y / scanPhoto.mat.Height; //100m图像张数
  1185. //从上次告警后重新开始计算长度及数量
  1186. int defectCount = curRecord.DefectInfoList.Where(m => m.PhotoIndex >= curRecord.preWarningPhotoIndex && m.PhotoIndex >= (liPhotoIndex + 1 - compCount) && m.PhotoIndex <= liPhotoIndex).Count();
  1187. if (defectCount >= curRecord.ProductInfo.DefectCountLimit)
  1188. {
  1189. curRecord.preWarningPhotoIndex = liPhotoIndex + 1;
  1190. AddTextEvent(DateTime.Now, $"告警{Thread.CurrentThread.ManagedThreadId}", $"每百米瑕疵数量达到阈值!({defectCount}>={curRecord.ProductInfo.DefectCountLimit})", WarningEnum.High);
  1191. if (!Config.StopPLC)
  1192. this.devContainer.devPlc.pauseDev();
  1193. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1194. {
  1195. //只是设备暂停,APP没暂停
  1196. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1197. devContainer.io_output(CMDName.黄灯输出);
  1198. devContainer.devIOCard.writeBitState(0, 1, true);
  1199. Task.Run(async () =>
  1200. {
  1201. await Task.Delay(500);
  1202. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1203. });
  1204. }
  1205. }
  1206. errStep = 11;
  1207. }
  1208. //暂停:每个缺陷项不同长度检测数量报警
  1209. if (curRecord.DefectTotalCount > 0 && curRecord.DefectInfoList != null)
  1210. {
  1211. #if true
  1212. //按缺陷计算没X米多少缺陷报警
  1213. for (int i = 0; i < curRecord.ProductInfo.QualifiedLimitList.Count; i++)
  1214. {
  1215. var defectWarn = curRecord.ProductInfo.QualifiedLimitList[i];
  1216. if (defectWarn.DefectWarnLength > 0 || defectWarn.DefectWarnCnt > 0)
  1217. {
  1218. errStep = 12;
  1219. int liPhotoIndex = scanPhoto.photoIndex - Config.defectPauseSkipPhotoCount; //二次判定完的图片index
  1220. int warnLen = defectWarn.DefectWarnLength * 100;//每米 to cm
  1221. int warnCount = warnLen * Config.cm2px_y / scanPhoto.mat.Height; //计算图像张数
  1222. //从上次告警后重新开始计算长度及数量
  1223. int warnDefectCount = curRecord.DefectInfoList.Where(m => m.PhotoIndex >= curRecord.preWarningPhotoIndexByLabel[i] && m.PhotoIndex >= (liPhotoIndex + 1 - warnCount) && m.PhotoIndex <= liPhotoIndex).Count();
  1224. if (warnDefectCount >= defectWarn.DefectWarnCnt)
  1225. {
  1226. curRecord.preWarningPhotoIndexByLabel[i] = liPhotoIndex + 1;
  1227. AddTextEvent(DateTime.Now, $"告警{Thread.CurrentThread.ManagedThreadId}", $"每{defectWarn.DefectWarnLength}米{Config.getDefectName(defectWarn.Code)}瑕疵数量达到阈值!({warnDefectCount}>={defectWarn.DefectWarnCnt})", WarningEnum.High);
  1228. if (!Config.StopPLC)
  1229. this.devContainer.devPlc.pauseDev();
  1230. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1231. {
  1232. //只是设备暂停,APP没暂停
  1233. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1234. devContainer.io_output(CMDName.黄灯输出);
  1235. devContainer.devIOCard.writeBitState(0, 1, true);
  1236. Task.Run(async () =>
  1237. {
  1238. await Task.Delay(500);
  1239. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1240. });
  1241. }
  1242. }
  1243. }
  1244. }
  1245. #endif
  1246. }
  1247. #if false
  1248. //暂停:按等级分卷
  1249. if (curRecord.DefectTotalCount > 0 && curRecord.ProductInfo.GradeLimitList != null && curRecord.ProductInfo.GradeLimitList.Count > 0 && curRecord.DefectInfoList != null)
  1250. {
  1251. errStep = 13;
  1252. //按缺陷计算每X米多少缺陷分等级
  1253. for (int i = 0; i < curRecord.ProductInfo.GradeLimitList.Count; i++)
  1254. {
  1255. if (curRecord.ProductInfo.GradeLimitList[i].JudgeLength > 0)
  1256. {
  1257. errStep = 14;
  1258. int liPhotoIndex = scanPhoto.photoIndex - Config.defectPauseSkipPhotoCount; //二次判定完的图片index
  1259. double GrageLen = curRecord.ProductInfo.GradeLimitList[i].JudgeLength * 100;//每米 to cm
  1260. int warnCount = (int)(GrageLen * Config.cm2px_y) / scanPhoto.mat.Height; //计算图像张数
  1261. if (curRecord.GradeDifferentiateInfoList == null)
  1262. {
  1263. curRecord.GradeDifferentiateInfoList = new List<GradeDifferentiateInfo>();
  1264. }
  1265. GradeLimit item = curRecord.ProductInfo.GradeLimitList[i];
  1266. GradeDifferentiateInfo differentiateInfo = new GradeDifferentiateInfo();
  1267. //从上次告警后重新开始计算长度及数量
  1268. var allFind = curRecord.DefectInfoList.Where(m => m.PhotoIndex >= curRecord.preGradePhotoIndexByGradeIndex && m.PhotoIndex >= (liPhotoIndex + 1 - warnCount) && m.PhotoIndex <= liPhotoIndex).ToList();
  1269. int warnDefectCount = 0;
  1270. if (item.Code == "All")
  1271. warnDefectCount = allFind.Count();
  1272. else
  1273. {
  1274. warnDefectCount = allFind.Where(m => m.Code == item.Code).Count();
  1275. }
  1276. int GradeCount = 0;
  1277. if (item.E > 0 && warnDefectCount > item.E)
  1278. {
  1279. GradeCount = item.E;
  1280. differentiateInfo.GradeCode = "E";
  1281. }
  1282. else if (item.D > 0 && warnDefectCount > item.D)
  1283. {
  1284. GradeCount = item.D;
  1285. differentiateInfo.GradeCode = "D";
  1286. }
  1287. else if (item.C > 0 && warnDefectCount > item.C)
  1288. {
  1289. GradeCount = item.C;
  1290. differentiateInfo.GradeCode = "C";
  1291. }
  1292. else if (item.B > 0 && warnDefectCount > item.B)
  1293. {
  1294. GradeCount = item.B;
  1295. differentiateInfo.GradeCode = "B";
  1296. }
  1297. else if (item.A > 0 && warnDefectCount > item.A)
  1298. {
  1299. GradeCount = item.A;
  1300. differentiateInfo.GradeCode = "A";
  1301. }
  1302. else
  1303. {
  1304. //不需要分级,下一条
  1305. continue;
  1306. }
  1307. differentiateInfo.UseGradeLimit = item;
  1308. differentiateInfo.DefectCnt = warnDefectCount;
  1309. differentiateInfo.StartPhotoIndex = allFind.Min(x => x.PhotoIndex);
  1310. differentiateInfo.EndPhotoIndex = allFind.Max(x => x.PhotoIndex);
  1311. differentiateInfo.StartY = allFind.Min(x => x.CentreY) / 100 - OffsetCut;
  1312. differentiateInfo.EndY = allFind.Max(x => x.CentreY) / 100 + OffsetCut;
  1313. differentiateInfo.CutLen = differentiateInfo.EndY - differentiateInfo.StartY;
  1314. //记录新的判定开始位置
  1315. curRecord.preGradePhotoIndexByGradeIndex = liPhotoIndex + 1;
  1316. AddTextEvent(DateTime.Now, $"提示{Thread.CurrentThread.ManagedThreadId}", $"每{curRecord.ProductInfo.GradeLimitList[i].JudgeLength}米,瑕疵数量达到分级阈值!({warnDefectCount}>={GradeCount})", WarningEnum.Low);
  1317. curRecord.GradeDifferentiateInfoList.Add(differentiateInfo);
  1318. //标记裁切位置
  1319. this.BeginInvoke(new System.Action(() =>
  1320. {
  1321. reDrawDefectPointsAndCut(differentiateInfo.StartY, differentiateInfo.EndY, differentiateInfo.GradeCode);
  1322. }));
  1323. //裁切暂停提示
  1324. if (curRecord.ProductInfo.IsHintCutting)
  1325. {
  1326. AddTextEvent(DateTime.Now, $"提示", $"裁切 起始{differentiateInfo.StartY}-终点{differentiateInfo.EndY}", WarningEnum.Low);
  1327. if (!Config.StopPLC)
  1328. this.devContainer.devPlc.pauseDev();
  1329. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1330. {
  1331. //只是设备暂停,APP没暂停
  1332. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1333. devContainer.io_output(CMDName.黄灯输出);
  1334. devContainer.devIOCard.writeBitState(0, 1, true);
  1335. Task.Run(async () =>
  1336. {
  1337. await Task.Delay(500);
  1338. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1339. });
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. #endif
  1346. task.record = curRecord;
  1347. task.finishEvent = callBackPhotoEvent;
  1348. devContainer.libPhoto.add(task);
  1349. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"Dev={devIndex},图像{scanPhoto.photoIndex},已加入图像处理队列");
  1350. errStep = 21;
  1351. //Application.DoEvents();
  1352. }
  1353. }
  1354. catch (Exception e)
  1355. {
  1356. AddTextEvent(DateTime.Now, $"拍照{Thread.CurrentThread.ManagedThreadId}", $"errStep:{errStep}-{e.Message}", WarningEnum.High);
  1357. }
  1358. }
  1359. private void callBackPhotoEvent(Device.PhotoLib.PhotoTask task)
  1360. {
  1361. int errStep = 0;
  1362. Records curRecord = task.record;
  1363. ScanPhotoInfo scanPhotos0 = task.scanPhotos0 as ScanPhotoInfo;
  1364. ScanPhotoInfo scanPhotos1 = task.scanPhotos1 as ScanPhotoInfo;
  1365. Stopwatch stopWatch = new Stopwatch();
  1366. AddTextEvent(DateTime.Now,$"图像处理{Thread.CurrentThread.ManagedThreadId}", $"图像{scanPhotos0.photoIndex},ThreadId={Thread.CurrentThread.ManagedThreadId}", WarningEnum.Low, false);
  1367. string time = "";
  1368. stopWatch.Start();
  1369. try
  1370. {
  1371. if (scanPhotos0.mat.Height != scanPhotos1.mat.Height)
  1372. {
  1373. int xw, xh;
  1374. AddTextEvent(DateTime.Now,$"警告{Thread.CurrentThread.ManagedThreadId}", $"两相机采集图高度不一致({scanPhotos0.photoIndex}),dev1.Height={scanPhotos0.mat.Height},dev2.Height={scanPhotos1.mat.Height},重新resize...", WarningEnum.Low);
  1375. if (scanPhotos0.mat.Height > scanPhotos1.mat.Height)
  1376. scanPhotos1.mat = OpenCVUtil.resize(scanPhotos1.mat, scanPhotos0.mat.Width, scanPhotos0.mat.Height,out xw, out xh);
  1377. else
  1378. scanPhotos0.mat = OpenCVUtil.resize(scanPhotos0.mat, scanPhotos1.mat.Width, scanPhotos1.mat.Height, out xw, out xh);
  1379. }
  1380. //saveMatTest(scanPhotos0.mat, 1);
  1381. //saveMatTest(scanPhotos1.mat, 2);
  1382. //反转+相机索引调换
  1383. Mat mat0 = scanPhotos1.mat;
  1384. Mat mat1 = scanPhotos0.mat;
  1385. if (Config.ScannerReversalX)
  1386. {
  1387. Cv2.Flip(mat0, mat0, FlipMode.X);
  1388. errStep = 1;
  1389. Cv2.Flip(mat1, mat1, FlipMode.X);
  1390. time += $"X翻转({stopWatch.ElapsedMilliseconds})";
  1391. }
  1392. if (Config.ScannerReversalY)
  1393. {
  1394. Cv2.Flip(mat0, mat0, FlipMode.Y);
  1395. errStep = 2;
  1396. Cv2.Flip(mat1, mat1, FlipMode.Y);
  1397. time += $"Y翻转({stopWatch.ElapsedMilliseconds})";
  1398. }
  1399. firstTest = false;
  1400. //记录resize大小
  1401. //var resize = new System.Drawing.Size(mat0.Width * 2, mat0.Height);
  1402. int resizeWidth = devContainer.libDefect.GetWidthForResize(mat0.Width+ mat1.Width - Config.MiddleSuperposition);
  1403. if (resizeWidth == 0)
  1404. throw new Exception("GetWidthForResize result 0 失败!");
  1405. var resize = new System.Drawing.Size(resizeWidth, 4096);//固定8192*2张*4096
  1406. //裁边,两侧和中间重合部分
  1407. if (Config.MiddleSuperposition > 0)//中间重合部分
  1408. {
  1409. errStep = 3;
  1410. int width = mat0.Width - Config.MiddleSuperposition /2 ;
  1411. mat0 = OpenCVUtil.cutImage(mat0, 0, 0, width, mat0.Height);
  1412. time += $"->图1去重({stopWatch.ElapsedMilliseconds})";
  1413. width = mat1.Width - Config.MiddleSuperposition / 2;
  1414. mat1 = OpenCVUtil.cutImage(mat1, Config.MiddleSuperposition / 2, 0, width, mat1.Height);
  1415. time += $"->图2去重({stopWatch.ElapsedMilliseconds})";
  1416. }
  1417. AddTextEvent(DateTime.Now,$"裁边{Thread.CurrentThread.ManagedThreadId}",
  1418. $"(图像{scanPhotos0.photoIndex})-左图去重后:{mat0.Width}*{mat0.Height},右图:{mat1.Width}*{mat1.Height}," +
  1419. $"重复值:{Config.MiddleSuperposition},孔洞:{Config.MarginHoleWidth},cm2px:{Config.cm2px_x},resizeWidth:{resizeWidth}", WarningEnum.Low, false);
  1420. errStep = 4;
  1421. //mat0 = OpenCVUtil.getMaxInsetRect(mat0);
  1422. int marginWidth0, marginWidth1;
  1423. mat0 = OpenCVUtil.getMaxInsetRect2(mat0, true, Config.MarginHoleWidth,out marginWidth0);
  1424. //AddTextEvent(DateTime.Now,"裁边", $"(图像{scanPhotos0.photoIndex})-图0裁边后:{mat0.Width}*{mat0.Height}");
  1425. errStep = 5;
  1426. time += $"->图1裁边({stopWatch.ElapsedMilliseconds})";
  1427. //mat1 = OpenCVUtil.getMaxInsetRect(mat1);
  1428. mat1 = OpenCVUtil.getMaxInsetRect2(mat1,false, Config.MarginHoleWidth, out marginWidth1);
  1429. //AddTextEvent(DateTime.Now,"裁边", $"(图像{scanPhotos0.photoIndex})-图1裁边后:{mat1.Width}*{mat1.Height}");
  1430. errStep = 6;
  1431. time += $"->图2裁边({stopWatch.ElapsedMilliseconds})";
  1432. //水平合并l
  1433. Mat mat = OpenCVUtil.mergeImage_sameSize(new Mat[] { mat0, mat1 });//这里相机反装,左右反转下
  1434. AddTextEvent(DateTime.Now,$"裁边{Thread.CurrentThread.ManagedThreadId}", $"(图像{scanPhotos0.photoIndex})-边缘宽度:(左图)={marginWidth0},(右图)={marginWidth1}; 裁边去孔洞后:({mat0.Width}+{mat1.Width}={mat0.Width+ mat1.Width});合并后(去孔洞):{mat.Width}*{mat.Height}", WarningEnum.Low, false);
  1435. float widthRatio = mat.Width * 1.0f / resize.Width;//宽度比例
  1436. time += $"->图1+2合并({stopWatch.ElapsedMilliseconds})";
  1437. //门幅更新(含两侧孔洞)x,y cm
  1438. float faceWidthX_cm = (float)Math.Round((scanPhotos0.photoIndex+1) * mat.Height * 1.0f / Config.cm2px_y,2);
  1439. float faceWidthY_cm = (float)Math.Round((mat.Width + Config.MarginHoleWidth * 2) * 1.0f / Config.cm2px_x, 2);
  1440. faceWidthX_cm = (float)Math.Round(faceWidthX_cm, 2);
  1441. faceWidthY_cm = (float)Math.Round(faceWidthY_cm, 2);
  1442. if (curRecord.FaceWidthMin==0 || curRecord.FaceWidthMin > faceWidthY_cm)
  1443. curRecord.FaceWidthMin = faceWidthY_cm;
  1444. if (curRecord.FaceWidthMax < faceWidthY_cm)
  1445. curRecord.FaceWidthMax = faceWidthY_cm;
  1446. var point = new float[] { faceWidthX_cm, faceWidthY_cm };// new System.Drawing.PointF(faceWidthX_cm, faceWidthY_cm);
  1447. AddTextEvent(DateTime.Now,$"门幅{Thread.CurrentThread.ManagedThreadId}", $"(图像{scanPhotos0.photoIndex})-({scanPhotos0.photoIndex})位置:{point[0]}; 幅宽:{point[1]}", WarningEnum.Low, false);
  1448. curRecord.FacePointList.Add(point);
  1449. reDrawFaceWidth(curRecord.FacePointList,
  1450. new double[] { 0, Math.Round(point[0] + 0.005f, 2) },
  1451. new double[] { curRecord.FaceWidthMin, Math.Round(curRecord.FaceWidthMax + 0.005f, 2) });
  1452. errStep = 7;
  1453. time += $"->门幅刷新({stopWatch.ElapsedMilliseconds})";
  1454. //去除两侧孔洞(门幅计算时不能去除)
  1455. //if (Config.MarginHoleWidth > 0)
  1456. // mat = OpenCVUtil.cutImage(mat, Config.MarginHoleWidth, 0, mat.Width - Config.MarginHoleWidth * 2, mat.Height);
  1457. //计算速度
  1458. double lenMi = Math.Round(faceWidthX_cm / 100, 2);
  1459. curRecord.Len = lenMi;
  1460. curRecord.TimeLen= pStopWatch.ElapsedMilliseconds / 1000.0d / 60.0d;//总时间 分
  1461. this.BeginInvoke(new System.Action(() =>
  1462. {
  1463. this.lblLen.Text = $"{lenMi}米";
  1464. this.lblLen.Tag = faceWidthX_cm;
  1465. this.lblSpeed.Text = $"速度:{Math.Round(lenMi / curRecord.TimeLen, 2)}米/分";
  1466. this.uilbKF.Text = $"当前幅宽:{faceWidthY_cm}cm";
  1467. }));
  1468. //
  1469. errStep = 9;
  1470. time += $"->速度刷新({stopWatch.ElapsedMilliseconds})";
  1471. //----缺陷队列
  1472. int oxw, oxh;
  1473. mat = OpenCVUtil.resize(mat, resize.Width, resize.Height, out oxw, out oxh);
  1474. AddTextEvent(DateTime.Now,$"图像处理{Thread.CurrentThread.ManagedThreadId}", $"(图像{scanPhotos0.photoIndex})-合成图resize后:{mat.Width}*{mat.Height}-{oxw}*{oxh}", WarningEnum.Low, false);
  1475. devContainer.libDefect.add(new Device.DefectLib.DefectTask()
  1476. {
  1477. modelName= curRecord.ProductInfo.ModelName,
  1478. record = curRecord,
  1479. bmp = mat,
  1480. bmpTag = mat.Clone(),
  1481. photoIndex = scanPhotos0.photoIndex,//0-n 首张必需为0,因下面计算长度是从0开始
  1482. widthRatio = widthRatio,
  1483. qualifiedLimitList = curRecord.ProductInfo.QualifiedLimitList,
  1484. finishEvent = callBackDefectEvent,
  1485. xw = oxw,
  1486. });
  1487. errStep = 10;
  1488. time += $"->加入瑕疵待检队列({stopWatch.ElapsedMilliseconds})";
  1489. }
  1490. catch (Exception ex)
  1491. {
  1492. curRecord.ScannerPhotoFinishCount++;//失败时不能因数量不一致无法保存
  1493. AddTextEvent(DateTime.Now,$"图像处理{Thread.CurrentThread.ManagedThreadId}", $"异常({errStep}):(图像{scanPhotos0.photoIndex})-{ex.Message}", WarningEnum.High);
  1494. string dirPath = FileUtil.initFolder($"{Config.ImagePath}{curRecord.BatchId}_{curRecord.ReelId}\\Err\\");
  1495. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(scanPhotos0.mat).Save($"{dirPath}{scanPhotos0.photoIndex}_0_Step{errStep}.bmp", ImageFormat.Bmp);
  1496. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(scanPhotos1.mat).Save($"{dirPath}{scanPhotos1.photoIndex}_1_Step{errStep}.bmp", ImageFormat.Bmp);
  1497. }
  1498. finally
  1499. {
  1500. AddTextEvent(DateTime.Now,$"图像处理{Thread.CurrentThread.ManagedThreadId}", $"(图像{scanPhotos0.photoIndex})-进度计时:{time}", WarningEnum.Low, false);
  1501. scanPhotos0.mat.Dispose();
  1502. scanPhotos1.mat.Dispose();
  1503. scanPhotos0 = scanPhotos1 = null;
  1504. task = null;
  1505. //System.GC.Collect();
  1506. }
  1507. }
  1508. private void callBackDefectEvent(Device.DefectLib.DefectTask res)
  1509. {
  1510. {
  1511. int step = 0;
  1512. try
  1513. {
  1514. AddTextEvent(DateTime.Now,$"检测完成{Thread.CurrentThread.ManagedThreadId}", $"图像队列:{res.record.ScannerPhotoFinishCount+1}/{res.record.ScannerPhotoCount} (图像{res.photoIndex})检测结果:{res.isSucceed}", WarningEnum.Low, false);
  1515. string dirPath = FileUtil.initFolder($"{Config.ImagePath}{res.record.BatchId}_{res.record.ReelId}\\");
  1516. string dirSourcePath = FileUtil.initFolder($"{Config.ImagePath}{res.record.BatchId}_{res.record.ReelId}\\源图\\");
  1517. //Cv2.Flip(res.bmp, res.bmp, FlipMode.XY);//翻转
  1518. if (Config.IsSaveAllImage)//保存所有原图
  1519. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save($"{dirSourcePath}{res.photoIndex}.bmp", ImageFormat.Bmp);
  1520. if (res.isSucceed)
  1521. {
  1522. step = 1;
  1523. AddTextEvent(DateTime.Now,$"检测完成{Thread.CurrentThread.ManagedThreadId}", $"(图像{res.photoIndex})-瑕疵检测完成,共{res.excelTable.Rows.Count}个瑕疵!各环节用时:{string.Join(",",res.stopwatch)}", WarningEnum.Low, false);
  1524. //AddTextEvent(DateTime.Now,$"打标完成", $"第 ({res.photoIndex}) 张照片,计算过程:{res.resultInfo}");
  1525. //if (!Config.IsSaveAllImage && Config.IsSaveDefectSourceImage)
  1526. // OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save($"{dirSourcePath}{res.photoIndex}.bmp", ImageFormat.Bmp);
  1527. step = 2;
  1528. if (res.excelTable.Rows.Count > 0)
  1529. {
  1530. res.record.dicPhoto_Defect[res.photoIndex] = true;//改为此图有瑕疵
  1531. //有瑕疵打标图必需保存 Jpeg
  1532. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmpTag).Save($"{dirPath}{res.photoIndex}_tag.jpg", ImageFormat.Jpeg);
  1533. if (!Config.IsSaveAllImage && Config.IsSaveDefectSourceImage)
  1534. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save($"{dirSourcePath}{res.photoIndex}.bmp", ImageFormat.Bmp);
  1535. step = 3;
  1536. res.record.DefectTotalCount += res.excelTable.Rows.Count;
  1537. if (res.record.DefectInfoList == null)
  1538. res.record.DefectInfoList = new List<DefectInfo>();
  1539. step = 4;
  1540. JObject defectNameInfo;
  1541. DefectInfo defectInfo=null;
  1542. List<object[]> dataRowlist=new List<object[]>();
  1543. long preTicks = pStopWatch.ElapsedMilliseconds;// DateTime.Now.Ticks;
  1544. for (int i = 0; i < res.lstDefectBmp.Count; i++)
  1545. {
  1546. step = 5 + i * 10;
  1547. defectNameInfo = Config.getDefectItem(int.Parse(res.excelTable.Rows[i]["类别"].ToString()));
  1548. defectInfo = new DefectInfo
  1549. {
  1550. PhotoIndex = res.photoIndex,
  1551. Code = defectNameInfo.Value<string>("code"),
  1552. Name = defectNameInfo.Value<string>("name"),
  1553. X = double.Parse(res.excelTable.Rows[i]["X"].ToString()),//cm
  1554. Y = Math.Round((res.photoIndex * res.bmp.Height * 1.0d / Config.cm2px_y + double.Parse(res.excelTable.Rows[i]["Y"].ToString())), 2),//cm
  1555. Width = double.Parse(res.excelTable.Rows[i]["W"].ToString()),//cm
  1556. Height = double.Parse(res.excelTable.Rows[i]["H"].ToString()),//cm
  1557. ZXD = double.Parse(res.excelTable.Rows[i]["置信度"].ToString()),
  1558. Contrast = double.Parse(res.excelTable.Rows[i]["对比度"].ToString()),
  1559. Target = int.Parse(res.excelTable.Rows[i]["目标"].ToString()),
  1560. image = BitmapConverter.ToBitmap(res.lstDefectBmp[i])
  1561. };
  1562. defectInfo.ModifyUserCode = defectInfo.CreateUserCode = res.record.CreateUserCode;
  1563. step = 6 + i * 10;
  1564. res.record.DefectInfoList.Add(defectInfo);
  1565. defectInfo.uid = preTicks++;// res.record.DefectInfoList.Count;//程序中的唯一索引,用于移除用索引
  1566. //AddTextEvent(DateTime.Now,$"打标完成", $"第{i}个缺陷:{ JsonConvert.SerializeObject(defectInfo)}; Y={res.photoIndex * res.bmp.Height * 1.0d / Config.cm2px_y}+{res.excelTable.Rows[i]["Y"].ToString()}");
  1567. step = 7 + i * 10;
  1568. if (!defectTag.ContainsKey(res.photoIndex))
  1569. {
  1570. defectTag.Add(res.photoIndex, res.bmpTag.Clone());
  1571. }
  1572. //保存打标小图
  1573. if (Config.IsSaveDefectCutImage)
  1574. {
  1575. string filename = $"{dirPath}\\{res.photoIndex}_X{defectInfo.X}_Y{defectInfo.Y}_W{defectInfo.Width}_H{defectInfo.Height}_目标{defectInfo.Target}_类别{defectInfo.Code}_置信度{defectInfo.ZXD}.jpg";
  1576. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.lstDefectBmp[i]).Save(filename, ImageFormat.Jpeg);
  1577. defectInfo.TagFilePath = filename;
  1578. }
  1579. step = 8 + i * 10;
  1580. res.lstDefectBmp[i].Dispose();
  1581. dataRowlist.Add(new object[]{ defectInfo.uid,defectInfo.Code, defectInfo.PhotoIndex,defectInfo.Name,
  1582. defectInfo.CentreX, defectInfo.CentreY / 100,defectInfo.Width * 10,defectInfo.Height * 10, defectInfo.Area * 100, defectInfo.ZXD, defectInfo.Contrast});
  1583. //更新UI
  1584. //this.Invoke(new System.Action(() =>
  1585. //{
  1586. // this.uiDataGridView1.Rows.Insert(0, );
  1587. // this.uiMiniPagination1.TotalCount = res.record.DefectInfoList.Count;
  1588. // if (this.uiDataGridView1.Rows.Count == 1)
  1589. // this.picDefectImage.loadImage(defectInfo.image);
  1590. //}));
  1591. step = 9 + i * 10;
  1592. //告警判断???在此还是在收到新照片时触发???
  1593. if (res.record.ProductInfo.DefectAreaLimit > 0 && defectInfo.Area>=res.record.ProductInfo.DefectAreaLimit)
  1594. {
  1595. AddTextEvent(DateTime.Now,$"告警{Thread.CurrentThread.ManagedThreadId}", $"瑕疵面积达到阈值!({defectInfo.Area}>={res.record.ProductInfo.DefectAreaLimit})", WarningEnum.High);
  1596. if (!Config.StopPLC)
  1597. this.devContainer.devPlc.pauseDev();
  1598. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1599. {
  1600. //只是设备暂停,APP没暂停
  1601. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1602. devContainer.io_output(CMDName.黄灯输出);
  1603. devContainer.devIOCard.writeBitState(0, 1, true);
  1604. Task.Run(async () =>
  1605. {
  1606. await Task.Delay(500);
  1607. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1608. });
  1609. }
  1610. }
  1611. }
  1612. AddTextEvent(DateTime.Now,$"检测完成{Thread.CurrentThread.ManagedThreadId}", "更新UI", WarningEnum.Low, false);
  1613. //更新UI
  1614. int bmpHeight = res.bmp.Height;
  1615. this.BeginInvoke(new System.Action(() =>
  1616. {
  1617. //这里显示了第1张图的最后一个缺陷
  1618. if (this.uiDataGridView1.Rows.Count == 0 && defectInfo!=null)
  1619. this.picDefectImage.loadImage(defectInfo.image);
  1620. foreach (var rowItem in dataRowlist)
  1621. this.uiDataGridView1.Rows.Insert(0, rowItem);
  1622. this.uiMiniPagination1.TotalCount = res.record.DefectInfoList.Count;
  1623. //
  1624. double len = Math.Round((res.photoIndex + 1) * bmpHeight * 1.0d / Config.cm2px_y+0.005f, 2);
  1625. this.reDrawDefectPoints(res.record.DefectInfoList, new double[] { 0, Math.Round(res.record.FaceWidthMax+ 0.005f, 2) }, new double[] { 0, len });
  1626. }));
  1627. step = 9;
  1628. AddTextEvent(DateTime.Now,$"检测完成{Thread.CurrentThread.ManagedThreadId}", "保存CSV", WarningEnum.Low, false);
  1629. //保存CSV
  1630. bool b = Utils.ExcelUtil.DataTable2CSV($"{dirPath}{res.photoIndex}.csv", res.excelTable);
  1631. //AddTextEvent(DateTime.Now,$"打标完成", $"{res.tag}.xlsx {(b ? "保存成功!" : "保存失败!")}");
  1632. step = 10;
  1633. #if 转移判定位置
  1634. //每百米告警判断???在此还是在收到新照片时触发???
  1635. if (res.record.ProductInfo.DefectCountLimit > 0 && res.record.DefectTotalCount >= res.record.ProductInfo.DefectCountLimit)
  1636. {
  1637. int compLen = 100 * 100;//每百米 to cm
  1638. int compCount = compLen * Config.cm2px_y / res.bmp.Height;
  1639. //从上次告警后重新开始计算长度及数量
  1640. int defectCount = res.record.DefectInfoList.Where(m => m.PhotoIndex >= res.record.preWarningPhotoIndex && m.PhotoIndex >= res.photoIndex+1 - compCount).Count();
  1641. if (defectCount >= res.record.ProductInfo.DefectCountLimit)
  1642. {
  1643. res.record.preWarningPhotoIndex = res.photoIndex + 1;
  1644. AddTextEvent(DateTime.Now,$"告警{Thread.CurrentThread.ManagedThreadId}", $"每百米瑕疵数量达到阈值!({defectCount}>={res.record.ProductInfo.DefectCountLimit})", WarningEnum.High);
  1645. }
  1646. step = 11;
  1647. #if false
  1648. //按缺陷计算没X米多少缺陷报警
  1649. for (int i = 0; i < res.record.ProductInfo.QualifiedLimitList.Count; i++)
  1650. {
  1651. var defectWarn = res.record.ProductInfo.QualifiedLimitList[i];
  1652. if (defectWarn.DefectWarnLength > 0 || defectWarn.DefectWarnCnt >0)
  1653. {
  1654. step = 12;
  1655. int warnLen = defectWarn.DefectWarnLength * 100;//每百米 to cm
  1656. int warnCount = warnLen * Config.cm2px_y / res.bmp.Height;
  1657. //从上次告警后重新开始计算长度及数量
  1658. int warnDefectCount = res.record.DefectInfoList.Where(m => m.PhotoIndex >= res.record.preWarningPhotoIndexByLabel[i] && m.PhotoIndex >= res.photoIndex + 1 - warnCount).Count();
  1659. if (warnDefectCount >= defectWarn.DefectWarnCnt)
  1660. {
  1661. res.record.preWarningPhotoIndexByLabel[i] = res.photoIndex + 1;
  1662. AddTextEvent(DateTime.Now, $"告警{Thread.CurrentThread.ManagedThreadId}", $"每{defectWarn.DefectWarnLength}米{Config.getDefectName(defectWarn.Code)}瑕疵数量达到阈值!({warnDefectCount}>={defectWarn.DefectWarnCnt})", WarningEnum.High);
  1663. }
  1664. }
  1665. }
  1666. #endif
  1667. }
  1668. #endif
  1669. }
  1670. }
  1671. else
  1672. {
  1673. AddTextEvent(DateTime.Now,$"打标失败{Thread.CurrentThread.ManagedThreadId}", $"(图像{res.photoIndex})-瑕疵检测失败!TId={Thread.CurrentThread.ManagedThreadId}");
  1674. }
  1675. res.bmp.Dispose();
  1676. res.bmpTag.Dispose();
  1677. res.bmps_cut = null;
  1678. res.excelTable.Dispose();
  1679. }
  1680. catch (Exception ex)
  1681. {
  1682. AddTextEvent(DateTime.Now,$"打标失败{Thread.CurrentThread.ManagedThreadId}", $"(图像{res.photoIndex})-瑕疵检测异常({step}):{ex.Message},TId={Thread.CurrentThread.ManagedThreadId}");
  1683. }
  1684. finally
  1685. {
  1686. res.record.ScannerPhotoFinishCount++;
  1687. int liScannerPhotoFinishCount = res.record.ScannerPhotoFinishCount;
  1688. int liScannerPhotoCount = res.record.ScannerPhotoCount;
  1689. AddTextEvent(DateTime.Now,$"检测完成{Thread.CurrentThread.ManagedThreadId}", $"{liScannerPhotoFinishCount}/{liScannerPhotoCount}", WarningEnum.Low, false);
  1690. //this.BeginInvoke(new System.Action(() =>
  1691. //{
  1692. // this.lblWaitImageCount.Text = $"{liScannerPhotoCount - liScannerPhotoFinishCount}";
  1693. //}));
  1694. res = null;
  1695. System.GC.Collect();
  1696. }
  1697. }
  1698. }
  1699. private bool _isDefect = false;
  1700. private async void saveCurrRecord(int key, string batchId, string reelId, double erpLen)
  1701. {
  1702. Records model=null;
  1703. int step = 0;
  1704. try
  1705. {
  1706. _isDefect = true;
  1707. AddTextEvent(DateTime.Now,"入库", $"准备入库key={key}");
  1708. //foreach (int itemKey in htTask.Keys)
  1709. // AddTextEvent(DateTime.Now,"入库", $"htTask {itemKey}");
  1710. step = 1;
  1711. model = Hashtable.Synchronized(htTask)[key] as Records;
  1712. //model = htTask[key] as Records;
  1713. step = 2;
  1714. if (model.Len == 0)
  1715. {
  1716. _isDefect = false;
  1717. return;
  1718. }
  1719. model.BatchId = batchId;
  1720. model.ReelId = reelId;
  1721. model.ErpLen = erpLen;
  1722. while (model.ScannerPhotoCount > model.ScannerPhotoFinishCount)
  1723. await Task.Delay(100);
  1724. step = 3;
  1725. //计算等级标准
  1726. List<GradeLimit> gradeLimitList = model.ProductInfo.GradeLimitList;
  1727. if (gradeLimitList!=null && gradeLimitList.Count > 0)
  1728. {
  1729. step = 4;
  1730. int count;
  1731. foreach(GradeLimit item in gradeLimitList)
  1732. {
  1733. if((model.DefectInfoList != null)&&(model.DefectInfoList.Count >0))
  1734. count = model.DefectInfoList.Where(m => m.Code == item.Code).Count();
  1735. else
  1736. count = 0;
  1737. if (count <= item.A && model.Grade <= 1) model.Grade = 1;
  1738. else if (count <= item.B && item.B > 0 && model.Grade <= 2) model.Grade = 2;
  1739. else if (count <= item.C && item.C > 0 && model.Grade <= 3) model.Grade = 3;
  1740. else if (count <= item.D && item.D > 0 && model.Grade <= 4) model.Grade = 4;
  1741. else if (count <= item.E && item.E > 0 && model.Grade <= 5) model.Grade = 5;
  1742. else if (count>0) model.Grade = 6;//不合格
  1743. AddTextEvent(DateTime.Now,"标准判断", $"({key}) 批号({model.BatchId}),标准={(char)(model.Grade + 64)} [{item.Code}:{count};A<={item.A};B<={item.B};C<={item.C};D<={item.D};E<={item.E}]");
  1744. }
  1745. step = 5;
  1746. }
  1747. model.Qualified = (model.Grade < 6);//是否合格
  1748. if (!svcRecord.InsertNav(model))
  1749. throw new Exception("写库失败!");
  1750. AddTextEvent(DateTime.Now,"入库完成", $"({key}) 批号({model.BatchId})已完成检测。");
  1751. htTask.Remove(key);
  1752. _isDefect = false;
  1753. }
  1754. catch (Exception ex)
  1755. {
  1756. _isDefect = false;
  1757. if (model==null)
  1758. AddTextEvent(DateTime.Now,"入库失败", $"记录({key})不存在{step}!" + ex.Message, WarningEnum.High);
  1759. else
  1760. AddTextEvent(DateTime.Now,"入库失败", $"({key}) 批号({model.BatchId})检测完成,但保存检测记录失败{step}:" + ex.Message, WarningEnum.High);
  1761. warning(WarningEnum.High, true);//暂停
  1762. }
  1763. }
  1764. //停机
  1765. private void btnClose_Click(object sender, EventArgs e)
  1766. {
  1767. if (currentState == CurrentStateEnum.运行中)
  1768. {
  1769. UIMessageTip.ShowWarning("请先结束或暂停设备运行后再停机!", 2000);
  1770. return;
  1771. }
  1772. if(_isDefect)
  1773. {
  1774. UIMessageTip.ShowWarning("还在检测处理中,等待完成再停机!", 2000);
  1775. return;
  1776. }
  1777. AddTextEvent(DateTime.Now,"停机", "停机中...");
  1778. this.btnStart.Enabled = this.btnEnd.Enabled = this.btnPause.Enabled = false;
  1779. this.btnClose.Enabled = false;
  1780. this.btnOpen.Enabled = true;
  1781. tcbarLightValue.Enabled = false;
  1782. if (devContainer.state && devContainer.devIOCard.IsInit)
  1783. {
  1784. devContainer.devIOCard.reset();
  1785. devContainer.io_output(CMDName.IO默认输出);
  1786. }
  1787. devContainer.stop();
  1788. currentState = CurrentStateEnum.初始;//应该是待机
  1789. this.resetUIValue();
  1790. AddTextEvent(DateTime.Now,"停机", "停机完成。");
  1791. }
  1792. //启动
  1793. private void btnStart_Click(object sender, EventArgs e)
  1794. {
  1795. AddTextEvent(DateTime.Now,"启动", "下发启动指令...");
  1796. if (!Config.StopPLC)
  1797. this.devContainer.devPlc.runDev();
  1798. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1799. {
  1800. if (!compareIOInput(CMDName.暂停按钮))//硬件急停
  1801. {
  1802. AddTextEvent(DateTime.Now, "启动", "下发IO指令...");
  1803. this.devContainer.devIOCard.writeBitState(0, 0, true);
  1804. this.startCommand();
  1805. Task.Run(async () =>
  1806. {
  1807. await Task.Delay(500);
  1808. this.devContainer.devIOCard.writeBitState(0, 0, false);
  1809. });
  1810. }
  1811. else
  1812. AddTextEvent(DateTime.Now, "启动", "设备急停!");
  1813. }
  1814. }
  1815. private void btnPause_Click(object sender, EventArgs e)
  1816. {
  1817. AddTextEvent(DateTime.Now,"暂停", "下发暂停指令...");
  1818. if (!Config.StopPLC)
  1819. this.devContainer.devPlc.pauseDev();
  1820. else if (!Config.StopIO && devContainer.devIOCard.IsInit)
  1821. {
  1822. //if (!compareIOInput(CMDName.暂停按钮))
  1823. this.devContainer.devIOCard.writeBitState(0, 1, true);
  1824. this.pauseCommand();//输出暂停不会触发输入暂停
  1825. Task.Run(async () =>
  1826. {
  1827. await Task.Delay(500);
  1828. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1829. });
  1830. }
  1831. }
  1832. private void startCommand()
  1833. {
  1834. if (!devContainer.state || currentState == CurrentStateEnum.运行中)
  1835. return;
  1836. if (devContainer.devIOCard.IsInit)
  1837. {
  1838. //devContainer.io_output(CMDName.启动按钮);
  1839. devContainer.io_output(CMDName.绿灯输出);
  1840. devContainer.io_output(CMDName.黄灯输出, false, true, 0);
  1841. devContainer.io_output(CMDName.红灯输出, false, true, 0);
  1842. devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0);
  1843. //devContainer.io_output(CMDName.暂停按钮, false, true, 0);
  1844. //devContainer.io_output(CMDName.黄灯输出, false, true, 0);
  1845. }
  1846. //运行中和暂停时都可正常接收扫描器触发新卷
  1847. //暂停-》继续
  1848. if (currentState == CurrentStateEnum.暂停)
  1849. {
  1850. AddTextEvent(DateTime.Now,"启动", $"暂停 -> 继续");
  1851. currentState = CurrentStateEnum.运行中;
  1852. Task.Run(() =>
  1853. {
  1854. if (currKey > 0)
  1855. pStopWatch.Start();
  1856. //写I/O启动。。。
  1857. //继续读取编译器和门幅等
  1858. //int nextStepId = currProcessIndex;
  1859. //do
  1860. //{
  1861. // currentState = CurrentStateEnum.运行中;
  1862. // nextStepId = nextProcess(currProductModel, nextStepId);
  1863. //} while (nextStepId >= 0 && !isBreakProcessRun());
  1864. });
  1865. }
  1866. else//首次开始/结束后重新开始
  1867. {
  1868. //校正从复位-》运行,不会新启动
  1869. resetUIValue();
  1870. AddTextEvent(DateTime.Now,"启动", "等待扫码...");
  1871. currentState = CurrentStateEnum.运行中;
  1872. defectTag.Clear();
  1873. ThnDieLen = 0;
  1874. }
  1875. this.Invoke(new System.Action(() =>
  1876. {
  1877. this.btnStart.Enabled = false;
  1878. this.btnEnd.Enabled = this.btnPause.Enabled = true;
  1879. }));
  1880. }
  1881. private void pauseCommand(bool buzzer = false)
  1882. {
  1883. if(!devContainer.state || currentState != CurrentStateEnum.运行中)
  1884. return;
  1885. //写IO
  1886. if (devContainer.devIOCard.IsInit)
  1887. {
  1888. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  1889. if (buzzer)
  1890. {
  1891. devContainer.io_output(CMDName.红灯输出);
  1892. devContainer.io_output(CMDName.蜂鸣器输出);
  1893. }
  1894. else
  1895. devContainer.io_output(CMDName.黄灯输出);
  1896. //devContainer.io_output(CMDName.暂停按钮, false, true, 0);
  1897. //devContainer.io_output(CMDName.黄灯输出, false, true, 0);
  1898. }
  1899. //停止读取
  1900. //AddTextEvent(DateTime.Now,"暂停", "暂停!");
  1901. pStopWatch.Stop();
  1902. currentState = CurrentStateEnum.暂停;
  1903. this.Invoke(new System.Action(() =>
  1904. {
  1905. this.btnStart.Enabled = this.btnEnd.Enabled = true;
  1906. this.btnPause.Enabled = false;
  1907. }));
  1908. }
  1909. //完成
  1910. private void btnEnd_Click(object sender, EventArgs e)
  1911. {
  1912. AddTextEvent(DateTime.Now,"结束验布", "结束验布!");
  1913. if (!Config.StopPLC)
  1914. this.devContainer.devPlc.pauseDev();
  1915. else if (!Config.StopIO)
  1916. {
  1917. this.devContainer.devIOCard.writeBitState(0, 1, true);
  1918. Task.Run(async () =>
  1919. {
  1920. await Task.Delay(500);
  1921. this.devContainer.devIOCard.writeBitState(0, 1, false);
  1922. });
  1923. }
  1924. currentState = CurrentStateEnum.初始;
  1925. UILocalize.OK = "是";
  1926. UILocalize.Cancel = "否";
  1927. if (currKey > 0 && ShowAskDialog("提示", "是否保存当前检测结果?"))
  1928. {
  1929. string szBatchId, szReelId;
  1930. double ldErpLen;
  1931. szBatchId = txtBatchId.Text.Trim();
  1932. szReelId = txtReelId.Text.Trim();
  1933. ldErpLen = numErpLen.IsEmpty ? 0 : Convert.ToDouble(numErpLen.Text.Trim());
  1934. int myKey = currKey;
  1935. Task.Run(() => { saveCurrRecord(myKey, szBatchId, szReelId, ldErpLen); });
  1936. resetUIValue();
  1937. pStopWatch.Stop();
  1938. this.btnStart.Enabled = true;
  1939. this.btnEnd.Enabled = this.btnPause.Enabled = false;//这里有问题,应该是devPlc回调设置
  1940. }
  1941. else
  1942. {
  1943. AddTextEvent(DateTime.Now, "结束验布", "无数据结束验布!");
  1944. _isDefect = false;
  1945. }
  1946. }
  1947. private void lstboxLog_DrawItem(object sender, DrawItemEventArgs e)
  1948. {
  1949. if (e.Index < 0) return;
  1950. string text = lstboxLog.GetItemText(e.Index);
  1951. //if (text.Contains("D"))
  1952. //{
  1953. // e.Graphics.FillRectangle(UIColor.Green, e.Bounds);
  1954. // e.Graphics.DrawString(text, e.Font, Color.Blue, e.Bounds, ContentAlignment.MiddleLeft);
  1955. //}
  1956. //e.Graphics.FillRectangle(UIColor.Green, e.Bounds);
  1957. switch (text[0])
  1958. {
  1959. case 'R':
  1960. e.DrawBackground();
  1961. e.Graphics.DrawString(text.Substring(1), e.Font, Color.Red, e.Bounds, ContentAlignment.MiddleLeft);
  1962. break;
  1963. case 'Y':
  1964. e.DrawBackground();
  1965. e.Graphics.DrawString(text.Substring(1), e.Font, Color.Orange, e.Bounds, ContentAlignment.MiddleLeft);
  1966. break;
  1967. //default: //B
  1968. // e.Graphics.DrawString(text.Substring(1), e.Font, Color.Black, e.Bounds, ContentAlignment.MiddleLeft);
  1969. // break;
  1970. }
  1971. }
  1972. private void txtBarCode_KeyDown(object sender, KeyEventArgs e)
  1973. {
  1974. if(e.KeyCode == Keys.Enter)
  1975. {
  1976. string barcode=txtBarCode.Text.Trim();
  1977. if (barcode == "")
  1978. return;
  1979. if (currentState != CurrentStateEnum.运行中 && currentState != CurrentStateEnum.暂停)
  1980. return;
  1981. devContainer.devCodeScanner.ScanerEvent?.Invoke(barcode);
  1982. }
  1983. }
  1984. private void showImg( Mat mat)
  1985. {
  1986. //把Mat格式的图片转换成Bitmap
  1987. Bitmap bitmap = BitmapConverter.ToBitmap(mat);
  1988. this.Invoke(new System.Action(() =>
  1989. {
  1990. //显示图片
  1991. //picDefectImage.loadImage(bitmap);
  1992. this.picScanner1.Image = bitmap;
  1993. }));
  1994. }
  1995. private void uiSymbolButton1_Click(object sender, EventArgs e)
  1996. {
  1997. try
  1998. {
  1999. }
  2000. catch (Exception ex)
  2001. {
  2002. MessageBox.Show(ex.Message);
  2003. }
  2004. }
  2005. int mynum = 0;
  2006. private void uiSymbolButton1_Click_1(object sender, EventArgs e)
  2007. {
  2008. //UIMessageTip.ShowOk($"{record.Len},{record.ScannerPhotoCount-record.ScannerPhotoFinishCount}", 1500);
  2009. //return;
  2010. try
  2011. {
  2012. // mynum++;
  2013. // int FaceWidth = 200;
  2014. // float faceWidthX_cm = (float)(mynum * 100 * 1.0f / Config.cm2px_y );
  2015. // float faceWidthY_cm = (float)(200 * 1.0f / Config.cm2px_y );
  2016. // var point = new System.Drawing.PointF(faceWidthX_cm, faceWidthY_cm);
  2017. // AddTextEvent(DateTime.Now,"门幅", $"位置:{point.X}; 幅宽:{point.Y}");
  2018. // lstFaceWidth.Add(point);
  2019. // reDrawFaceWidth(lstFaceWidth, new double[] { 0, point.X }, new double[] { faceWidthY_cm, faceWidthY_cm });
  2020. // //Mat mat = new Mat(Application.StartupPath + "\\1.bmp");
  2021. // //devContainer.devScannerGentl1.ScanEvent(1, mat, 1);
  2022. // //---------------------
  2023. // if (record == null)
  2024. // {
  2025. // record = new Records();
  2026. // record.DefectInfoList = new List<DefectInfo>();
  2027. // record.DefectInfoList.Add(new DefectInfo() { Code = "jb", Name = "浆斑", X = 20, Y = 2, Width = 2, Height = 2 });
  2028. // record.DefectInfoList.Add(new DefectInfo() { Code = "jb", Name = "浆斑", X = 20, Y = 5, Width = 2, Height = 2 });
  2029. // record.DefectInfoList.Add(new DefectInfo() { Code = "wy", Name = "污印", X = 50, Y = 2, Width = 4, Height = 4 });
  2030. // record.DefectInfoList.Add(new DefectInfo() { Code = "lj", Name = "垃圾", X = 60, Y = 5, Width = 2, Height = 2 });
  2031. // reDrawDefectPoints(record.DefectInfoList, new double[2] { 0, 10 }, new double[2] { 0, 100 });
  2032. // foreach (DefectInfo info in record.DefectInfoList)
  2033. // {
  2034. // this.uiDataGridView1.Rows.Add(info.Code, info.Name,
  2035. // info.CentreX, info.CentreY, info.Area, info.ZXD, info.Target);
  2036. // }
  2037. // }
  2038. }
  2039. catch (Exception ex)
  2040. {
  2041. MessageBox.Show(ex.Message);
  2042. }
  2043. }
  2044. private void tcbarLightValue_ValueChanged(object sender, EventArgs e)
  2045. {
  2046. if (devContainer.state)
  2047. {
  2048. //bool b1 = devContainer.devScannerGentl1.setParam((float)tcbarExposureTime.Value);
  2049. //bool b2= devContainer.devScannerGentl2.setParam((float)tcbarExposureTime.Value);
  2050. // AddTextEvent(DateTime.Now,"setExposureTime", b1.ToString());
  2051. // AddTextEvent(DateTime.Now,"setExposureTime", b2.ToString());
  2052. var res=devContainer.devLight.setDigitalValue(1, (int)tcbarLightValue.Value);
  2053. //UIMessageTip.ShowOk($"{(int)tcbarLightValue.Value}/255 var={res} {Config.Light_Name}", 1000);
  2054. //tpnlLight.Text = this.tpnlLight.Tag + $" ({(int)tcbarLightValue.Value}/255)";
  2055. }
  2056. }
  2057. private void swcDefectPauseForUser_ValueChanged(object sender, bool value)
  2058. {
  2059. this.defectPauseForUser = this.swcDefectPauseForUser.Active;
  2060. }
  2061. private void button1_Click(object sender, EventArgs e)
  2062. {
  2063. //List<DefectInfo> lstEditDefect = new List<DefectInfo>();
  2064. //DefectInfo dt = new DefectInfo();
  2065. //dt.Name = "123";
  2066. //dt.Code = "wuyin";
  2067. //dt.image = Image.FromFile("C:\\Users\\fang\\Desktop\\123.png");
  2068. //lstEditDefect.Add(dt);
  2069. //Mat mtt = new Mat("C:\\Users\\fang\\Desktop\\新建文件夹\\mx\\636.bmp");
  2070. //FHome_Defect frmDefect = new FHome_Defect(lstEditDefect, mtt);
  2071. //frmDefect.ShowDialog();
  2072. Config.LoadAllConfig();
  2073. //设置程序最小/大线程池
  2074. // Get the current settings.
  2075. int minWorker, minIOC;
  2076. ThreadPool.GetMinThreads(out minWorker, out minIOC);
  2077. ThreadPool.SetMinThreads(25, minIOC);
  2078. Mat matt = new Mat("C:\\Users\\fang\\Desktop\\新建文件夹\\253.bmp");
  2079. //OpenCVUtil.LoadEdgeMode();
  2080. //int tt = 0;
  2081. //var mty = OpenCVUtil.getMaxInsetRect2(matt, false, 0,out tt);
  2082. //mty.SaveImage("edge.bmp");
  2083. List<QualifiedLimit> qlist = new List<QualifiedLimit>();
  2084. //[ 'laji','liangdian', 'wuyin', 'jietou', 'bmss', 'qipi', 'tiaohen','yayin','zhouyin','yisesi','chongying']
  2085. qlist.Add(new QualifiedLimit() { Code = "laji", ZXD = 0.3, Area = 0.04, ContrastLower = 0.98, ContrastTop = 1.02 });
  2086. qlist.Add(new QualifiedLimit() { Code = "liangdian", ZXD = 0.3, Area = 0.09, ContrastLower = 0.93, ContrastTop = 1.07 });
  2087. qlist.Add(new QualifiedLimit() { Code = "wuyin", ZXD = 0.3, Area = 0.04, ContrastLower = 0.96, ContrastTop = 1.04 });
  2088. qlist.Add(new QualifiedLimit() { Code = "jietou", ZXD = 0.3, Area = 0.09, ContrastLower = 0.94, ContrastTop = 1.06 });
  2089. qlist.Add(new QualifiedLimit() { Code = "bmss", ZXD = 0.3, Area = 0.08, ContrastLower = 0.99, ContrastTop = 1.01 });
  2090. qlist.Add(new QualifiedLimit() { Code = "qipi", ZXD = 0.4, Area = 0.01, ContrastLower = 0.99, ContrastTop = 1.01 });
  2091. qlist.Add(new QualifiedLimit() { Code = "tiaohen", ZXD = 0.3, Area = 2, ContrastLower = 0.99, ContrastTop = 1.01 });
  2092. qlist.Add(new QualifiedLimit() { Code = "yayin", ZXD = 0.3, Area = 0.05, ContrastLower = 0.99, ContrastTop = 1.01 });
  2093. qlist.Add(new QualifiedLimit() { Code = "zhouyin", ZXD = 0.3, Area = 2, ContrastLower = 0.99, ContrastTop = 1.01 });
  2094. qlist.Add(new QualifiedLimit() { Code = "yisesi", ZXD = 0.3, Area = 0.05, ContrastLower = 0.99, ContrastTop = 1.01 });
  2095. qlist.Add(new QualifiedLimit() { Code = "chongying", ZXD = 0.3, Area = 2, ContrastLower = 0.99, ContrastTop = 1.01 });
  2096. DefectLib dlt = new DefectLib();
  2097. dlt.start();
  2098. dlt.add(new Device.DefectLib.DefectTask()
  2099. {
  2100. modelName = "MX0727.trt",
  2101. record = null,
  2102. bmp = matt,
  2103. bmpTag = matt.Clone(),
  2104. photoIndex = 0,//0-n 首张必需为0,因下面计算长度是从0开始
  2105. widthRatio = 1,
  2106. qualifiedLimitList = qlist,
  2107. finishEvent = callBackDefectEvent,
  2108. xw = 0,
  2109. });
  2110. return;
  2111. Config.LoadAllConfig();
  2112. DefectLib dl = new DefectLib();
  2113. dl.start();
  2114. string[] files = Directory.GetFiles("E:\\CPL\\个人\\gePic", $"*.bmp", SearchOption.TopDirectoryOnly);
  2115. List<QualifiedLimit> list = new List<QualifiedLimit>();
  2116. list.Add(new QualifiedLimit() { Code = "jb",ZXD = 0.6, Area = 0.04, ContrastLower = 0.98, ContrastTop = 1.02});
  2117. list.Add(new QualifiedLimit() { Code = "wy", ZXD = 0.6, Area = 0.09, ContrastLower = 0.93, ContrastTop = 1.07 });
  2118. list.Add(new QualifiedLimit() { Code = "mj", ZXD = 0.6, Area = 0.04, ContrastLower = 0.96, ContrastTop = 1.04 });
  2119. list.Add(new QualifiedLimit() { Code = "hy", ZXD = 0.67, Area = 0.09, ContrastLower = 0.94, ContrastTop = 1.06 });
  2120. list.Add(new QualifiedLimit() { Code = "lj", ZXD = 0.7, Area = 0.08, ContrastLower = 0.99, ContrastTop = 1.01 });
  2121. list.Add(new QualifiedLimit() { Code = "yss", ZXD = 0.5, Area = 0.04, ContrastLower = 0.99, ContrastTop = 1.01 });
  2122. list.Add(new QualifiedLimit() { Code = "zy", ZXD = 0.8, Area = 2, ContrastLower = 0.99, ContrastTop = 1.01 });
  2123. list.Add(new QualifiedLimit() { Code = "wc", ZXD = 0.6, Area = 0.05, ContrastLower = 0.99, ContrastTop = 1.01 });
  2124. list.Add(new QualifiedLimit() { Code = "cs", ZXD = 0.8, Area = 2, ContrastLower = 0.99, ContrastTop = 1.01 });
  2125. list.Add(new QualifiedLimit() { Code = "cy", ZXD = 1, Area = 0.0, ContrastLower = 0.0, ContrastTop = 0 });
  2126. list.Add(new QualifiedLimit() { Code = "tcy", ZXD = 0.5, Area = 0.0, ContrastLower = 0.99, ContrastTop = 1.01 });
  2127. list.Add(new QualifiedLimit() { Code = "jt", ZXD = 1, Area = 0.0, ContrastLower = 0.0, ContrastTop = 0 });
  2128. for (int i = 0; i < files.Count(); i++)
  2129. {
  2130. Mat mat = new Mat(files[i]);
  2131. dl.add(new Device.DefectLib.DefectTask()
  2132. {
  2133. modelName = "best_0116_bs14.fp16.trt",
  2134. //record = curRecord,
  2135. bmp = mat.Clone(),
  2136. bmpTag = mat.Clone(),
  2137. photoIndex = i,//0-n 首张必需为0,因下面计算长度是从0开始
  2138. widthRatio = 1,
  2139. qualifiedLimitList = list,
  2140. finishEvent = callBackDefectTestEvent,
  2141. });
  2142. }
  2143. string s = DateTime.Now.Ticks.ToString() + "-";
  2144. Thread.Sleep(1);
  2145. s += DateTime.Now.Ticks.ToString() + "-";
  2146. MessageBox.Show(s);
  2147. // 创建SqlSugarClient实例并配置连接字符串
  2148. //var db = new SqlSugarClient(new ConnectionConfig()
  2149. //{
  2150. // // 设置数据库类型为SQLServer
  2151. // DbType = SqlSugar.DbType.SqlServer,
  2152. // // 设置服务器地址、数据库名称以及登录信息等
  2153. // ConnectionString = "Data Source=.;Initial Catalog=testDB;User ID=sa;Password=abc123!@#;"
  2154. //});
  2155. //// 可选:打开调试日志输出
  2156. //db.Ado.IsEnableLogEvent = true;
  2157. //// 查询操作示例
  2158. //if (!db.Ado.IsValidConnection())
  2159. // db.Ado.Open();
  2160. //string sql = "select * from t2";
  2161. //List<SugarParameter> parameters = new List<SugarParameter>();
  2162. //var res= db.Ado.GetDataTable(sql, parameters);
  2163. //loadErpData("20240107492");
  2164. return;
  2165. string code = "SHNY-PX-6-L-100";
  2166. string[] barCodes = code.Split(new char[] { '-' });
  2167. if (barCodes.Length < 4)
  2168. {
  2169. AddTextEvent(DateTime.Now,"扫码", $"产品编码({code})格式错误,不做响应!", WarningEnum.High);
  2170. return;
  2171. }
  2172. //新开始
  2173. //加载新产品
  2174. string pcode = barCodes[0] + "-" + barCodes[1] + "-" + barCodes[2];
  2175. var productInfo = svcProduct.GetModelNav(pcode); //frmProduct.loadProduct(code);
  2176. if (productInfo == null)
  2177. {
  2178. AddTextEvent(DateTime.Now,"扫码", $"编码({code})不存在,请先添加产品,暂停设备!", WarningEnum.High);
  2179. this.BeginInvoke(new System.Action(() =>
  2180. {
  2181. frmProduct.loadProduct(pcode);//转到新建编码
  2182. }));
  2183. return;
  2184. }
  2185. AddTextEvent(DateTime.Now,"扫码", $"编码({code}),加载产品信息({productInfo.Code})完成,加载配方(光源={productInfo.LightValue},曝光={productInfo.ExposureTime},增益={productInfo.Gain})...");
  2186. if (productInfo.LightValue > 0)//光源 - 通道0
  2187. devContainer.devLight.setDigitalValue(1, productInfo.LightValue);
  2188. if (productInfo.ExposureTime > 0 || productInfo.Gain > 0)//相机曝光 增益
  2189. {
  2190. devContainer.devCamer1.setParam((float)(productInfo.ExposureTime > 0 ? productInfo.ExposureTime : -1), (float)(productInfo.Gain > 0 ? productInfo.Gain : -1));
  2191. devContainer.devCamer2.setParam((float)(productInfo.ExposureTime > 0 ? productInfo.ExposureTime : -1), (float)(productInfo.Gain > 0 ? productInfo.Gain : -1));
  2192. }
  2193. AddTextEvent(DateTime.Now,"扫码", $"编码({code}),配方设置完成:光源={productInfo.LightValue},曝光={productInfo.ExposureTime}");
  2194. //ABSCamerCardDev pDev = new CamerCardDevIK();
  2195. //pDev.WarningEvent = (level, msg) =>
  2196. //{
  2197. // AddTextEvent(DateTime.Now,"设备事件", msg, level);
  2198. //};
  2199. //var b = pDev.open(0, 0);
  2200. //MessageBox.Show(b.ToString());
  2201. ////b = pDev.loadConfiguration(@"D:\Debug\DevCfg\wcf.vlcf");
  2202. //b =pDev.start(this.picScanner1,"c:\\");
  2203. //MessageBox.Show(b.ToString());
  2204. //====
  2205. //Mat mat0= new Mat(@"f:\2.bmp");
  2206. //int marginWidth0;
  2207. //mat0 = OpenCVUtil.getMaxInsetRect2(mat0, true, 0, out marginWidth0);
  2208. //Mat mat1 = new Mat(@"f:\1.bmp");
  2209. //mat1 = OpenCVUtil.getMaxInsetRect2(mat1, false, 0, out marginWidth0);
  2210. //lblLen.Text = "0";
  2211. //Task.Run(async () => {
  2212. // for(int i = 0; i < 100; i++)
  2213. // {
  2214. // //选中
  2215. // this.Invoke(new System.Action(() =>
  2216. // {
  2217. // lblLen.Text = Convert.ToInt32(lblLen.Text) + 1 + "";
  2218. // }));
  2219. // await Task.Delay(1000);
  2220. // }
  2221. //});
  2222. //FHome_Defect frm = new FHome_Defect();
  2223. //frm.ShowDialog();
  2224. }
  2225. #region 测试
  2226. private void callBackDefectTestEvent(Device.DefectLib.DefectTask res)
  2227. {
  2228. {
  2229. int step = 0;
  2230. try
  2231. {
  2232. if (res.isSucceed)
  2233. {
  2234. step = 1;
  2235. AddTextEvent(DateTime.Now, $"检测完成{Thread.CurrentThread.ManagedThreadId}", $"(图像{res.photoIndex})-瑕疵检测完成,共{res.excelTable.Rows.Count}个瑕疵!各环节用时:{string.Join(",", res.stopwatch)}");
  2236. //AddTextEvent(DateTime.Now,$"打标完成", $"第 ({res.photoIndex}) 张照片,计算过程:{res.resultInfo}");
  2237. }
  2238. else
  2239. {
  2240. AddTextEvent(DateTime.Now, $"打标失败{Thread.CurrentThread.ManagedThreadId}", $"(图像{res.photoIndex})-瑕疵检测失败!TId={Thread.CurrentThread.ManagedThreadId}");
  2241. }
  2242. res.bmp.Dispose();
  2243. res.bmpTag.Dispose();
  2244. res.bmps_cut = null;
  2245. res.excelTable.Dispose();
  2246. }
  2247. catch (Exception ex)
  2248. {
  2249. AddTextEvent(DateTime.Now, $"打标失败{Thread.CurrentThread.ManagedThreadId}", $"(图像{res.photoIndex})-瑕疵检测异常({step}):{ex.Message},TId={Thread.CurrentThread.ManagedThreadId}");
  2250. }
  2251. finally
  2252. {
  2253. res.record.ScannerPhotoFinishCount++;
  2254. int liScannerPhotoFinishCount = res.record.ScannerPhotoFinishCount;
  2255. int liScannerPhotoCount = res.record.ScannerPhotoCount;
  2256. AddTextEvent(DateTime.Now, $"检测完成{Thread.CurrentThread.ManagedThreadId}", $"{liScannerPhotoFinishCount}/{liScannerPhotoCount}");
  2257. //this.BeginInvoke(new System.Action(() =>
  2258. //{
  2259. // this.lblWaitImageCount.Text = $"{liScannerPhotoCount - liScannerPhotoFinishCount}";
  2260. //}));
  2261. res = null;
  2262. System.GC.Collect();
  2263. }
  2264. }
  2265. }
  2266. #endregion
  2267. private void numErpLen_ValueChanged(object sender, string value)
  2268. {
  2269. //numErpLen_TextChanged(sender, null);
  2270. if (numErpLen.IsEmpty || currKey == 0) return;
  2271. var val = Convert.ToDouble(numErpLen.Text);
  2272. if (val <= 0) return;
  2273. Records record = Hashtable.Synchronized(htTask)[currKey] as Records;
  2274. if (record != null)
  2275. record.ErpLen = val;
  2276. }
  2277. private void numErpLen_KeyUp(object sender, KeyEventArgs e)
  2278. {
  2279. if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
  2280. {
  2281. if (numErpLen.IsEmpty || currKey == 0) return;
  2282. var val = Convert.ToDouble(numErpLen.Text);
  2283. if (val <= 0) return;
  2284. Records record = Hashtable.Synchronized(htTask)[currKey] as Records;
  2285. if (record != null)
  2286. record.ErpLen = val;
  2287. }
  2288. }
  2289. private void FHome_Resize(object sender, EventArgs e)
  2290. {
  2291. uilbKF.Top = 8;
  2292. }
  2293. private void FHome_Paint(object sender, PaintEventArgs e)
  2294. {
  2295. uilbKF.Top = 8;
  2296. }
  2297. }
  2298. }