革博士程序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.

FHome.cs 134 KiB

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