革博士V2程序
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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