using CCWin.SkinControl; using ClosedXML.Excel; using DocumentFormat.OpenXml.EMMA; using DocumentFormat.OpenXml.Office2010.ExcelAc; using DocumentFormat.OpenXml.Office2019.Excel.RichData; using DocumentFormat.OpenXml.Office2021.DocumentTasks; using GeBoShi.SysCtrl; using GeBoShi.UI; using GeBoShi.UI.DataQuery; using GeBoShi.UI.InageShow; using GeBoShi.UI.Load; using GeBoShi.UI.Product; using GeBoShi.UI.SysSet; using HalconDotNet; using HZH_Controls; using HZH_Controls.Controls; using HZH_Controls.Forms; using ImageToolKits; using MaiMuControl; using MaiMuControl.Device; using MaiMuControl.Device.CamDev; using Models; using Newtonsoft.Json.Linq; using OpenCvSharp; using OpenCvSharp.Extensions; using PG_Detect; using Service; using SqlSugar; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.IO.Ports; using System.Linq; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.UI.WebControls.WebParts; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; namespace GeBoShi { public partial class Main : Form { [DllImport("user32.dll ", EntryPoint = "SetParent")] private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //将外部窗体嵌入程序 [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpszClass, string lpszWindow); //按照窗体类名或窗体标题查找窗体 object AddTextLock = new object(); bool backgroundWorkerDo; private Stopwatch RunStartTime = new Stopwatch(); /// /// 显示颜色现在对应30色,确保label在30个以内 /// Color[] ChartColor = new Color[30] { Color.Red, Color.Blue, Color.Green, Color.YellowGreen, Color.Orange, Color.Peru, Color.DarkRed,Color.GreenYellow, Color.Pink , Color.Brown, Color.CadetBlue, Color.OrangeRed, Color.Cyan, Color.Lime, Color.Magenta, Color.Tan, Color.Sienna, Color.DarkGray, Color.SaddleBrown, Color.DarkBlue, Color.Firebrick,Color.Gainsboro,Color.Honeydew,Color.Khaki,Color.Lavender, Color.LightGoldenrodYellow,Color.Navy, Color.Khaki, Color.IndianRed,Color.Lavender}; Process process = null; IntPtr appWin; public Main() { InitializeComponent(); UIStyle.SetUIStyle(this); this.uiTitel1.FatherForm = this; //this.uiTitel1.UserMenuStrip = this.menuStrip1; this.uiTitel1.ShowContrlBox(true, true, true); this.uiTitel1.ShowMenu(); this.DoubleBuffered = true;//设置本窗体 SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景. SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲 SysMgr.Instance.MainRuning += main_running; SysMgr.Instance.AutoRuning += auto_runing; #region 缺陷列表dataGridView设置 skinDataGridView1.AllowUserToAddRows = skinDataGridView1.AllowUserToDeleteRows = false;//用户添加删除行 skinDataGridView1.AllowUserToResizeRows = false;//用户调整行大小 //显示行号与列宽度自动调整 skinDataGridView1.RowHeadersVisible = true; skinDataGridView1.RowHeadersWidth = 50; //dataGridView1.ColumnHeadersHeightSizeMode = dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; skinDataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变 skinDataGridView1.RowTemplate.Height = 30; //skinDataGridView1.RowPostPaint += (sender, e) =>//序号列头 //{ // showRowNum_onDataGrid_RowPostPaint(this.skinDataGridView1, sender, e); //}; for (int i = 0; i < skinDataGridView1.Columns.Count; i++)//禁止点击列头排序 skinDataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; this.skinDataGridView1.CellClick += skinDataGridView1_CellClick; ; #endregion #region 标准列表dataGridView设置 dataGridView2.AutoGenerateColumns = false;//自动创建列 dataGridView2.AllowUserToAddRows = dataGridView1.AllowUserToDeleteRows = false;//用户添加删除行 //dataGridView2.AllowUserToResizeRows = true;//用户调整行大小 // //dataGridView1.AllowUserToResizeColumns = false;//用户调整列大小 // //显示行号与列宽度自动调整 //dataGridView2.RowHeadersVisible = true; //dataGridView2.RowHeadersWidth = 62; //dataGridView2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变 //dataGridView2.RowPostPaint += (sender, e) =>//序号列头 //{ // SysMgr.showRowNum_onDataGrid_RowPostPaint(this.dataGridView2, sender, e); //}; //dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; panel_jcbz.Visible = false; panel_jcbz.Location = new System.Drawing.Point(0, 0); panel_jcbz.Dock = DockStyle.Fill; #endregion //设置图标大小 this.lineChartDefect.Size = new System.Drawing.Size(600, 800); this.lineChartFaceWidth.Size = new System.Drawing.Size(1000, 300); #region 数据查询dataGridView设置 uiDataGridView1.AutoGenerateColumns = false;//自动创建列 uiDataGridView1.AllowUserToAddRows = uiDataGridView1.AllowUserToDeleteRows = false;//用户添加删除行 uiDataGridView1.AllowUserToResizeRows = true;//用户调整行大小 uiDataGridView1.AllowUserToResizeColumns = false;//用户调整列大小 uiDataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//只可选中整行,不是单元格 //显示行号与列宽度自动调整 uiDataGridView1.RowHeadersVisible = true; uiDataGridView1.RowHeadersWidth = 30; uiDataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变 uiDataGridView1.RowPostPaint += (sender, e) =>//序号列头 { SysMgr.showRowNum_onDataGrid_RowPostPaint(this.uiDataGridView1, sender, e); }; uiDataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; //for (int i = 0; i < dataGridView1.Columns.Count; i++)//禁止点击列头排序 // uiDataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; //行列交叉处标题 //if (uiDataGridView1.RowHeadersVisible) uiDataGridView1.TopLeftHeaderCell.Value = "SPH/CYL"; //事件 this.uiDataGridView1.DataBindingComplete += this.uiDataGridView1_DataBindingComplete;//bing data时发生,可修改单元格内容 //this.uiDataGridView1.SelectIndexChange += uiDataGridView1_SelectIndexChange;//选择行时发行 //this.uiDataGridView1.CellClick += UiDataGridView1_CellClick; #endregion //this.lblDefectLen.Top = toolStrip1.Top + 10; //this.lblDefectLen.Left = toolStrip1.Width - 300; //this.lblDefectSpeed.Top = toolStrip1.Top + 10 + lblDefectLen.Height + 5; //this.lblDefectSpeed.Left = toolStrip1.Width - 300; this.lbFK.Text = "当前幅宽:"; this.skinTabControl1.SelectedIndex = 0; } #region 初始化 /// /// 初始化 /// /// private bool InitSystem() { //进入初始化,初始化失败则中断 InitFrm initFrm = new InitFrm(); initFrm.ShowDialog(); if (initFrm.DialogResult == DialogResult.OK) { //初始化成功 } else { initFrm.Dispose(); return false; } initFrm.Dispose(); return true; } #endregion #region 界面刷新 private void showRowNum_onDataGrid_RowPostPaint(DataGridView dgv, object sender, DataGridViewRowPostPaintEventArgs e) { Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height); TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right); } private void ResetUI(bool clearSN) { //保持产品名称和料号 //txtProductName.Text = txtProductCode.Text = txtProductSN.Text = ""; if (clearSN) cbPdtSN.Text = ""; //this.lstLog.Items.Clear(); this.tsbtnImpStop.Enabled = false; this.tsbtnStart.Enabled = true; this.tsbtnStop.Enabled = false; this.cbPdtSN.Enabled = true; this.cbPdtColor.Enabled = true; this.numPdtLength.Enabled = true; this.pictureBox1.Image = null; pictureBox1.Refresh(); tslabelTime.Text = "实时测试队列"; skinDataGridView1.DataSource = null; this.skinDataGridView1.Rows.Clear(); ResetChart(); lblDefectLen.Text = $"检测长度: 0 米"; lblDefectSpeed.Text = $"检测速度: 0 米/分钟"; ucSwitch1.Checked = SysMgr.Instance.GetDefectPause(); ucSwitch2.Checked = SysMgr.Instance.GetDefectDB(); this.Refresh(); } void ResetChart() { chart1.Series.Clear(); chart1.Series.Add("SELECT"); chart1.Series["SELECT"].ChartType = SeriesChartType.Point; chart1.Series["SELECT"].MarkerSize = 25; chart1.Series["SELECT"].MarkerColor = Color.Black; chart1.Series["SELECT"].MarkerStyle = MarkerStyle.Star6; //chart1.Series["SELECT"].Enabled = false; chart1.ChartAreas[0].AxisX.Title = "宽度(cm)"; chart1.ChartAreas[0].AxisY.Title = "长度(m)"; chart3.Series.Clear(); chart3.Series.Add("面宽"); chart3.ChartAreas[0].AxisX.Title = "长度(m)"; chart3.ChartAreas[0].AxisY.Title = "宽度(cm)"; chart3.Series["面宽"].ChartType = SeriesChartType.Line; chart3.Series["面宽"].MarkerSize = 5; chart3.Series["面宽"].MarkerColor = Color.Blue; chart3.Series["面宽"].MarkerStyle = MarkerStyle.Circle; } #endregion #region 权限判断 private void UserRightCheck() { //this.tsmPdtMgr.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Product); //this.tsmSysDataFind.Visible = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Statistics); //this.tsmUserList.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.User); //this.tsmUserRight.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Role); //if (this.tsmUserList.Enabled == false && this.tsmUserRight.Enabled == false) // this.tsmSysUserMgr.Visible = false; //else // this.tsmSysUserMgr.Visible = true; //this.tsmDebug.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Debug); //this.tsmSysSet.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.ParamsSetting); //if (this.tsmDebug.Enabled == false && this.tsmSysSet.Enabled == false) // this.stmSysSet.Visible = false; //else // this.stmSysSet.Visible = true; } #endregion #region 运行判断 /// /// 系统是否在运行 /// /// private bool SystemIsRun() { //if (SysMgr.Instance.IsRuning) //{ // FrmDialog.ShowDialog(this, "设备正在运行中!", "警告", false); // //MessageBox.Show("设备正在运行中!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); // return false; //} return true; } #endregion #region 界面事件 private void Main_Load(object sender, EventArgs e) { //登入 if (SysMgr.Instance.LoginSystem()) { //登入成功 if (InitSystem()) { this.Cursor = Cursors.WaitCursor; //this.WindowState = FormWindowState.Normal; this.Top = 0; this.Left = 0; this.Width = SystemInformation.WorkingArea.Width; this.Height = SystemInformation.WorkingArea.Height; //this.WindowState = FormWindowState.Maximized; //this.splitContainer1.SplitterDistance = this.Width / 3; ResetUI(true); this.Show(); this.tsslLoginInfo.Text = $"操作员:{SysMgr.Instance.UserMgr.LoginUser.Code}({SysMgr.Instance.UserMgr.LoginUser.Name})"; this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow; this.tsslLoginTime.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.tsslLoginInfo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.tsState.Text = ""; //更新数据库格式 Service.InitDB.initDB(ConfMgr.Instance.DBConStr); //权限判断 UserRightCheck(); //开启后台 //timer1.Enabled = true; backgroundWorkerDo = true; backgroundWorker1.RunWorkerAsync(); //s_BackWorker = true; //backgroundWorker.RunWorkerAsync(); //开启云端连接 //SysMgr.Instance.InitCloudConnect(); //开启产品服务 //SysMgr.Instance.InitPdtService(); //开启处理事件反馈 SysMgr.Instance.InitDefectEvent(); //加载产品料号 SysMgr.Instance.LoadProductCodeList(); //加载产品选择 LoadPdtList(SysMgr.Instance.ProductCodeList); this.Cursor = Cursors.Default; //初次加载缺陷标准列表 InitDefectListDataView(); //激活OnPageChanged事件 pageCtrl1.OnPageChanged += new EventHandler(pagerControl1_OnPageChanged); //加载串口 GetComPort(); //运行前检测磁盘空间 SysMgr.CheckDisk(this); } else { Application.Exit(); } } else { Application.Exit(); } } private void Main_FormClosing(object sender, FormClosingEventArgs e) { if (SystemIsRun()) { DialogResult dr = DialogResult.Cancel; if (SysMgr.Instance.IsInit) { dr = FrmDialog.ShowDialog(this, "确定要退出当前系统?", "警告", true); } else dr = DialogResult.OK; if (dr == DialogResult.Cancel) { e.Cancel = true; } else { backgroundWorkerDo = false; //Thread.Sleep(300); Thread.Sleep(300); if (SysMgr.Instance.IsInit) SysMgr.Instance.Close(); //SysMgr.Instance.MainRuning -= main_running; } } else e.Cancel = true; } private void Main_SizeChanged(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Maximized) { this.WindowState = FormWindowState.Normal; this.Top = 0; this.Left = 0; this.Width = SystemInformation.WorkingArea.Width; this.Height = SystemInformation.WorkingArea.Height; } } #endregion #region 菜单 #region 用户 #endregion #region 系统设置 private void MainFrm_Paint(object sender, PaintEventArgs e) { } #endregion #endregion #region 检测管理 private string[] pdtlistData; private void LoadPdtList(List list) { this.cbPdtType.Items.Clear(); while (true) { bool bk = true; for (int i = 0; i < list.Count; i++) { if (list[i] == null || string.IsNullOrEmpty(list[i])) { list.Remove(list[i]); bk = false; } } if (bk) { break; } } this.pdtlistData = list.ToArray(); cbPdtType.Items.AddRange(pdtlistData);//比使用DataSource速度要快一些 this.cbPdtType.Text = ""; cbPdtType.Focus(); cbPdtType.SelectAll(); } private void tsmPdtMgr_Click(object sender, EventArgs e) { if (SystemIsRun()) { ProductListFrm frm = new ProductListFrm(); frm.ShowDialog(); //加载产品料号 SysMgr.Instance.LoadProductCodeList(); //加载产品选择 LoadPdtList(SysMgr.Instance.ProductCodeList); } } #endregion #region 显示图像和消息 /// /// 异步输出日志 /// /// 模板标识 /// 内容 /// private void AddTextEvent(string tag, string msg, WarningEnum level = WarningEnum.Normal, bool Show = true) { lock (AddTextLock) { if (tag != null && tag != "") tag = $" - [{tag}]"; var now = DateTime.Now; msg = now.ToString("HH:mm:ss fff") + tag + " - " + msg; syslog.Text = msg; syslog.ForeColor = level == WarningEnum.Normal ? Color.White : level == WarningEnum.Low ? Color.Yellow : Color.Red; } } private void main_running(object sender, MainEventArgs e) { ShowMessage(e); } private delegate void ShowMessageDelegate(MainEventArgs e); private void ShowMessage(MainEventArgs e) { if (InvokeRequired) { ShowMessageDelegate smd = new ShowMessageDelegate(ShowMessage); this.BeginInvoke(smd, e); } else { AddTextEvent(e.Tag, e.Message, e.Warning, e.show); } } /// /// 自动运行流程显示 /// /// /// private void auto_runing(object sender, RunEventArgs e) { ShowUIEvent(e); } private delegate void ShowUIEventDelegate(RunEventArgs e); Bitmap bmp0; Bitmap bmp1; Bitmap bmp2; private void ReDrawDefectPoints(List DataRowlist) { foreach (var rowItem in DataRowlist) { this.skinDataGridView1.Rows.Insert(0, rowItem); if (chart1.Series.FindByName((string)rowItem[3]) == null)//rowItem[3] 为name { chart1.Series.Add((string)rowItem[3]); var obj = SysMgr.Instance.GetDefectLabel((string)rowItem[3]); int labelIndex = obj.Value("id"); chart1.Series[(string)rowItem[3]].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point; chart1.Series[(string)rowItem[3]].MarkerSize = 5; chart1.Series[(string)rowItem[3]].MarkerColor = ChartColor[labelIndex]; chart1.Series[(string)rowItem[3]].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle; } chart1.Series[(string)rowItem[3]].Points.AddXY(rowItem[4], rowItem[5]); } //chart1.ChartAreas[0].AxisY.Maximum = ((int)(this.chart1.Series["划伤"].Points.FindMaxByValue().YValues.Max() / 10) + 1) * 10 + 5; chart1.ChartAreas[0].AxisY.ScaleView.Scroll(System.Windows.Forms.DataVisualization.Charting.ScrollType.Last); } private void LoadDefectLabelAndPrint(Product md, bool reLabel = false) { dataGridView1.Columns.Clear(); DataTable dt = new DataTable(); //建立个数据表 dt.Columns.Add(new DataColumn("二次判断项", typeof(string)));//在表中添加string类型的列 dataGridView1.DataSource = dt; //插入按钮 DataGridViewButtonColumn btn1 = new DataGridViewButtonColumn(); btn1.Name = "Pause"; btn1.HeaderText = "判断"; //btn1.DefaultCellStyle.va = "启用"; btn1.Text = "开启"; btn1.UseColumnTextForButtonValue = false; btn1.DefaultCellStyle.NullValue = "开启"; btn1.DefaultCellStyle.BackColor = Color.LimeGreen; dataGridView1.Columns.Add(btn1); DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn(); btn2.Name = "Print"; btn2.HeaderText = "打标"; btn2.Text = "开启"; btn2.UseColumnTextForButtonValue = false; btn2.DefaultCellStyle.NullValue = "开启"; btn2.DefaultCellStyle.BackColor = Color.LimeGreen; dataGridView1.Columns.Add(btn2); List list = new List(); DataTable dts = (DataTable)dataGridView1.DataSource; dts.Clear(); foreach (var item in md.QualifiedLimitList) { if (md.DefectPauseOption == null || md.DefectPauseOption.Count==0 || md.DefectPauseOption.Contains(item.Code)) { //新增 DataRow dr;//行 dr = dts.NewRow(); dr["二次判断项"] = item.NameCode; dts.Rows.Add(dr);//在表的对象的行里添加此行 list.Add(item.NameCode); } } dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns[0].DefaultCellStyle.ForeColor = Color.Black; dataGridView1.Columns[0].DefaultCellStyle.SelectionForeColor = Color.Black; if (reLabel) { SysMgr.Instance.LoadDefectItemsPuase(list); SysMgr.Instance.LoadDefectItemsDB(list); } } private void ReDrawDefectPoints(List DataRowlist) { try { //重新绘制 chart1.Series.Clear(); chart1.Series.Add("SELECT"); chart1.Series["SELECT"].ChartType = SeriesChartType.Point; chart1.Series["SELECT"].MarkerSize = 25; chart1.Series["SELECT"].MarkerColor = Color.Black; chart1.Series["SELECT"].MarkerStyle = MarkerStyle.Star6; //chart1.Series["SELECT"].Enabled = false; chart1.ChartAreas[0].AxisX.Title = "宽度(cm)"; chart1.ChartAreas[0].AxisY.Title = "长度(m)"; foreach (var rowItem in DataRowlist) { //this.skinDataGridView1.Rows.Insert(0, rowItem); if (chart1.Series.FindByName((string)rowItem.Name) == null)//rowItem[3] 为name { chart1.Series.Add((string)rowItem.Name); var obj = SysMgr.Instance.GetDefectLabel((string)rowItem.Name); int labelIndex = obj.Value("id"); chart1.Series[(string)rowItem.Name].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point; chart1.Series[(string)rowItem.Name].MarkerSize = 5; chart1.Series[(string)rowItem.Name].MarkerColor = ChartColor[labelIndex]; chart1.Series[(string)rowItem.Name].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle; } chart1.Series[(string)rowItem.Name].Points.AddXY(rowItem.CentreX, rowItem.CentreY / 100); } //chart1.ChartAreas[0].AxisY.Maximum = ((int)(this.chart1.Series["划伤"].Points.FindMaxByValue().YValues.Max() / 10) + 1) * 10 + 5; chart1.ChartAreas[0].AxisY.ScaleView.Scroll(System.Windows.Forms.DataVisualization.Charting.ScrollType.Last); } catch { } } private void ShowUIEvent(RunEventArgs e) { if (InvokeRequired) { ShowUIEventDelegate smd = new ShowUIEventDelegate(ShowUIEvent); this.BeginInvoke(smd, e); } else { try { if (e.Cmd == 6) //显示主图 { //this.BeginInvoke(new System.Action(() => //{ if (e.PicIndex == 1) { bmp1 = e.Pic.ToBitmap(); //this.pictureBox2.Image = bmp1; //this.pictureBox2.Refresh(); } else if (e.PicIndex == 2) { bmp2 = e.Pic.ToBitmap(); //this.pictureBox3.Image = bmp2; //this.pictureBox3.Refresh(); } else if (e.PicIndex == 0) { bmp0 = e.Pic.ToBitmap(); this.pictureBox1.Image = bmp0; this.pictureBox1.Refresh(); } //})); } else if (e.Cmd == 10) //测试结束 { this.tsbtnStart.Enabled = true; this.tsbtnStop.Enabled = false; this.tsbtnImpStop.Enabled = false; this.cbPdtSN.Enabled = true; this.cbPdtColor.Enabled = true; this.numPdtLength.Enabled = true; this.cbPdtType.Enabled = true; } else if (e.Cmd == 11) //显示缺陷列表 { //this.BeginInvoke(new System.Action(() => //{ ReDrawDefectPoints(e.DataRowlist); //显示最新缺陷 var defectInfo = SysMgr.Instance.GetDefectInfo((long)this.skinDataGridView1.Rows[0].Cells["colUid"].Value); if (defectInfo == null) { return; } //OpenCvSharp.Mat img = BitmapConverter.ToMat((Bitmap)defectInfo.image); //imageBox3.RefreshWindow(img, ImageBox.ImageModeEnum.Zoom);//可以不显示区域 //this.imageBox3.Image = (defectInfo.image); //})); } else if(e.Cmd == 12) //显示处理图 { //this.BeginInvoke(new System.Action(() => //{ bmp0 = (Bitmap)e.Defectimg.Clone(); this.pictureBox1.Image = bmp0; this.pictureBox1.Refresh(); //})); } else if (e.Cmd == 13) //显示门幅 { //this.BeginInvoke(new System.Action(() => //{ List ydata = new List(); this.lbFK.Text = "当前幅宽:" + $"{e.Points[e.Points.Count - 1][1]}"; this.chart3.Series["面宽"].Points.Clear(); foreach (var Item in e.Points) { ydata.Add(Item[1]); float x = Item[0] / 100; //cm -> m this.chart3.Series["面宽"].Points.AddXY((float)Math.Round(x, 2), (float)Math.Round(Item[1], 2)); } chart3.ChartAreas[0].AxisY.Maximum = Math.Round(ydata.Max() + 10, 0); chart3.ChartAreas[0].AxisY.Minimum = Math.Round(ydata.Min() - 10, 0); //chart3.ChartAreas["ChartArea1"].AxisX.ScaleView.Scroll(ScrollType.Last); //})); } else if (e.Cmd == 14) //显示速度 { //this.BeginInvoke(new System.Action(() => //{ lblDefectLen.Text = $"检测长度: {Math.Round(e.Len, 2)} 米"; lblDefectSpeed.Text = $"检测速度: {Math.Round(e.Speed,2)} 米/分钟"; //})); } else if (e.Cmd == 15) //显示处理图 new { //this.BeginInvoke(new System.Action(() => //{ bmp0 = (Bitmap)e.DefectMat.ToBitmap(); this.pictureBox1.Image = bmp0; this.pictureBox1.Refresh(); //})); } else if (e.Cmd == 16) //显示缓存 { this.tsState.Text = $"相机1:{e.Cam1ImgCnt},相机2:{e.Cam2ImgCnt}"; this.tslabelTime.Text = e._DefinfoCnt; //this.stsSaveQueue.Text = $"存图队列:{e.SaveImgCnt}"; } else if (e.Cmd == 17) //显示光源亮度 { ; } else if (e.Cmd == 18) //显示二次判断和打标 { //this.BeginInvoke(new System.Action(() => //{ // LoadDefectLabelAndPrint(e.MD); //})); } else if (e.Cmd == 19) // 二次判定数据修改 { //不能使用同步Invoke方式,会使相机超时丢帧 this.BeginInvoke(new System.Action(() => { reFreashFrm(e.ImgIndex, e.LstEditDefect, e.Records, e.LstEditInfo); #if false int liDefectCount = e.LstEditDefect.Count; if(e.LstEditInfo != null || e.LstEditDefect != null) { string oldCode; for (int i = 0; i < this.skinDataGridView1.Rows.Count; i++) { if ((int)this.skinDataGridView1.Rows[i].Cells["colIndex"].Value != e.ImgIndex) continue; long uid = (long)this.skinDataGridView1.Rows[i].Cells["colUid"].Value; foreach (var row in e.LstEditDefect) { //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称,{uid} {row.uid}"); if (row.uid == uid) { oldCode = this.skinDataGridView1.Rows[i].Cells["colCode"].Value.ToString(); //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称 ({this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value})->({row.Name})"); this.skinDataGridView1.Rows[i].Cells["colCode"].Value = row.Code; this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value = row.Name; //this.uiDataGridView1.Refresh(); if (!string.IsNullOrWhiteSpace(row.TagFilePath) && oldCode != row.Code) File.Move(row.TagFilePath, row.TagFilePath.Replace($"_类别{oldCode}", $"_类别{row.Code}"));// break; } } if (e.LstEditInfo != null) { foreach (var item in e.LstEditInfo) { if (item.uid == uid) { this.skinDataGridView1.Rows.RemoveAt(i); i--; break; } } } } //SysMgr.Instance.DelDefectEdit(e.Records, frmDefect.lstDel); //double len = (double)this.lblLen.Tag; //this.reDrawDefectPoints(curRecord.DefectInfoList, new double[] { 0, Math.Round(curRecord.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len }); //AddTextEvent($"二次检测", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {e.LstEditDefect.Count},总数{e.Records.DefectInfoList.Count}"); } //this.uiMiniPagination1.TotalCount = curRecord.DefectTotalCount = curRecord.DefectInfoList.Count; // //double len = Math.Round((res.photoIndex + 1) * bmpHeight * 1.0d / Config.cm2px_y + 0.005f, 2); //重新绘制分布图 ReDrawDefectPoints(e.Records.DefectInfoList); //自动继续运行设备(这里临时暂停后不能再急停,否则无法继续) SysMgr.Instance.StartMotion(); #endif })); } else if (e.Cmd == 20) //显示存图缓存 { //this.tsState.Text = $"相机1:{e.Cam1ImgCnt},相机2:{e.Cam2ImgCnt}"; this.stsSaveQueue.Text = $"存图队列:{e.SaveImgCnt}"; } else if (e.Cmd == 21) //显示二次判定界面 { this.BeginInvoke(new System.Action(() => { var pimage = (Bitmap)e.TagImg.ToBitmap().Clone(); List ld = new List(); foreach (var item in e.LstEditDefect) { ld.Add(item); } int index = e.ImgIndex; //Task.Run(() => //{ int liDefectCount = ld.Count; ImageShowFrm frmDefect = new ImageShowFrm(index, ld, pimage); if (frmDefect.ShowDialog() == DialogResult.OK) { SysMgr.Instance.DelDefectEdit(e.Records, frmDefect.lstDel); reFreashFrm(index, ld, e.Records, frmDefect.lstDel); AddTextEvent($"二次检测2", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {ld.Count},总数{e.Records.DefectInfoList.Count}"); } else { reFreashFrm(index, ld, e.Records, null); } //}); })); } //Application.DoEvents(); } catch { } } } #endregion #region 二次确认界面刷新 void reFreashFrm(int index, List lstEditDefect, Records currRecord, List lstEditInfo) { int err = 0; try { //int liDefectCount = lstEditDefect.Count; //ImageShowFrm frmDefect = new ImageShowFrm(e.LstEditDefect, e.TagImg.ToBitmap()); //frmDefect.Show(); //if (frmDefect.ShowDialog() == DialogResult.OK) if (lstEditInfo != null || lstEditDefect != null) { err = 1; string oldCode; for (int i = 0; i < this.skinDataGridView1.Rows.Count; i++) { if ((int)this.skinDataGridView1.Rows[i].Cells["colIndex"].Value != index) continue; err = 2; long uid = (long)this.skinDataGridView1.Rows[i].Cells["colUid"].Value; foreach (var row in lstEditDefect) { //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称,{uid} {row.uid}"); if (row.uid == uid) { err = 3; oldCode = this.skinDataGridView1.Rows[i].Cells["colCode"].Value.ToString(); //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称 ({this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value})->({row.Name})"); this.skinDataGridView1.Rows[i].Cells["colCode"].Value = row.Code; this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value = row.Name; //this.uiDataGridView1.Refresh(); if (!string.IsNullOrWhiteSpace(row.TagFilePath) && oldCode != row.Code) File.Move(row.TagFilePath, row.TagFilePath.Replace($"_类别{oldCode}", $"_类别{row.Code}"));// break; } } err = 4; if (lstEditInfo != null) { foreach (var item in lstEditInfo) { if (item.uid == uid) { this.skinDataGridView1.Rows.RemoveAt(i); i--; break; } } } } //SysMgr.Instance.DelDefectEdit(e.Records, frmDefect.lstDel); //double len = (double)this.lblLen.Tag; //this.reDrawDefectPoints(curRecord.DefectInfoList, new double[] { 0, Math.Round(curRecord.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len }); //AddTextEvent($"二次检测", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {e.LstEditDefect.Count},总数{e.Records.DefectInfoList.Count}"); } //this.uiMiniPagination1.TotalCount = curRecord.DefectTotalCount = curRecord.DefectInfoList.Count; // //double len = Math.Round((res.photoIndex + 1) * bmpHeight * 1.0d / Config.cm2px_y + 0.005f, 2); //重新绘制分布图 err = 5; ReDrawDefectPoints(currRecord.DefectInfoList); err = 6; //自动继续运行设备(这里临时暂停后不能再急停,否则无法继续) SysMgr.Instance.StartMotion(); }catch(Exception ex) { MessageBox.Show($"err {err}:{ex.Message}"); } } #endregion #region 后台 GetPN pn = new GetPN(); private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while (backgroundWorkerDo) { try { this.Invoke(new MethodInvoker(() => { this.tsslLoginTime.Text = $" 当前时间:{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}"; })); //检测按钮和实时状态 if (SysMgr.Instance.IsInit) { bool sts = SysMgr.Instance.WarningShowLed(false); if (sts) { this.Invoke(new MethodInvoker(() => { this.tsbtnStart.Enabled = true; this.tsbtnStop.Enabled = false; })); } int stsno = 0; stsno = SysMgr.Instance.ButtonIOTrg(false); if (stsno == 1) { this.Invoke(new MethodInvoker(() => { tsbtnStart_Click(null, null); })); } else if (stsno == 2) { this.Invoke(new MethodInvoker(() => { this.tsbtnStart.Enabled = true; })); SysMgr.Instance.LedPause(); } else if (stsno == 3) { this.Invoke(new MethodInvoker(() => { tsbtnReset_Click(null, null); })); } } if (pn.P(SysMgr.Instance.IsRuning)) { //继续计时 RunStartTime.Start(); } if (pn.N(SysMgr.Instance.IsRuning)) { //停止计时 RunStartTime.Stop(); } if (SysMgr.Instance.IsRuning) { ////实时显示 //RunStartTime.Stop(); //this.Invoke(new MethodInvoker(() => //{ // tslabelTime.Text = "实时测试:" + ((double)RunStartTime.ElapsedMilliseconds / 1000.0).ToString("0.000") + "s"; // //this.Refresh(); //})); //RunStartTime.Start(); } Thread.Sleep(100); //Application.DoEvents(); } catch { } } } /// /// 信号上升沿下降沿捕获 /// class GetPN { bool _P = false; bool _N = false; /// /// 判断上升沿 /// /// /// public bool P(bool Value) { if (Value && !_P) { _P = true; return true; } if (!Value) _P = false; return false; } /// /// 判断下降沿 /// /// /// public bool N(bool Value) { if (!Value && _N) { _N = false; return true; } if (Value) _N = true; return false; } } #endregion #region 表格点击 private void skinDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; var defectInfo = SysMgr.Instance.GetDefectInfo((long)this.skinDataGridView1.CurrentRow.Cells["colUid"].Value); if (defectInfo == null) { DialogResult dr = DialogResult.Cancel; dr = FrmDialog.ShowDialog(this, "此记录已不存在!", "警告", true); return; } //选中 this.Invoke(new System.Action(() => { if (chart1.Series != null && chart1.Series.FindByName("SELECT") != null) { chart1.Series["SELECT"].Points.Clear(); chart1.Series["SELECT"].Points.AddXY(defectInfo.CentreX, defectInfo.CentreY / 100); chart1.Refresh(); } })); } #endregion #region 二次判断 private void ucSwitch1_CheckedChanged(object sender, EventArgs e) { SysMgr.Instance.SetDefectPause(ucSwitch1.Checked); } #endregion #region 打标 private void ucSwitch2_CheckedChanged(object sender, EventArgs e) { SysMgr.Instance.SetDefectDB(ucSwitch2.Checked); } #endregion #region 控制光源 private void ucTrackBar1_ValueChanged(object sender, EventArgs e) { //SysMgr.Instance.SetLightValue((int)ucTrackBar1.Value); } #endregion #region 二次判断和打标表格点击 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { //for (int i = 0; i < this.dataGridView1.RowCount; i++) //{ // namelist.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString()); //} int Index = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引 if (Index < this.dataGridView1.Rows.Count && this.dataGridView1.Columns[this.dataGridView1.CurrentCell.ColumnIndex].HeaderText.ToString() == "判断") { List namelist = new List(); DataGridViewButtonCell btn = (DataGridViewButtonCell)this.dataGridView1.CurrentCell; if (btn.FormattedValue.ToString() == "开启") { this.dataGridView1.CurrentCell.Value = "禁用"; this.dataGridView1.CurrentCell.Style.BackColor = Color.Red; this.dataGridView1.CurrentCell.Style.ForeColor = Color.Red; } else { this.dataGridView1.CurrentCell.Value = "开启"; this.dataGridView1.CurrentCell.Style.BackColor = Color.LimeGreen; this.dataGridView1.CurrentCell.Style.ForeColor = Color.Black; } for (int i = 0; i < this.dataGridView1.RowCount; i++) { DataGridViewButtonCell btn2 = (DataGridViewButtonCell)this.dataGridView1.Rows[i].Cells[1]; if (btn2.FormattedValue.ToString() == "开启") namelist.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString()); } //开启该项二次判断功能 SysMgr.Instance.LoadDefectItemsPuase(namelist); } else if (Index < this.dataGridView1.Rows.Count && this.dataGridView1.Columns[this.dataGridView1.CurrentCell.ColumnIndex].HeaderText.ToString() == "打标") { List namelist = new List(); DataGridViewButtonCell btn = (DataGridViewButtonCell)this.dataGridView1.CurrentCell; if (btn.FormattedValue.ToString() == "开启") { this.dataGridView1.CurrentCell.Value = "禁用"; this.dataGridView1.CurrentCell.Style.BackColor = Color.Red; this.dataGridView1.CurrentCell.Style.ForeColor = Color.Red; } else { this.dataGridView1.CurrentCell.Value = "开启"; this.dataGridView1.CurrentCell.Style.BackColor = Color.LimeGreen; this.dataGridView1.CurrentCell.Style.ForeColor = Color.Black; } for (int i = 0; i < this.dataGridView1.RowCount; i++) { DataGridViewButtonCell btn2 = (DataGridViewButtonCell)this.dataGridView1.Rows[i].Cells[1]; if (btn2.FormattedValue.ToString() == "开启") namelist.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString()); } //开启该项打标功能 SysMgr.Instance.LoadDefectItemsDB(namelist); } } #endregion #region 选检测标准之后自动加载二次判断 private void cbDefectCode_SelectedIndexChanged(object sender, EventArgs e) { Product model = SysMgr.Instance.GetProduct(cbPdtType.Text); if (model != null) { LoadDefectLabelAndPrint(model, true); } } #endregion #region 模拟键盘 private KeyBoardType keyBoardType = KeyBoardType.UCKeyBorderAll_EN; [Description("键盘打开样式"), Category("自定义")] public KeyBoardType KeyBoardType { get { return keyBoardType; } set { keyBoardType = value; } } private void showKeyPanel(Control ctl) { //keyPanel.Top = ctl.Top + ctl.Height + 5; //keyPanel.Left = ctl.Left; //keyPanel.Visible = true; //keyPanel.BringToFront(); process = Process.Start(@"C:\WINDOWS\system32\osk.exe"); } //Froms.FrmAnchor m_frmAnchor; private void cbPdtSN_Click(object sender, EventArgs e) { showKeyPanel((Control)sender); } #endregion #region 主界面Tab切换 int curr_TabIndex = 0; private void skinTabControl1_TabIndexChanged(object sender, EventArgs e) { } private void skinTabControl1_Selected(object sender, TabControlEventArgs e) { if (this.skinTabControl1.SelectedIndex == curr_TabIndex) return; else { curr_TabIndex = this.skinTabControl1.SelectedIndex; switch(curr_TabIndex) { case 0: #region 主界面 #endregion break; case 1: #region 标准界面 #endregion break; case 2: #region 数据分析 #endregion break; case 3: #region 系统设置 RefeshSysParams(); #endregion break; } } } #endregion #region 检测标准界面 Models.Product _model = new Models.Product(); #region 标准列表获取 private void InitDefectListDataView(int selIndex = -1) { var list = SysMgr.Instance.ProductList; //tsslCount.Text = $"共 {list.Count} 条记录"; int liIndex = 0; if (selIndex > 0) liIndex = selIndex; else if (this.dataGridView2.CurrentRow != null) liIndex = this.dataGridView2.CurrentRow.Index; dataGridView2.DataSource = new BindingSource(list, null); if (dataGridView2.Rows.Count > liIndex) dataGridView2.CurrentCell = dataGridView2[1, liIndex]; //如果产品存在设置问题,无流程显示颜色 for (int i = 0; i < dataGridView2.Rows.Count; i++) { ; } } #endregion #region 检测标准搜索 private void tbSearch_TextChanged(object sender, EventArgs e) { if (tbSearch.Text != "") { int count = 0; foreach (DataGridViewRow row in dataGridView2.Rows) { for (int i = 0; i < row.Cells.Count; i++) { if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().Contains(tbSearch.Text)) { count = count + 1; } } if (count == 0) { CurrencyManager cm = (CurrencyManager)BindingContext[dataGridView2.DataSource]; cm.SuspendBinding(); //挂起数据绑定 row.Visible = false; cm.ResumeBinding(); //恢复数据绑定 } count = 0; } } else { for (int i = 0; i < dataGridView2.Rows.Count; i++) { dataGridView2.Rows[i].Visible = true; } } } #endregion #region 删除检测标准 private void btnDelDefectNav_Click(object sender, EventArgs e) { try { if (this.dataGridView2.CurrentRow == null) return; if (MessageBox.Show($"确认删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { var list = ((BindingSource)dataGridView2.DataSource).DataSource as List; int liIndex = this.dataGridView2.CurrentRow.Index;//获取当前选中行的索引 if (!SysMgr.Instance.DelDefectItem(list[liIndex])) throw new Exception("删除失败!"); MessageBox.Show("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //initDataView(); this.dataGridView2.Rows.RemoveAt(liIndex); if (this.dataGridView2.Rows.Count == 0) InitDefectListDataView(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } #endregion #region 标准详细 private void initModelData() { //模型文件 string strDefectModelFile = ConfMgr.Instance.SysConfigParams.AIModelPath; if (!Directory.Exists(strDefectModelFile)) { MessageBox.Show("模型路径错误:" + strDefectModelFile, "警告"); return; } string[] onnxFiles = Directory.GetFiles(strDefectModelFile, "*.trt"); //标签文件 string[] labelFiles = Directory.GetFiles(strDefectModelFile, "*.json"); string errorStr = ""; foreach (string onnxFile in onnxFiles) { string onlyName; onlyName = Path.GetFileName(onnxFile); cmbDefectModelFile.Items.Add(onlyName); string findname = onlyName.Replace(".trt", ".json"); //存在对应label文件 if (labelFiles.Count(p => Path.GetFileName(p) == findname) <= 0) { errorStr += $"{onlyName},"; } } if (!string.IsNullOrEmpty(errorStr)) MessageBox.Show("模型缺少词典文件:" + errorStr, "警告"); //加载材质 string configPath = ConfMgr.Instance.ConfigDir + $"\\material.json"; if (File.Exists(configPath)) { string lsTmp = File.ReadAllText(configPath); JArray defectItemList = JArray.Parse(lsTmp); cmbClasses.Items.Clear(); foreach (JObject item in defectItemList) { string name = item.Value("name"); cmbClasses.Items.Add(name); } } else MessageBox.Show("模型材质文件:" + configPath, "警告"); } private void ShowDefectItemInfo(Product m = null) { panel_jcbz.Visible = true; //panel_jcbz.Location = new System.Drawing.Point(0, 0); //panel_jcbz.Dock = DockStyle.Fill; #region 缺陷信息和等级dataGridView设置 dataGridView3.AllowUserToAddRows = dataGridView3.AllowUserToDeleteRows = false;//用户添加删除行 dataGridView4.AllowUserToAddRows = dataGridView4.AllowUserToDeleteRows = false; dataGridView3.AllowUserToResizeRows = dataGridView4.AllowUserToResizeRows = false;//用户调整行大小 //dataGridView1.AllowUserToResizeColumns = false;//用户调整列大小 //显示行号与列宽度自动调整 dataGridView3.RowHeadersVisible = dataGridView4.RowHeadersVisible = true; dataGridView3.RowHeadersWidth = dataGridView4.RowHeadersWidth = 50; //dataGridView1.ColumnHeadersHeightSizeMode = dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; dataGridView3.RowHeadersWidthSizeMode = dataGridView4.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变 dataGridView3.RowTemplate.Height = dataGridView4.RowTemplate.Height = 30; #endregion initModelData(); if (m != null) { _model = m; //显示模型 foreach (string onnxFile in this.cmbDefectModelFile.Items) if (!string.IsNullOrWhiteSpace(_model.ModelName) && onnxFile.ToLower() == _model.ModelName.ToLower()) this.cmbDefectModelFile.SelectedItem = _model.ModelName; //显示寻边算法 foreach (string edge in this.cbEdgeDefect.Items) if (!string.IsNullOrWhiteSpace(_model.EdgeDefectType) && edge.ToLower() == _model.EdgeDefectType.ToLower()) this.cbEdgeDefect.SelectedItem = _model.EdgeDefectType; //显示识别算法 foreach (string defect in this.cbImageDefet.Items) if (!string.IsNullOrWhiteSpace(_model.ImageDefectType) && defect.ToLower() == _model.ImageDefectType.ToLower()) this.cbImageDefet.SelectedItem = _model.ImageDefectType; txtName.Text = _model.Name; cmbClasses.Text = _model.Material; tbColorName.Text = _model.ColorName; numHoldCut.Value = _model.EdgeHoleCut; int[] rgb = new int[3]; if (!string.IsNullOrEmpty(_model.ColorValue)) { for (int i = 0; i < rgb.Length; i++) rgb[i] = Convert.ToInt32(_model.ColorValue.Split(',')[i]); tbColorName.ForeColor = Color.FromArgb(rgb[0], rgb[1], rgb[2]); } //tbSpec.Text = _model.Spec; TrackBarLightValue.Value = _model.LightValue; TrackBarExposureTime.Value = (int)_model.ExposureTime; TrackBarGain.Value = (int)_model.Gain; } } #endregion #region 新增 private void btnNewDefectItem_Click(object sender, EventArgs e) { ShowDefectItemInfo(); } #endregion #region 表格双击 private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { var list = ((BindingSource)dataGridView2.DataSource).DataSource as List; int liIndex = this.dataGridView2.CurrentRow.Index;//获取当前选中行的索引 ShowDefectItemInfo(list[liIndex]); } #endregion #region 光设置 private void TrackBarLightValue_ValueChanged(object sender, EventArgs e) { UCTrackBar trackBar = (UCTrackBar)sender; if (trackBar.Name == "TrackBarLightValue") { numericUpDown1.Value = (decimal)trackBar.Value; } else if (trackBar.Name == "TrackBarExposureTime") { numericUpDown2.Value = (decimal)trackBar.Value; } else if (trackBar.Name == "TrackBarGain") { numericUpDown3.Value = (decimal)trackBar.Value; } } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { NumericUpDown num = (NumericUpDown)sender; if (num.Name == "numericUpDown1") { TrackBarLightValue.Value = (float)num.Value > TrackBarLightValue.MaxValue ? TrackBarLightValue.MaxValue : (float)num.Value; } else if (num.Name == "numericUpDown2") { TrackBarExposureTime.Value = (float)num.Value > TrackBarExposureTime.MaxValue ? TrackBarExposureTime.MaxValue : (float)num.Value; } else if (num.Name == "numericUpDown3") { TrackBarGain.Value = (float)num.Value > TrackBarGain.MaxValue ? TrackBarGain.MaxValue : (float)num.Value; } } #endregion #region 模型加载 private void cmbDefectModelFile_TextChanged(object sender, EventArgs e) { try { string modeljson = cmbDefectModelFile.Text.Replace(".trt", ".json"); //加载缺陷 string configPath = ConfMgr.Instance.SysConfigParams.AIModelPath + $"\\{modeljson}"; string lsTmp = File.ReadAllText(configPath); JArray defectItemList = JArray.Parse(lsTmp); //加行 dataGridView3.Rows.Clear(); dataGridView4.Rows.Clear(); cbDefectName.Items.Clear(); foreach (JObject item in defectItemList) { string code = item.Value("code"); string name = item.Value("name"); //color = item.Value("color"); dataGridView3.Rows.Add(); dataGridView3.Rows[dataGridView3.RowCount - 1].HeaderCell.Value = name; dataGridView3[0, dataGridView3.RowCount - 1].Value = code; dataGridView4.Rows.Add(); dataGridView4.Rows[dataGridView4.RowCount - 1].HeaderCell.Value = name; dataGridView4[0, dataGridView4.RowCount - 1].Value = code; cbDefectName.Items.Add(name); } //模型是否是产品模型 if (_model.ModelName == cmbDefectModelFile.Text) { //加载参数 string code; QualifiedLimit item1; for (int i = 0; i < dataGridView3.Rows.Count; i++) { code = dataGridView3.Rows[i].Cells["Code"].Value.ToString(); item1 = _model.QualifiedLimitList.FirstOrDefault(m => m.Code == code); if (item1 != null) { dataGridView3.Rows[i].Cells["ZXD"].Value = item1.ZXD; dataGridView3.Rows[i].Cells["Area"].Value = item1.Area; dataGridView3.Rows[i].Cells["DBDH"].Value = Utils.ContrastToPercent(item1.ContrastTop); dataGridView3.Rows[i].Cells["DBDL"].Value = Utils.ContrastToPercent(item1.ContrastLower); dataGridView3.Rows[i].Cells["OrAnd"].Value = item1.IsOR; dataGridView3.Rows[i].Cells["DefectLength"].Value = item1.DefectWarnLength; dataGridView3.Rows[i].Cells["DefectWarn"].Value = item1.DefectWarnCnt; } else { dataGridView3.Rows[i].Cells["ZXD"].Value = 0.4; dataGridView3.Rows[i].Cells["Area"].Value = 2; dataGridView3.Rows[i].Cells["DBDH"].Value = 51; dataGridView3.Rows[i].Cells["DBDL"].Value = 49; dataGridView3.Rows[i].Cells["OrAnd"].Value = false; dataGridView3.Rows[i].Cells["DefectLength"].Value = 0; dataGridView3.Rows[i].Cells["DefectWarn"].Value = 0; } } GradeLimit item2; for (int i = 0; i < dataGridView4.Rows.Count; i++) { code = dataGridView4.Rows[i].Cells["Code2"].Value.ToString(); item2 = _model.GradeLimitList.FirstOrDefault(m => m.Code == code); if (item2 != null) { dataGridView4.Rows[i].Cells["A"].Value = item2.A; dataGridView4.Rows[i].Cells["B"].Value = item2.B; dataGridView4.Rows[i].Cells["C"].Value = item2.C; dataGridView4.Rows[i].Cells["D"].Value = item2.D; dataGridView4.Rows[i].Cells["E"].Value = item2.E; } } } else { //加载默认参数 string code; QualifiedLimit item1; for (int i = 0; i < dataGridView3.Rows.Count; i++) { dataGridView3.Rows[i].Cells["ZXD"].Value = 0.4; dataGridView3.Rows[i].Cells["Area"].Value = 2; dataGridView3.Rows[i].Cells["DBDH"].Value = 51; dataGridView3.Rows[i].Cells["DBDL"].Value = 49; dataGridView3.Rows[i].Cells["OrAnd"].Value = false; dataGridView3.Rows[i].Cells["DefectLength"].Value = 0; dataGridView3.Rows[i].Cells["DefectWarn"].Value = 0; } GradeLimit item2; for (int i = 0; i < dataGridView4.Rows.Count; i++) { dataGridView4.Rows[i].Cells["A"].Value = 0; dataGridView4.Rows[i].Cells["B"].Value = 0; dataGridView4.Rows[i].Cells["C"].Value = 0; dataGridView4.Rows[i].Cells["D"].Value = 0; dataGridView4.Rows[i].Cells["E"].Value = 0; } } } catch (Exception ex) { MessageBox.Show("载入出错:" + ex.Message, "警告"); } } #endregion #region 标准设置 private void btnCelDefect_Click(object sender, EventArgs e) { panel_jcbz.Visible = false; } private void btnSaveDefect_Click(object sender, EventArgs e) { try { if (this.cmbClasses.SelectedIndex < 0) throw new Exception("请选择材质!"); if (string.IsNullOrEmpty(this.txtName.Text)) throw new Exception("请填写名称!"); if (string.IsNullOrEmpty(this.tbColorName.Text)) throw new Exception("请填写颜色!"); if (this.cmbDefectModelFile.SelectedIndex < 0) throw new Exception("请选择模型!"); if (this.cbEdgeDefect.SelectedIndex < 0) throw new Exception("请选择寻边算法!"); if (this.cbImageDefet.SelectedIndex < 0) throw new Exception("请选择识别算法!"); _model.Code = $"2.0-{txtName.Text}-{cmbClasses.Text}"; //_model.Color = (int)numColorNo.Value; _model.Name = txtName.Text; _model.Material = cmbClasses.Text; _model.ColorName = tbColorName.Text; _model.ModelName = cmbDefectModelFile.Text; _model.EdgeHoleCut = (int)numHoldCut.Value; _model.EdgeDefectType = cbEdgeDefect.Text; _model.ImageDefectType = cbImageDefet.Text; //_model.Spec = tbSpec.Text; _model.LightValue = (int)TrackBarLightValue.Value; _model.ExposureTime = (double)TrackBarExposureTime.Value; _model.Gain = (double)TrackBarGain.Value; //model.OpenThicknessDetection = cbGetHD.Checked; //model.ThicknessDetectionStopDis = (int)numStopDis.Value; //model.DefectAreaLimit = (int)numDefectAreaLimit.Value; //model.DefectCntLength = (double)numDefectCntLength.Value; //model.DefectCountLimit = (int)numDefectCountLimit.Value; //model.WarnDefect = tbWarnDefect.Text; //model.residueWarnningLen = (double)numReelLen.Value; //缺陷阈值 if (_model.QualifiedLimitList == null) _model.QualifiedLimitList = new List(); else _model.QualifiedLimitList.Clear(); QualifiedLimit qualifiedLimit = new QualifiedLimit(); string modeljson = cmbDefectModelFile.Text.Replace(".trt", ".json"); string configPath = ConfMgr.Instance.SysConfigParams.AIModelPath + $"\\{modeljson}"; string lsTmp = File.ReadAllText(configPath); JArray defectItemList = JArray.Parse(lsTmp); for (int i = 0; i < dataGridView3.Rows.Count; i++) { string code2 = dataGridView3.Rows[i].Cells["Code"].Value.ToString(); string nameCode = defectItemList.FirstOrDefault(x => x.Value("code") == code2).Value("name"); qualifiedLimit = new Models.QualifiedLimit() { Code = dataGridView3.Rows[i].Cells["Code"].Value.ToString(), ZXD = Utils.IsDecimal(dataGridView3.Rows[i].Cells["ZXD"].Value) ? Convert.ToDouble(dataGridView3.Rows[i].Cells["ZXD"].Value) : 0, Area = Utils.IsDecimal(dataGridView3.Rows[i].Cells["Area"].Value) ? Convert.ToDouble(dataGridView3.Rows[i].Cells["Area"].Value) : 0, ContrastLower = Utils.IsDecimal(dataGridView3.Rows[i].Cells["DBDL"].Value) ? Utils.PercentToContrast(Convert.ToDouble(dataGridView3.Rows[i].Cells["DBDL"].Value)) : 0, ContrastTop = Utils.IsDecimal(dataGridView3.Rows[i].Cells["DBDH"].Value) ? Utils.PercentToContrast(Convert.ToDouble(dataGridView3.Rows[i].Cells["DBDH"].Value)) : 0, IsOR = Convert.ToBoolean(dataGridView3.Rows[i].Cells["OrAnd"].Value), NameCode = nameCode, DefectWarnLength = Utils.IsNumber(dataGridView3.Rows[i].Cells["DefectLength"].Value) ? Convert.ToInt32(dataGridView3.Rows[i].Cells["DefectLength"].Value) : 0, DefectWarnCnt = Utils.IsDecimal(dataGridView3.Rows[i].Cells["DefectWarn"].Value) ? Convert.ToInt32(dataGridView3.Rows[i].Cells["DefectWarn"].Value) : 0, ModifyUserCode = SysMgr.Instance.UserMgr.LoginUser.Code, CreateUserCode = SysMgr.Instance.UserMgr.LoginUser.Code }; if (qualifiedLimit.ContrastLower + qualifiedLimit.ContrastTop > 0 && qualifiedLimit.ContrastTop < qualifiedLimit.ContrastLower) throw new Exception($"检测标准中第{i + 1}行中对比度上限值({qualifiedLimit.ContrastTop})不可小于下限值({qualifiedLimit.ContrastLower})!"); _model.QualifiedLimitList.Add(qualifiedLimit); } //产品等级 if (_model.GradeLimitList == null) _model.GradeLimitList = new List(); else _model.GradeLimitList.Clear(); for (int i = 0; i < dataGridView4.Rows.Count; i++) { _model.GradeLimitList.Add( new Models.GradeLimit() { Code = dataGridView4.Rows[i].Cells["Code2"].Value.ToString(), A = Utils.IsNumber(dataGridView4.Rows[i].Cells["A"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["A"].Value) : 0, B = Utils.IsNumber(dataGridView4.Rows[i].Cells["B"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["B"].Value) : 0, C = Utils.IsNumber(dataGridView4.Rows[i].Cells["C"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["C"].Value) : 0, D = Utils.IsNumber(dataGridView4.Rows[i].Cells["D"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["D"].Value) : 0, E = Utils.IsNumber(dataGridView4.Rows[i].Cells["E"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["E"].Value) : 0, ModifyUserCode = SysMgr.Instance.UserMgr.LoginUser.Code, CreateUserCode = SysMgr.Instance.UserMgr.LoginUser.Code }); } // _model.ModifyUserCode = SysMgr.Instance.UserMgr.LoginUser.Code; bool result; bool IsAdd = false; if (_model.Id == 0) { _model.CreateUserCode = SysMgr.Instance.UserMgr.LoginUser.Code; result = SysMgr.Instance.AddDefectItem(_model); IsAdd = true; } else { result = SysMgr.Instance.UpdateDefectItem(_model); } if (!result) throw new Exception("数据保存失败!"); else { if(IsAdd) InitDefectListDataView(); MessageBox.Show("保存成功!", "保存"); panel_jcbz.Visible = false; } } catch (Exception ex) { MessageBox.Show("保存出错:" + ex.Message, "警告"); } } #endregion #region 颜色选择 private void btnColor_Click(object sender, EventArgs e) { ColorDialog dlg = new ColorDialog(); DialogResult result = dlg.ShowDialog(); if (result == DialogResult.OK) { // 获取用户所选颜色 Color selectedColor = dlg.Color; // 在 label1 中显示所选颜色的 RGB 值 tbColorName.Text = SysMgr.CLRToName(selectedColor); tbColorName.ForeColor = selectedColor; } } #endregion #endregion #region 数据分析界面 #region 表格事件 private void uiDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { var list = uiDataGridView1.DataSource as List; for (int i = 0; i < uiDataGridView1.Rows.Count; i++) { if (list[i].Grade < 1) uiDataGridView1.Rows[i].Cells["colGrade"].Value = ""; else if (list[i].Grade <= 5) uiDataGridView1.Rows[i].Cells["colGrade"].Value = (char)(list[i].Grade + 64); else uiDataGridView1.Rows[i].Cells["colGrade"].Value = "不合格"; //if (list[i].RoleInfo != null) // uiDataGridView1.Rows[i].Cells["colRoleName"].Value = list[i].RoleInfo.Name; } } #endregion #region 数据查询 private Expression> createQueryExpression() { return Expressionable.Create() .And(it => it.CreateTime >= uiDatePicker1.Value.Date) .And(it => it.CreateTime < uiDatePicker2.Value.Date.AddDays(1)) .AndIF(!string.IsNullOrWhiteSpace(txtBarcode.Text), it => it.BarCode.Contains(txtBarcode.Text.Trim())) .ToExpression();//注意 这一句 不能少 } private void btnSelectData_Click(object sender, EventArgs e) { pageCtrl1.PageIndex = 1; QueryData(); } private void QueryData() { //未连接数据库,通过模拟数据来实现 //一般通过ORM的分页去取数据来填充 //pageIndex:第几页,和界面对应,从1开始,取数据可能要用pageIndex //count:单页数据量,也就是PageSize值 int count = this.pageCtrl1.PageSize; int totalCount = 0; var list = SysMgr.Instance.GetRecords(pageCtrl1.PageIndex, count, ref totalCount, createQueryExpression()); uiDataGridView1.DataSource = list; pageCtrl1.RecordCount = totalCount; this.pageCtrl1.DrawControl(totalCount); } #endregion #region 数据导出 private void btnExcel_Click(object sender, EventArgs e) { try { if (this.uiDataGridView1.CurrentRow == null) return; Models.Records record = SysMgr.Instance.GetRecord(int.Parse(this.uiDataGridView1.CurrentRow.Cells[0].Value.ToString())); if (record.DefectInfoList.Count < 0) throw new Exception("当前记录无缺陷!"); string path = ConfMgr.SelectFolder(); if (string.IsNullOrWhiteSpace(path)) return; //var list = uiDataGridView1.DataSource as List; //var table = ExcelUtil.ConvertToDataTable(list); //{ 名称=x.Name,Xcm=x.X,Ym=x.Y/100,宽cm=x.Width,高cm=x.Height,面积=x.Area, 置信度 =x.ZXD} var list = record.DefectInfoList;//.Select(x => new { x.Name,x.X,x.Y,x.Width,x.Height,x.Area, x.ZXD}).ToList(); //绘图1 double len = Math.Round(record.Len * 100, 2);//cm this.reDrawDefectPoints(record, new double[] { 0, Math.Round(record.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len }); //绘图2 //var points = Array.ConvertAll(record.FaceWidthListStr.Split(new[] { ',', }, StringSplitOptions.RemoveEmptyEntries),Double.Parse).ToList(); //reDrawFaceWidth(record.FacePointList, // new double[] { 0, Math.Round(len + 0.005f, 2) }, // new double[] { record.FaceWidthMin, Math.Round(record.FaceWidthMax + 0.005f, 2) }); reDrawFaceWidth(record.FacePointList, new double[] { 0, Math.Round(len + 0.005f, 2) }, new double[] { 130, 160 }); // foreach (var item in list) { item.Name = SysMgr.Instance.GetDefectName(record.ProductInfo.ModelName, item.Code); //item.Height = item.Height / 100; //单位错误,保证单位一致 } // string Grade = ""; if (record.Grade < 1) Grade = ""; else if (record.Grade <= 5) Grade = (char)(record.Grade + 64) + ""; else Grade = "不合格"; JsonProductDefects data = new JsonProductDefects() { ProName = record.BarCodeName, BatchId = record.BatchId, ReelId = record.ReelId, Len = record.Len.ToString(), Speed = Math.Round(record.Len / record.TimeLen, 2).ToString(), Grade = Grade, DateTime = record.CreateTime.ToString("yyyy年MM月dd日 HH:mm") }; data.DefectTotal = record.DefectInfoList.GroupBy(x => x.Name).Select(g => new JDefectTotal { Name = g.Key, Count = g.Count() }).ToList(); data.DefectDetail = record.DefectInfoList.Select(x => new JDefectDetail { Index = x.PhotoIndex, Name = x.Name, X = x.X, Y = Math.Round(x.Y / 100.0d, 2), Width = x.Width * 10, Height = x.Height * 10, ZXD = x.ZXD, Area = x.Area * 100, Contrast = x.Contrast }) .OrderBy(x => x.Index).ThenBy(x => x.Y).ToList(); data.Pdt = SysMgr.Instance.GteDefectItem(record.ProductId); data.xyPix = $"X:{ConfMgr.Instance.SysConfigParams.Cm2px_x},Y:{ConfMgr.Instance.SysConfigParams.Cm2px_y}"; var image1 = captureControl(this.lineChartDefect); var image2 = captureControl(this.lineChartFaceWidth); var filePath = $"{path}缺陷列表_{record.BarCode}_{record.BarCodeName}.xlsx"; exportTabel(data, image1, image2, filePath, record.ProductInfo.ModelName); //if (!res) // throw new Exception("导出失败!"); MessageBox.Show("导出成功!", "导出完成"); System.Diagnostics.Process.Start(filePath); } catch (Exception ex) { MessageBox.Show($"{ex.Message}", "导出失败"); //UIMessageTip.ShowError(ex.Message, 2000); //API.OutputDebugString(ex.StackTrace); } } #region 切页 /// /// 页数变化时调用绑定数据方法 /// /// /// private void pagerControl1_OnPageChanged(object sender, EventArgs e) { QueryData(); } #endregion #region 数据图形操作 public void exportTabel(JsonProductDefects ProductDefects, byte[] defectImage, byte[] faceWidthImage, string savePath, string modelName) { //try //{ if (ProductDefects == null) throw new Exception("传入的参数为空"); using (var workbook = new XLWorkbook()) { var wsDefectsDetail = workbook.Worksheets.Add("正面疵点列表"); wsDefectsDetail.RowHeight = 20; wsDefectsDetail.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; wsDefectsDetail.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; wsDefectsDetail.Style.Font.FontName = "宋体"; wsDefectsDetail.Column("A").Width = 12; wsDefectsDetail.Column("B").Width = 25; wsDefectsDetail.Column("C").Width = 10; wsDefectsDetail.Column("D").Width = 10; wsDefectsDetail.Column("E").Width = 10; wsDefectsDetail.Column("F").Width = 10; wsDefectsDetail.Column("G").Width = 12; wsDefectsDetail.Column("H").Width = 14; wsDefectsDetail.Column("I").Width = 14; int rowIndex = 1; int cellIndex = 1; #region 第一行 var row1_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex); row1_cell1.Value = "产品疵点缺陷分布图表"; row1_cell1.Style.Font.Bold = true; //row1_cell1.Style.Font.FontName = "宋体"; row1_cell1.Style.Font.FontSize = 12; var mergeRange_row1 = wsDefectsDetail.Range("A1:I1").Row(1).Merge(); mergeRange_row1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; #endregion #region 第二行 rowIndex++; var row2_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex); row2_cell1.Value = "产品品名"; row2_cell1.Style.Font.Bold = true; row2_cell1.Style.Font.FontSize = 10; row2_cell1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var row2_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1); row2_cell2.DataType = XLDataType.Text; row2_cell2.Value = ProductDefects.ProName; row2_cell2.Style.Font.FontSize = 10; row2_cell2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var row2_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2); row2_cell3.Value = "产品批号"; row2_cell3.Style = row2_cell1.Style; var row2_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3); row2_cell4.Value = "'" + ProductDefects.BatchId; row2_cell4.Style = row2_cell2.Style; var row2_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4); row2_cell5.Value = "产品卷号"; row2_cell5.Style = row2_cell1.Style; var row2_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5); //row2_cell6.SetDataType(XLDataType.Text);//类型设置不起作用 用"'"+内容代替 //row2_cell6.DataType = XLDataType.Text; row2_cell6.Value = "'" + ProductDefects.ReelId; row2_cell6.Style = row2_cell2.Style; var row2_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6); row2_cell7.Value = "长度(米)"; row2_cell7.Style = row2_cell1.Style; var row2_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7); row2_cell8.Value = ProductDefects.Len; row2_cell8.Style = row2_cell2.Style; //NULL var row2_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8); row2_cell9.Style = row2_cell2.Style; #endregion #region 第三行 rowIndex++; var row3_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex); row3_cell1.Value = "检验时间"; row3_cell1.Style = row2_cell1.Style; var row3_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1); row3_cell2.Value = "'" + ProductDefects.DateTime; row3_cell2.Style = row2_cell2.Style; var row3_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2); row3_cell3.Value = "检验长度"; row3_cell3.Style = row2_cell1.Style; var row3_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3); row3_cell4.Value = ProductDefects.Len; row3_cell4.Style = row2_cell2.Style; var row3_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4); row3_cell5.Value = "平均速度"; row3_cell5.Style = row2_cell1.Style; var row3_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5); row3_cell6.Value = ProductDefects.Speed; row3_cell6.Style = row2_cell2.Style; var row3_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6); row3_cell7.Value = "等级"; row3_cell7.Style = row2_cell1.Style; var row3_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7); row3_cell8.Value = ProductDefects.Grade; row3_cell8.Style = row2_cell2.Style; var row3_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8); row3_cell9.Style = row2_cell2.Style; #endregion #region 第四第五行 rowIndex++; var row4_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex); row4_cell1.Value = "设备参数"; row4_cell1.Style = row2_cell1.Style; row4_cell1.Style.Font.Bold = true; row4_cell1.Style.Font.FontSize = 10; row4_cell1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var mergeRange_row4 = wsDefectsDetail.Range("A4:A5").Column(1).Merge(); mergeRange_row4.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var row4_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1); row4_cell2.Value = "光源亮度"; row4_cell2.Style = row2_cell1.Style; var row4_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2); row4_cell3.Value = "曝光时间"; row4_cell3.Style = row2_cell1.Style; var row4_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3); row4_cell4.Value = "增益"; row4_cell4.Style = row2_cell1.Style; var row4_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4); row4_cell5.Value = "行频比"; row4_cell5.Style = row2_cell1.Style; var row4_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5); row4_cell6.Value = "物面分辨率"; row4_cell6.Style = row2_cell1.Style; var row4_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6); row4_cell7.Value = "触发计数"; row4_cell7.Style = row2_cell1.Style; var row4_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7); row4_cell8.Value = "采集计数"; row4_cell8.Style = row2_cell1.Style; var row4_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8); row4_cell9.Value = ""; row4_cell9.Style = row2_cell1.Style; rowIndex++; var row5_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1); row5_cell2.Value = ProductDefects.Pdt.LightValue; row5_cell2.Style = row2_cell1.Style; var row5_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2); row5_cell3.Value = ProductDefects.Pdt.ExposureTime; row5_cell3.Style = row2_cell1.Style; var row5_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3); row5_cell4.Value = ProductDefects.Pdt.Gain; row5_cell4.Style = row2_cell1.Style; var row5_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4); row5_cell5.Value = ""; row5_cell5.Style = row2_cell1.Style; var row5_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5); row5_cell6.Value = ProductDefects.xyPix; row5_cell6.Style = row2_cell1.Style; var row5_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6); row5_cell7.Value = ""; row5_cell7.Style = row2_cell1.Style; var row5_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7); row5_cell8.Value = ""; row5_cell8.Style = row2_cell1.Style; var row5_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8); row5_cell9.Value = ""; row5_cell9.Style = row2_cell1.Style; #endregion #region 第六行后 rowIndex++; if (ProductDefects.DefectTotal != null && ProductDefects.DefectTotal.Count > 0) { cellIndex = 1; int DefectTotalCount = ProductDefects.DefectTotal.Count; //最少5行,固定4列 var row6_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex); row6_cell1.Value = "检测参数"; row6_cell1.Style.Font.Bold = true; row6_cell1.Style.Font.FontSize = 10; row6_cell1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; string cellstr = $"A6:A{7 + ProductDefects.DefectTotal.Count}"; var mergeRange_row6 = wsDefectsDetail.Range(cellstr).Column(1).Merge(); mergeRange_row6.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var row6_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1); row6_cell2.Value = "筛选标准"; row6_cell2.Style.Font.Bold = true; row6_cell2.Style.Font.FontSize = 10; row6_cell2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var mergeRange_row6_2 = wsDefectsDetail.Range($"B6:I6").Row(1).Merge(); mergeRange_row6_2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; //第七行 rowIndex++; var row7_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1); row7_cell2.Value = "缺陷类型"; row7_cell2.Style = row2_cell1.Style; var row7_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2); row7_cell3.Value = "置信度"; row7_cell3.Style = row2_cell1.Style; var row7_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3); row7_cell4.Value = "面积"; row7_cell4.Style = row2_cell1.Style; var row7_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4); row7_cell5.Value = "对比度下限"; row7_cell5.Style = row2_cell1.Style; var row7_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5); row7_cell6.Value = "对比度上限"; row7_cell6.Style = row2_cell1.Style; var row7_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6); row7_cell7.Value = "所用模型版本"; row7_cell7.Style = row2_cell1.Style; var row7_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7); row7_cell8.Value = "或向选择"; row7_cell8.Style = row2_cell1.Style; var row7_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8); row7_cell9.Value = "本次检出数量"; row7_cell9.Style = row2_cell1.Style; //第八行之后 rowIndex++; for (int j = 1; j <= ProductDefects.DefectTotal.Count; j++) // 行 { var temprowcel2 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 1); var temprowcel3 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 2); var temprowcel4 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 3); var temprowcel5 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 4); var temprowcel6 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 5); var temprowcel7 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 6); var temprowcel8 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 7); var temprowcel9 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 8); var tempItemDefectTotal = ProductDefects.DefectTotal[j - 1]; temprowcel2.Value = tempItemDefectTotal.Name; temprowcel2.Style.Font.Bold = true; temprowcel2.Style.Font.FontSize = 10; temprowcel2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; var temp = ProductDefects.Pdt.QualifiedLimitList.Find(x => SysMgr.Instance.GetDefectName(modelName, x.Code) == tempItemDefectTotal.Name); temprowcel3.Value = temp.ZXD; temprowcel3.Style.Font.Bold = true; temprowcel3.Style.Font.FontSize = 10; temprowcel3.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; temprowcel4.Value = temp.Area; temprowcel4.Style.Font.Bold = true; temprowcel4.Style.Font.FontSize = 10; temprowcel4.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; temprowcel5.Value = ContrastToPercent(temp.ContrastLower); temprowcel5.Style.Font.Bold = true; temprowcel5.Style.Font.FontSize = 10; temprowcel5.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; temprowcel6.Value = ContrastToPercent(temp.ContrastTop); temprowcel6.Style.Font.Bold = true; temprowcel6.Style.Font.FontSize = 10; temprowcel6.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; temprowcel7.Value = ProductDefects.Pdt.ModelName; temprowcel7.Style.Font.Bold = true; temprowcel7.Style.Font.FontSize = 10; temprowcel7.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; temprowcel8.Value = temp.IsOR; temprowcel8.Style.Font.Bold = true; temprowcel8.Style.Font.FontSize = 10; temprowcel8.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; temprowcel9.Value = tempItemDefectTotal.Count; temprowcel9.Style.Font.FontSize = 10; temprowcel9.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; } //更新行号 rowIndex = rowIndex + ProductDefects.DefectTotal.Count; } #endregion #region 最后 //rowIndex++; if (ProductDefects.DefectDetail != null && ProductDefects.DefectDetail.Count > 0) { List lstRow5str = new List() { "源图", "名称", "X(cm)", "Y(米)", "宽(mm)", "高(mm)", "置信度", "面积(mm^2)", "对比度" }; for (int i = 0; i < lstRow5str.Count; i++) { var temp_row5_cell = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + i); temp_row5_cell.Value = lstRow5str[i]; temp_row5_cell.Style.Font.Bold = true; temp_row5_cell.Style.Font.FontSize = 11; temp_row5_cell.Style.Font.FontName = "等线"; temp_row5_cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; } rowIndex++; for (int i = 0; i < ProductDefects.DefectDetail.Count; i++) for (int j = 0; j < lstRow5str.Count; j++) { var temp_row6_cell = wsDefectsDetail.Row(rowIndex + i).Cell(cellIndex + j); switch (lstRow5str[j]) { case "源图": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Index; break; case "名称": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Name; break; case "X(cm)": temp_row6_cell.Value = ProductDefects.DefectDetail[i].X; break; case "Y(米)": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Y; break; case "宽(mm)": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Width; break; case "高(mm)": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Height; break; case "置信度": temp_row6_cell.Value = ProductDefects.DefectDetail[i].ZXD; break; case "面积(mm^2)": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Area; break; case "对比度": temp_row6_cell.Value = ProductDefects.DefectDetail[i].Contrast; break; } temp_row6_cell.Style.Font.FontSize = 11; temp_row6_cell.Style.Font.FontName = "等线"; temp_row6_cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; } // row6_cell1.InsertTable(ProductDefects.DefectDetail); } #endregion var wsDefectsImg = workbook.Worksheets.Add("正面疵点分布图"); wsDefectsImg.AddPicture(new MemoryStream(defectImage), "纵向计算") .MoveTo(wsDefectsImg.Cell(1, 1)); var wsFaceWidthImg = workbook.Worksheets.Add("门幅曲线"); wsFaceWidthImg.AddPicture(new MemoryStream(faceWidthImage), "幅宽曲线图") .MoveTo(wsFaceWidthImg.Cell(1, 1)); workbook.SaveAs(savePath); } // return true; //} //catch (Exception ex) //{ // return false; //} } private double ContrastLow = 0.8; private double ContrastTop = 1.2; private double ContrastToPercent(double val) { if (val < ContrastLow) return 0; else if (val > ContrastTop) return 100; double temp = 100 / (ContrastTop - ContrastLow); return Math.Round(temp * (val - ContrastLow), 2); } // /// /// 重新生成缺陷分布(cm2M在内部转换) /// /// Records.DefectInfoList /// 幅宽 /// 卷长度 private void reDrawDefectPoints(Records records, double[] XSizeRange, double[] YSizeRange) { //AddTextEvent($"绘图", $"缺陷分布, W={string.Join(", ", XSizeRange)},H={string.Join(", ", YSizeRange)}, LastData={JsonConvert.SerializeObject(lstDefectInfo[lstDefectInfo.Count - 1])}"); var lstData = records.DefectInfoList.OrderBy(m => m.Code).ThenBy(m => m.Code).ToList(); if (XSizeRange == null || YSizeRange == null) return; else { if (YSizeRange[0] == YSizeRange[1]) { YSizeRange[0] -= YSizeRange[0] / 10f; YSizeRange[1] += YSizeRange[1] / 10f; } YSizeRange[0] /= 100; YSizeRange[1] /= 100; lineChartDefect.Series.Clear(); lineChartDefect.ChartAreas[0].AxisX.Title = "宽度(cm)"; lineChartDefect.ChartAreas[0].AxisY.Title = "长度(m)"; //option = new UILineOption(); //option.XAxis.Name = "面宽(cm)"; //option.YAxis.Name = "长度(米)"; //option.Grid.Top = 20;//边距 //option.Grid.Right = 20;//边距 foreach (var rowItem in lstData) { string name = SysMgr.Instance.GetDefectName(records.ProductInfo.ModelName, rowItem.Code); if (lineChartDefect.Series.FindByName(name) == null)//rowItem[3] 为name { lineChartDefect.Series.Add(name); var obj = SysMgr.Instance.GetDefectLabel(records.ProductInfo.ModelName, name); int labelIndex = obj.Value("id"); lineChartDefect.Series[name].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point; lineChartDefect.Series[name].MarkerSize = 5; lineChartDefect.Series[name].MarkerColor = ChartColor[labelIndex]; lineChartDefect.Series[name].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle; } lineChartDefect.Series[name].Points.AddXY(rowItem.CentreX, rowItem.CentreY / 100); } lineChartDefect.ChartAreas[0].AxisX.Minimum = XSizeRange[0]; lineChartDefect.ChartAreas[0].AxisX.Maximum = XSizeRange[1]; lineChartDefect.ChartAreas[0].AxisY.Minimum = YSizeRange[0]; lineChartDefect.ChartAreas[0].AxisY.Maximum = YSizeRange[1]; //X轴数据类型 //option.XAxisType = UIAxisType.Value; //设置X/Y轴显示范围 //option.XAxis.SetRange(XSizeRange[0], XSizeRange[1]); //option.YAxis.SetRange(YSizeRange[0], YSizeRange[1]); //坐标轴显示小数位数 //option.XAxis.AxisLabel.DecimalPlaces = option.YAxis.AxisLabel.DecimalPlaces = 1; //X/Y轴画参考线 //option.YAxisScaleLines.Add(new UIScaleLine("上限", 3.5, Color.Red)); //option.YAxisScaleLines.Add(new UIScaleLine("下限", 2.2, Color.Gold)); //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(3).DateTimeString(), dt.AddHours(3), Color.Red)); //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(6).DateTimeString(), dt.AddHours(6), Color.Red)); //option.ToolTip.Visible = true; //option.ToolTip.Formatter = "怎么自定义X,Y显示名称??{X}"; //option.Title = new UITitle(); //option.Title.Text = ""; //option.Title.SubText = ""; } //string preCode = ""; //UILineSeries series = null; //foreach (var item in lstData) //{ // if (preCode != item.Code)//加一组新类型及样式 // { // preCode = item.Code; // var one = Config.getDefectItem(item.Code); // if (one == null) // { // continue; // } // JObject objItem = one as JObject; // Color color = ColorTranslator.FromHtml(objItem.Value("color")); // series = option.AddSeries(new UILineSeries(objItem.Value("name"), color));//加一组 // series.Symbol = UILinePointSymbol.Star; // series.SymbolSize = 4; // series.SymbolLineWidth = 2; // series.ShowLine = false; // series.SymbolColor = color; // //数据点显示小数位数(针对当前UILineSeries) // series.XAxisDecimalPlaces = 1; // series.YAxisDecimalPlaces = 2; // //series.Smooth = false; // } // series.Add(item.CentreX, item.CentreY / 100); //cm -> m //} //==== //option.GreaterWarningArea = new UILineWarningArea(3.5); //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold); //this.BeginInvoke(new System.Action(() => //{ //this.lineChartDefect.SetOption(option); //series.UpdateYData();//按序号更新Y轴值(可设置值超出范围用于闪烁) //})); } /// /// 重新门幅宽度 /// /// /// 卷长度 /// 幅宽 private void reDrawFaceWidth(List points, double[] XSizeRange, double[] YSizeRange) { //AddTextEvent($"绘图", $"门幅宽度, W={string.Join(", ", XSizeRange)},H={string.Join(", ", YSizeRange)}, LastData={JsonConvert.SerializeObject(points[points.Count-1])}"); if (YSizeRange[0] == YSizeRange[1]) { YSizeRange[0] -= YSizeRange[0] / 10f; YSizeRange[1] += YSizeRange[1] / 10f; } XSizeRange[0] /= 100; XSizeRange[1] /= 100; //防止超限 XSizeRange[1] += 0.01; YSizeRange[1] += 0.1; lineChartFaceWidth.Series.Clear(); lineChartFaceWidth.Series.Add("面宽"); lineChartFaceWidth.ChartAreas[0].AxisX.Title = "长度(m)"; lineChartFaceWidth.ChartAreas[0].AxisY.Title = "宽度(cm)"; lineChartFaceWidth.Series["面宽"].ChartType = SeriesChartType.Line; lineChartFaceWidth.Series["面宽"].MarkerSize = 5; lineChartFaceWidth.Series["面宽"].MarkerColor = Color.Blue; lineChartFaceWidth.Series["面宽"].MarkerStyle = MarkerStyle.Circle; //UILineOption option = new UILineOption(); //option.XAxis.Name = "长度(米)"; //option.YAxis.Name = "面宽(cm)"; //option.Grid.Top = 20; //option.Grid.Right = 20; //X轴数据类型 //option.XAxisType = UIAxisType.Value; //设置X/Y轴显示范围 //option.XAxis.SetRange(XSizeRange[0], XSizeRange[1]); //option.YAxis.SetRange(YSizeRange[0], YSizeRange[1]); //坐标轴显示小数位数 //option.XAxis.AxisLabel.DecimalPlaces = option.YAxis.AxisLabel.DecimalPlaces = 1; //X/Y轴画参考线 //option.YAxisScaleLines.Add(new UIScaleLine("上限", 3.5, Color.Red)); //option.YAxisScaleLines.Add(new UIScaleLine("下限", 2.2, Color.Gold)); //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(3).DateTimeString(), dt.AddHours(3), Color.Red)); //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(6).DateTimeString(), dt.AddHours(6), Color.Red)); //option.ToolTip.Visible = true; //option.ToolTip.Formatter = "怎么自定义X,Y显示名称??{X}"; //option.Title = new UITitle(); //option.Title.Text = ""; //option.Title.SubText = ""; //Color color = Color.Blue; //UILineSeries series = null; //series = option.AddSeries(new UILineSeries("面宽", color)); //series.Symbol = UILinePointSymbol.Circle; //series.ShowLine = true; //series.SymbolSize = 4; //series.SymbolLineWidth = 2; //series.SymbolColor = color; ////数据点显示小数位数(针对当前UILineSeries) //series.XAxisDecimalPlaces = 2; //series.YAxisDecimalPlaces = 1; lineChartFaceWidth.ChartAreas[0].AxisY.Maximum = YSizeRange[1]; lineChartFaceWidth.ChartAreas[0].AxisY.Minimum = YSizeRange[0]; lineChartFaceWidth.ChartAreas[0].AxisX.Maximum = XSizeRange[1]; lineChartFaceWidth.ChartAreas[0].AxisX.Minimum = XSizeRange[0]; float x; foreach (var item in points) { x = item[0] / 100; //cm -> m //series.Add(x, item[1]); this.lineChartFaceWidth.Series["面宽"].Points.AddXY((float)Math.Round(x, 2), (float)Math.Round(item[1], 2)); } //==== //option.GreaterWarningArea = new UILineWarningArea(3.5); //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold); //this.BeginInvoke(new System.Action(() => //{ //this.lineChartFaceWidth.SetOption(option); //})); } // 截图操作函数 private byte[] captureControl(System.Windows.Forms.Control control) { Bitmap bmp = new Bitmap(control.Width, control.Height); Graphics graphics = Graphics.FromImage(bmp); Rectangle rectangle = new Rectangle(0, 0, control.Width, control.Height); control.DrawToBitmap(bmp, rectangle); //bmp to jpg MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//bmp是已经获得的bitmap数据 byte[] bytes = ms.GetBuffer(); ms.Close(); graphics.Dispose(); return bytes; //bitmap.Save(@"C:\Images\Capture.jpg", ImageFormat.Jpeg); //return Image.FromStream(new MemoryStream(bytes)); } public class JsonProductDefects { [Description("产品品名")] public string ProName { get; set; } [Description("产品批号")] public string BatchId { get; set; } [Description("产品卷号")] public string ReelId { get; set; } [Description("检验长度")] public string Len { get; set; } [Description("平均速度")] public string Speed { get; set; } [Description("等级")] public string Grade { get; set; } [Description("检验时间")] public string DateTime { get; set; } [Description("疵点统计")] public List DefectTotal = new List(); public List DefectDetail = new List(); [Description("检测设置")] public Models.Product Pdt { get; set; } [Description("物面分辨率")] public string xyPix { get; set; } } public class JDefectTotal { [Description("疵点名")] public string Name { get; set; } [Description("疵点数")] public int Count { get; set; } } public class JDefectDetail { [Description("源图")] public int Index { get; set; } [Description("名称")] public string Name { get; set; } [Description("X(cm)")] public double X { get; set; } [Description("Y(米)")] public double Y { get; set; } [Description("宽(cm)")] public double Width { get; set; } [Description("高(cm)")] public double Height { get; set; } [Description("置信度")] public double ZXD { get; set; } [Description("面积(cm^2)")] public double Area { get; set; } [Description("对比度")] public double Contrast { get; set; } } #endregion #endregion #endregion #region 系统上设置界面 #region 串口获取 private void GetComPort() { var comNameList = SerialPort.GetPortNames().ToList(); comNameList.ForEach(comName => { this.cobLightPortNum.Items.Add(comName); this.cbJimiqiCom.Items.Add(comName); }); //显示所有打印机 //if (SysMgr.Instance.PrintControl != null) //{ // List list = SysMgr.Instance.PrintControl.GetPrintersName(); // foreach (string printer in list) // { // cboPrinters.Items.Add(printer); // cboPrinters2.Items.Add(printer); // } //} } #endregion #region 界面刷新&保存 private void RefeshSysParams() { chkBuzzer.Checked = ConfMgr.Instance.SysConfigParams.OpenBuzzer; //chkDoorSensor.Checked = ConfMgr.Instance.SysConfigParams.OpenDoor; cbIODev.Checked = ConfMgr.Instance.SysConfigParams.OpenIO; cbPLC.Checked = ConfMgr.Instance.SysConfigParams.OpenPLC; cbJimiqi.Checked = ConfMgr.Instance.SysConfigParams.OpenLengthCount; cbAutorun.Checked = ConfMgr.Instance.SysConfigParams.OpenAutoRun; //cbJMStop.Checked = ConfMgr.Instance.SysConfigParams.OpenLengthCountStop; //cbAIEdge.Checked = ConfMgr.Instance.SysConfigParams.OpenAIEdge; //cbEmgStop.Checked = ConfMgr.Instance.SysConfigParams.OpenEMGStop; cbOpenDB.Checked = ConfMgr.Instance.SysConfigParams.OpenDB; cobLightPortNum.Text = ConfMgr.Instance.SysConfigParams.LightCom; numLightBaud.Value = ConfMgr.Instance.SysConfigParams.LightComBaud; cbJimiqiCom.Text = ConfMgr.Instance.SysConfigParams.LengthCounterCom; numJimiqiBaud.Value = ConfMgr.Instance.SysConfigParams.LengthCounterComBaud; tbIODevNum.Text = ConfMgr.Instance.SysConfigParams.IODevName; //tbIOCfgPath.Text = ConfMgr.Instance.SysConfigParams.IOCfgPath; tbPLCIP.Text = ConfMgr.Instance.SysConfigParams.PLC_IP; tbCamCfgPath.Text = ConfMgr.Instance.SysConfigParams.CamPath_1; tbCamCfgPath2.Text = ConfMgr.Instance.SysConfigParams.CamPath_2; numCamIndex.Value = ConfMgr.Instance.SysConfigParams.CamIndex_1; numCamIndex2.Value = ConfMgr.Instance.SysConfigParams.CamIndex_2; numCamDev.Value = ConfMgr.Instance.SysConfigParams.CamDev_1; numCamDev2.Value = ConfMgr.Instance.SysConfigParams.CamDev_2; tbDefectPath.Text = ConfMgr.Instance.SysConfigParams.ImageDir; chkSave1.Checked = ConfMgr.Instance.SysConfigParams.DefectSrcImag.AutoSave; chkSave2.Checked = ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoSave; chkSave3.Checked = ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoSave; chkSave4.Checked = ConfMgr.Instance.SysConfigParams.CamImag.AutoSave; chkDefect_Path_AutoClear.Checked = ConfMgr.Instance.SysConfigParams.DefectSrcImag.AutoDelete; numDefect_Path_AutoClear.Value = (decimal)ConfMgr.Instance.SysConfigParams.DefectSrcImag.AutoDeleteDays; //chkSave2.Checked = ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoSave; //tbDefectSmallPath.Text = ConfMgr.Instance.SysConfigParams.DefectSmallImag.SavePath; //chkDefect_Small_Path_AutoClear.Checked = ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoDelete; //numDefect_Small_Path_AutoClear.Value = (decimal)ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoDeleteDays; //chkSave3.Checked = ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoSave; //tbDefectCompressSavePath.Text = ConfMgr.Instance.SysConfigParams.DefectSplicImag.SavePath; //chkDefect_Compress_SavePath_AutoClear.Checked = ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoDelete; //numDefect_Compress_SavePath_AutoClear.Value = (decimal)ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoDeleteDays; //chkSave4.Checked = ConfMgr.Instance.SysConfigParams.CamImag.AutoSave; //tbCamIamgePath.Text = ConfMgr.Instance.SysConfigParams.CamImag.SavePath; //cbAutoDel.Checked = ConfMgr.Instance.SysConfigParams.CamImag.AutoDelete; //numCamimageAutoDelDay.Value = (decimal)ConfMgr.Instance.SysConfigParams.CamImag.AutoDeleteDays; //tbModelPath.Text = ConfMgr.Instance.SysConfigParams.AIModelPath; //tbPdtPath.Text = ConfMgr.Instance.ProjectDir; //tbLogPath.Text = ConfMgr.Instance.SysConfigParams.LogPath; //ckbAutoClear.Checked = ConfMgr.Instance.SysConfigParams.AutoDeleteLog; //numLogDays.Value = (decimal)ConfMgr.Instance.SysConfigParams.AutoDeleteLogData; numViewX.Value = (decimal)ConfMgr.Instance.SysConfigParams.Cm2px_x; numViewY.Value = (decimal)ConfMgr.Instance.SysConfigParams.Cm2px_y; numMid.Value = (decimal)ConfMgr.Instance.SysConfigParams.MidCoin; //numKW.Value = (decimal)ConfMgr.Instance.SysConfigParams.HolePx; //numL.Value = (decimal)ConfMgr.Instance.SysConfigParams.LCrop; //numR.Value = (decimal)ConfMgr.Instance.SysConfigParams.RCrop; /////////////Print//////////////// //this.cbOpenBarTenderPrint.Checked = ConfMgr.Instance.SysConfigParams.EnableLabelPrint; //this.cboPrinters.SelectedItem = ConfMgr.Instance.SysConfigParams.LabelPrinterName; //this.cbOpenExcelPrint.Checked = ConfMgr.Instance.SysConfigParams.EnableExcelPrint; //this.cboPrinters2.SelectedItem = ConfMgr.Instance.SysConfigParams.ExcelPrinterName; //////////////////////////////// ////////////////本地云端//////////////// //cbOpenCloud.Checked = ConfMgr.Instance.SysConfigParams.OpenCloud; //tbCloudName.Text = ConfMgr.Instance.SysConfigParams.CloudThisName; //tbCloudIP.Text = ConfMgr.Instance.SysConfigParams.CloudServerIP; //numCloudPort.Value = (decimal)ConfMgr.Instance.SysConfigParams.CloudServerPort; //tbCloudUser.Text = ConfMgr.Instance.SysConfigParams.CloudUser; //tbCloudPassword.Text = ConfMgr.Instance.SysConfigParams.CloudPassword; //////////////////////////////////////// /// this.cbMX1.Checked = ConfMgr.Instance.SysConfigParams.Cam1_flipXY; //this.cbMY1.Checked = ConfMgr.Instance.SysConfigParams.Cam1_flipY; this.cbMX2.Checked = ConfMgr.Instance.SysConfigParams.Cam2_flipXY; //this.cbMY2.Checked = ConfMgr.Instance.SysConfigParams.Cam2_flipY; this.numStopDis.Value = (decimal)ConfMgr.Instance.SysConfigParams.StopLookDis; //this.numStopDecTime.Value = (decimal)ConfMgr.Instance.SysConfigParams.StopDecTime; this.numStopPicCnt.Value = ConfMgr.Instance.SysConfigParams.StopImageCnt; this.numDBdis.Value = (decimal)ConfMgr.Instance.SysConfigParams.CamToDBDis; } private void GetParamsSave() { SysConfigParams configParams = new SysConfigParams(); configParams = ConfMgr.Instance.SysConfigParams; configParams.OpenBuzzer = chkBuzzer.Checked; //configParams.OpenDoor = chkDoorSensor.Checked; configParams.OpenIO = cbIODev.Checked; configParams.OpenPLC = cbPLC.Checked; configParams.OpenLengthCount = cbJimiqi.Checked; configParams.OpenAutoRun = cbAutorun.Checked; configParams.OpenDB = cbOpenDB.Checked; configParams.LightCom = cobLightPortNum.Text; configParams.LightComBaud = (int)numLightBaud.Value; configParams.LengthCounterCom = cbJimiqiCom.Text; configParams.LengthCounterComBaud = (int)numJimiqiBaud.Value; configParams.IODevName = tbIODevNum.Text; //configParams.IOCfgPath = tbIOCfgPath.Text; configParams.PLC_IP = tbPLCIP.Text; configParams.PLC_Rack = 0; configParams.PLC_Solt = 1; configParams.CamPath_1 = tbCamCfgPath.Text; configParams.CamPath_2 = tbCamCfgPath2.Text; configParams.CamIndex_1 = (int)numCamIndex.Value; configParams.CamIndex_2 = (int)numCamIndex2.Value; configParams.CamDev_1 = (int)numCamDev.Value; configParams.CamDev_2 = (int)numCamDev2.Value; configParams.ImageDir = tbDefectPath.Text; configParams.DefectSrcImag.AutoSave = chkSave1.Checked; configParams.DefectSrcImag.SavePath = $"{configParams.ImageDir}//原图"; configParams.DefectSrcImag.AutoDelete = chkDefect_Path_AutoClear.Checked; configParams.DefectSrcImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value; configParams.DefectSplicImag.AutoSave = chkSave2.Checked; configParams.DefectSplicImag.SavePath = $"{configParams.ImageDir}//瑕疵图"; configParams.DefectSplicImag.AutoDelete = chkDefect_Path_AutoClear.Checked; configParams.DefectSplicImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value; configParams.DefectSmallImag.AutoSave = chkSave3.Checked; configParams.DefectSmallImag.SavePath = $"{configParams.ImageDir}//瑕疵小图"; configParams.DefectSmallImag.AutoDelete = chkDefect_Path_AutoClear.Checked; configParams.DefectSmallImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value; configParams.CamImag.AutoSave = chkSave4.Checked; configParams.CamImag.SavePath = $"{configParams.ImageDir}//相机图"; configParams.CamImag.AutoDelete = chkDefect_Path_AutoClear.Checked; configParams.CamImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value; //configParams.AIModelPath = tbModelPath.Text; //configParams.ProductPath = tbPdtPath.Text; //configParams.LogPath = tbLogPath.Text; //configParams.AutoDeleteLog = ckbAutoClear.Checked; //configParams.AutoDeleteLogData = (double)numLogDays.Value; configParams.Cm2px_x = (int)numViewX.Value; configParams.Cm2px_y = (int)numViewY.Value; configParams.MidCoin = (int)numMid.Value; ////////////////////Print////////////////////////// //configParams.EnableLabelPrint = this.cbOpenBarTenderPrint.Checked; //if (this.cboPrinters.SelectedItem != null) // configParams.LabelPrinterName = this.cboPrinters.SelectedItem.ToString(); //configParams.EnableExcelPrint = this.cbOpenExcelPrint.Checked; //if (this.cboPrinters2.SelectedItem != null) // configParams.ExcelPrinterName = this.cboPrinters2.SelectedItem.ToString(); ///////////////////////////////////////////////// ///////本地云端//////////////////////////// //configParams.OpenCloud = this.cbOpenCloud.Checked; //configParams.CloudThisName = this.tbCloudName.Text; //configParams.CloudServerIP = this.tbCloudIP.Text; //configParams.CloudServerPort = (int)this.numCloudPort.Value; //configParams.CloudUser = this.tbCloudUser.Text; //configParams.CloudPassword = this.tbCloudPassword.Text; /////////////////////////////////////////// /// configParams.Cam1_flipXY = this.cbMX1.Checked; configParams.Cam2_flipXY = this.cbMX2.Checked; configParams.StopLookDis = (double)this.numStopDis.Value; //configParams.StopDecTime = (double)this.numStopDecTime.Value; configParams.StopImageCnt = (int)this.numStopPicCnt.Value; configParams.CamToDBDis = (double)this.numDBdis.Value; ConfMgr.Instance.WriteSysConfParams(configParams); } #endregion #region 文件路径选择 private void btnClearPath_Click(object sender, EventArgs e) { PictureBox pb = (PictureBox)sender; string path = ""; if (pb.Name == btnClearDefect_Path.Name) this.tbDefectPath.Text = path; } private void tbDefectPath_Click(object sender, EventArgs e) { TextBox tb = (TextBox)sender; string path = ConfMgr.SelectFolder(Application.StartupPath); if (!string.IsNullOrWhiteSpace(path)) { tb.Text = path; } } private void tbCamCfgPath_Click(object sender, EventArgs e) { TextBox tb = (TextBox)sender; string path = ConfMgr.SelectFile("所有文件|*.*", Application.StartupPath); if (!string.IsNullOrWhiteSpace(path)) { if (tb.Name == tbCamCfgPath.Name) this.tbCamCfgPath.Text = path; else if (tb.Name == tbCamCfgPath2.Name) this.tbCamCfgPath2.Text = path; } } #endregion #endregion #region 主界面控制 #region 按钮 private void tsbtnStart_Click(object sender, EventArgs e) { if (!SysMgr.Instance.IsRuning) { //低报警自动复位 if (SysMgr.Instance.StatusMgr.Status == SystemStsEnum.Warning) { if (SysMgr.Instance.StatusMgr.Warning == WarningEnum.Low) { SysMgr.Instance.StatusMgr.ClearWarning(); SysMgr.Instance.StatusMgr.GotoNormalStandby(); } } //提示正在报警中 if (SysMgr.Instance.StatusMgr.Status == SystemStsEnum.Warning) { FrmDialog.ShowDialog(this, "系统报警中!无法启动运行!", "警告", false); return; } this.Cursor = Cursors.WaitCursor; System.Windows.Forms.Application.DoEvents(); if (SysMgr.Instance.StatusMgr.Status != SystemStsEnum.Pause) { ResetUI(false); AddTextEvent("运行", $"启动自动检测流程"); string color = this.cbPdtColor.Text; string len = this.numPdtLength.Value.ToString(); string type = this.cbPdtType.Text; string sn = this.cbPdtSN.Text; if (string.IsNullOrEmpty(sn)) { FrmDialog.ShowDialog(this, "未输入产品单号!", "提示", false); return; } if (string.IsNullOrEmpty(color) || string.IsNullOrEmpty(type)) { FrmDialog.ShowDialog(this, "未选择颜色和产品材质!", "提示", false); return; } if (SysMgr.Instance.StartRun(this, sn, ref color, ref type, ref sn)) { this.tsbtnImpStop.Enabled = true; this.tsbtnStop.Enabled = true; this.tsbtnStart.Enabled = false; //锁定信息 this.cbPdtSN.Enabled = false; this.cbPdtColor.Enabled = false; this.numPdtLength.Enabled = false; this.cbPdtType.Enabled = false; //记录开始运行时间 RunStartTime.Restart(); //重新显示 //this.cbPdtColor.Text = name; //this.cbProductBatch.Text = batch; //this.cbProductReelNum.Text = reel; //this.cbProductNum.Text = len; //this.cbPdtType.Text = defname; ResetChart(); } } else //暂停状态开始 { if (SysMgr.Instance.ReStartRun()) { this.tsbtnStop.Enabled = true; this.tsbtnStart.Enabled = false; } } this.Cursor = Cursors.Default; } } private void tsbtnReset_Click(object sender, EventArgs e) { } private void tsbtnStop_Click(object sender, EventArgs e) { AddTextEvent("暂停", "手动暂停"); this.tsbtnStart.Enabled = true; SysMgr.Instance.Stop(); SysMgr.Instance.StatusMgr.GotoPause(); SysMgr.Instance.SendStatus(); SysMgr.Instance.LedPause(); } private void tsbtnWarning_Click(object sender, EventArgs e) { if (SysMgr.Instance.StatusMgr.Warning != WarningEnum.Normal) { AddTextEvent("清除", "手动清除报警"); SysMgr.Instance.StatusMgr.ClearWarning(); SysMgr.Instance.LedReady(); if (SysMgr.Instance.IsAuto) SysMgr.Instance.StatusMgr.GotoPause(); else SysMgr.Instance.StatusMgr.GotoNormalStandby(); SysMgr.Instance.SendStatus(); } } /// /// 结束验布 /// /// /// private void tsbtnImpStop_Click(object sender, EventArgs e) { AddTextEvent("结束验布", "手动结束验布"); SysMgr.Instance.StatusMgr.GotoPause(); SysMgr.Instance.DefectEnd(this); this.tsbtnStop.Enabled = false; this.tsbtnStart.Enabled = true; this.tsbtnImpStop.Enabled = false; SysMgr.Instance.StatusMgr.GotoNormalStandby(); SysMgr.Instance.SendStatus(); SysMgr.Instance.LedReady(); } #endregion #endregion #region 调试 private void button2_Click(object sender, EventArgs e) { Mat img = new Mat("H:\\CPL\\GeBoshi\\新建文件夹\\23_src.bmp"); HObject himg = new HObject(); //转换 OpencvUtils.MatToHObject(img, out himg); PGDetect tPGDetect = new PGDetect(); //HObject obj = new HObject(); //HOperatorSet.GenImageConst(out obj, "byte", 2048 * 8, 2048 * 2);//生成一幅图像,用byte格式,默认是黑色 //Mat initMat = new Mat(2048 * 2, 2048 * 8, MatType.CV_8UC3); if (!tPGDetect.IniOptimization(himg, ConfMgr.Instance.SysConfigParams.HalconDataPath)) throw new Exception($"传统算法({ConfMgr.Instance.SysConfigParams.HalconDataPath})初始化失败!"); Stopwatch stopwatch = Stopwatch.StartNew(); double[] ststopwatch = new double[4]; HObject ho_imgG = new HObject(); HObject ho_ImageResult3 = new HObject(); HObject ho_ImageSub = new HObject(); HTuple hv_RES, hv_gauss_filter1, hv_gauss_filter2, hv_Energy_value, hv_Region_S_value, hv_class, hv_defectinfo; int object_num = 0; stopwatch.Stop(); ststopwatch[0] = stopwatch.ElapsedMilliseconds; stopwatch.Restart(); //预处理 tPGDetect.Processing(himg, out ho_imgG, out ho_ImageResult3, out ho_ImageSub, ConfMgr.Instance.SysConfigParams.HalconDataPath, out hv_RES, out hv_gauss_filter1, out hv_gauss_filter2, out hv_Energy_value, out hv_Region_S_value, out hv_class); stopwatch.Stop(); ststopwatch[1] = stopwatch.ElapsedMilliseconds; stopwatch.Restart(); //算法处理 tPGDetect.Detect(himg, ho_imgG, ho_ImageResult3, ho_ImageSub, hv_Energy_value, hv_Region_S_value, hv_class, out hv_defectinfo, out object_num); stopwatch.Stop(); ststopwatch[2] = stopwatch.ElapsedMilliseconds; stopwatch.Restart(); //打标 double[] defectinfo = hv_defectinfo.ToDArr(); //List DefectLabelInfoList = new List(); for (int i = 0; i < object_num; i++) { #region 检测信息汇总 int index = i * 6; // 打印输出信息(示例代码,根据实际情况进行修改和格式化) // 获取输出信息 int x = (int)defectinfo[index]; int y = (int)defectinfo[index + 1]; int w = (int)defectinfo[index + 2]; int h = (int)defectinfo[index + 3]; int classId = (int)defectinfo[index + 4]; double confidence = Math.Round(defectinfo[index + 5], 2); //置信度 int px = x; //var cmX = Math.Round(px * task.widthRatio / task.cm2px_x, 2); //var cmY = Math.Round((task.bmp.Height - y - h) * task.widthRatio / task.cm2px_y, 2);//外面计Y从右下角为原点 //DefectLabelInfoList.Add(new DefectLabelInfo() //{ // x = x, // y = y, // w = w, // h = h, // classId = classId, // confidence = confidence, //置信度 // cmW = Math.Round(w * task.widthRatio / task.cm2px_x, 2), // cmH = Math.Round(h * task.widthRatio / task.cm2px_y, 2), // i = i, // j = i, //}); ////y = image_hight-y-h;//转到右下角为原点 //task.excelTable.Rows.Add($"{task.photoIndex}", cmX, cmY, //Math.Round(w * task.widthRatio / task.cm2px_x, 2), Math.Round(h * task.widthRatio / task.cm2px_y, 2), //i, classId, confidence, 0); int penLine = 20; //打标 var point1 = new OpenCvSharp.Point(x, y); var point2 = new OpenCvSharp.Point(point1.X + w + penLine / 2, point1.Y + h + penLine / 2); Cv2.Rectangle(img, point1, point2, new Scalar(0.0, 0.0, 255.0), penLine);//画打标点 //切小图 int left, top, decX, decY; int tdecX = (w / 2) / 2; int tdecY = w / h > 4 ? w / 8 : (h / 1) / 2; decX = (w > 236 ? tdecX : 256 - w) / 2; decY = (h > 236 ? tdecY : 256 - h) / 2; left = point1.X - decX; top = point1.Y - decY; if (left < 0) left = 0; if (top < 0) top = 0; int width = w + decX * 2; int height = h + decY * 2; if (left + width > img.Width - 1) width = img.Width - left - 1; if (top + height > img.Height - 1) height = img.Height - top - 1; Rect roi = new Rect(left, top, width, height); //task.lstDefectBmp.Add(new Mat(task.bmpTag, roi).Clone()); #endregion } stopwatch.Stop(); ststopwatch[3] = stopwatch.ElapsedMilliseconds; } #endregion } }