public override void QueryReset() { ReSetInfo(); MySmartThreadPool.Instance().QueueWorkItem(() => { if (!splashScreenManager.IsSplashFormVisible) { splashScreenManager.ShowWaitForm(); } SpcModel spcModel = DB.Instance(); try { List <RetStatistical> rets = spcModel.Database.SqlQuery <RetStatistical>(QueryPars.GetMainStatisticalStr()).ToList(); this.BeginInvoke((Action)(() => { gridControl_Results.DataSource = rets; })); } catch (Exception er) { } finally { if (splashScreenManager.IsSplashFormVisible) { splashScreenManager.CloseWaitForm(); } spcModel.Dispose(); } }); }
private void SearchForm_Load(object sender, EventArgs e) { MySmartThreadPool.Instance().QueueWorkItem(() => { SpcModel spcModel = DB.Instance(); try { List <AoiSoftwares> aoiSoftwares = spcModel.softwares.ToList(); this.BeginInvoke((Action <List <AoiSoftwares> >)((res) => { gridLookUpEdit_Software.Properties.DataSource = res; gridLookUpEdit_Software.Properties.DisplayMember = "software_name"; gridLookUpEdit_Software.Properties.ValueMember = "id"; }), aoiSoftwares); } catch (Exception er) { int a = 0; } finally { spcModel.Dispose(); } }); }
public void TopGridView(DataGridView dataGridView) { AoiModel aoiModel = DB.GetAoiModel(); Action <DataGridView> t = (control) => { lock (aoiModel) { string AllPcbNums = "(select count(*) from pcbs)"; string PassPcbNums = "(select count(*) from pcbs where is_misjudge = 0 and is_error = 0)"; string ErrorPcbNums = "(select count(*) from pcbs)"; string MisreportPcbNums = "(select count(*) from pcbs where is_misjudge = 1)"; string MisreportRate = MisreportPcbNums + "/" + AllPcbNums; string PassRate = PassPcbNums + "/" + AllPcbNums; string final = "select " + AllPcbNums + " as AllPcbNums, " + ErrorPcbNums + " as ErrorPcbNums, " + MisreportPcbNums + " as MisreportPcbNums, " + MisreportRate + " as MisreportRate, " + PassRate + "as PassRate"; var tables = aoiModel.Database.SqlQuery <SqlQueryData1>(final).ToList(); //.SqlQuery("select *from BlogMaster where UserId='3'"); this.BeginInvoke((Action)(() => { bindingSourceAll.DataSource = tables; control.DataSource = bindingSourceAll; })); aoiModel.Dispose(); } }; MySmartThreadPool.Instance().QueueWorkItem <DataGridView>(t, dataGridView); }
/// <summary> /// AI检测结束共用函数 /// </summary> /// <param name="oneStitchSidePcb"></param> public void aiDone(string savePath) { Console.WriteLine(allDetectNum); if (allDetectNum == nowPcb.AllPhotoNum) { this.BeginInvoke((Action)(() => { fuckDetectNum = 0; try { MySmartThreadPool.InstanceSmall().WaitForIdle(); Console.WriteLine("InstanceSmall: " + MySmartThreadPool.InstanceSmall().InUseThreads); Console.WriteLine("Instance: " + MySmartThreadPool.Instance().InUseThreads); //这里可以直接发送了!!!!!! //结束计时 //MessageBox.Show("执行查询总共使用了, total :" + times + "s 秒"); try { JsonData <Pcb> jsonData = new JsonData <Pcb>(); jsonData.data = nowPcb; jsonData.executionTime = 11; jsonData.ngNum = nowPcb.results.Count; var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; string[] props = { "FrontPcb", "BackPcb" }; //排除掉,不能让前端看到的字段。为true的话就是只保留这些字段 jSetting.ContractResolver = new LimitPropsContractResolver(props, false); string res = JsonConvert.SerializeObject(jsonData, jSetting); RabbitMQClientHandler.GetInstance() .TopicExchangePublishMessageToServerAndWaitConfirm("", "work", "work", res); File.WriteAllText(Path.Combine(savePath, "result.json"), ConvertJsonString(res)); } catch (Exception er) { MessageBox.Show(" 发送队列出错" + er.Message); //LogHelper.WriteLog("连接队列失败!!!", er); } } catch (Exception er) { } finally { allDetectNum = 0; } })); } }
private void btnLogin_Click(object sender, EventArgs e) { lbResult.Visible = true; lbResult.Text = "登录中......"; MySmartThreadPool.Instance().QueueWorkItem((username, password) => { AoiModel aoiModel = DB.GetAoiModel(); try { string md5Pass = Utils.GenerateMD5(password); User user = aoiModel.users.Where(u => u.Username == username && u.Password == md5Pass).FirstOrDefault(); if (user != null) { this.DialogResult = DialogResult.OK; this.Close(); } else { this.BeginInvoke((Action)(() => { lbResult.Text = "用户名或密码错误"; lbResult.Visible = true; })); } } catch (Exception err) { try { this.BeginInvoke((Action)(() => { lbResult.Text = "连接数据库出错"; lbResult.Visible = true; })); //LogHelper.WriteLog("Login error", err); } catch (Exception er) { //LogHelper.WriteLog("Login error", err); } } finally { aoiModel.Dispose(); } }, tbUsername.Text.Trim(), tbPassword.Text.Trim()); }
private void ScreenEvent(BitmapInfo bitmapInfo) { lock (obj) { if (this.InvokeRequired) { BeginInvoke(new ImageReadyEventScreen(ScreenEvent), bitmapInfo); return; } else { try { bitmap = bitmapInfo.m_Bitmap; bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); //指定不进行翻转的 180 度旋转 (垂直翻转+水平翻转) nowPcb.FrontPcb.bitmaps.Enqueue(new OneStitchSidePcb.BitmapInfo() { bitmap = BitmapScaleHelper.ScaleToSize(bitmap, (float)0.5), name = "/F" + fuckDetectNum + ".jpg" }); fuckDetectNum++; //Aoi.StitchMain(nowPcb.FrontPcb, onStitchCallBack); MySmartThreadPool.Instance().QueueWorkItem(() => { lock (nowPcb.FrontPcb) { Aoi.StitchMain(nowPcb.FrontPcb, onStitchCallBack); } }); bitmap.Save(nowPcb.FrontPcb.savePath + "/F" + fuckDetectNum + ".jpg"); //this.pictureBox1.Image = bitmap; //if (needsave) //{ // bitmaps.Enqueue(bitmap); //} } catch (Exception e) { Loghelper.WriteLog("获取照片失败", e); throw e; } } } }
public void Tab1Ini(QueryPars q) { TopGridView(dgvAll2); AoiModel aoiModel = DB.GetAoiModel(); Action <QueryPars> t = (v) => { lock (aoiModel) { var tables = aoiModel.Database.SqlQuery <SqlQueryData2NG>("select ng_type as Type, count(*) as Nums from results where create_time between '" + v.startTime + "' and '" + v.endTime + "' GROUP BY ng_type").ToList(); //.SqlQuery("select *from BlogMaster where UserId='3'"); this.BeginInvoke((Action)(() => { bindingSourceTab1.DataSource = tables; })); var xData = aoiModel.Database.SqlQuery <string>("select ng_type as Type from results where create_time between '" + v.startTime + "' and '" + v.endTime + "' GROUP BY ng_type ORDER BY ng_type").ToList(); var yData = aoiModel.Database.SqlQuery <string>("select count(*) * 100 /(select count(*) from results where create_time between '" + v.startTime + "' and '" + v.endTime + "') as rate " + " from results where create_time between '" + v.startTime + "' and '" + v.endTime + "' GROUP BY ng_type ORDER BY ng_type").ToList(); this.BeginInvoke((Action)(() => { chartTab1.Series[0]["PieLabelStyle"] = "Outside"; //将文字移到外侧 chartTab1.Series[0]["PieLineColor"] = "Black"; //绘制黑色的连线。 chartTab1.Series[0].Points.DataBindXY(xData, yData); })); aoiModel.Dispose(); } }; MySmartThreadPool.Instance().QueueWorkItem <QueryPars>(t, q); }
/// <summary> /// AI大图检测 /// </summary> /// <param name="isFront">是否是正面</param> /// <param name="bitmapInfo">图片信息</param> /// <param name="scaleRect">已经缩放的矩形框在缩放大图的位置</param> /// <param name="scale">缩放的尺度</param> /// <param name="confidence">置信度</param> /// <param name="savePath">图像保存地址</param> public void aiDetect(bool isFront, OneStitchSidePcb.BitmapInfo bitmapInfo, Rectangle scaleRect, double scale, float confidence, string savePath) { //Console.WriteLine(allDetectNum); MySmartThreadPool.InstanceSmall().QueueWorkItem((name, bmp) => { try { bbox_t_container boxlist = new bbox_t_container(); using (MemoryStream stream = new MemoryStream()) { bmp.Save(stream, ImageFormat.Jpeg); byte[] byteImg = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(byteImg, 0, Convert.ToInt32(stream.Length)); int n = -1; lock (detectKey) { n = AITestSDK.detect_opencv_mat(byteImg, byteImg.Length, ref boxlist, confidence); } if (n == -1) { Console.WriteLine("AI调用失败"); } else { resultJoin(name, isFront, scale, scaleRect, boxlist, new List <string>() { "NG" }, new Point(0, 0)); } } } catch (Exception er) { } finally { bmp.Dispose(); allDetectNum++; aiDone(savePath); } //最总检测的结果还是放在这里发送吧 }, bitmapInfo.name, (Bitmap)bitmapInfo.bitmap.Clone()); }
private void QueryCriteria_Load(object sender, EventArgs e) { AoiModel aoiModel = DB.GetAoiModel(); Action t = () => { lock (aoiModel) { var tables = aoiModel.pcbNames.Select(s => new { s.Name }).ToList(); this.BeginInvoke((Action)(() => { combPcbName.DataSource = tables; combPcbName.ValueMember = "Name"; combPcbName.DisplayMember = "Name"; })); aoiModel.Dispose(); } }; MySmartThreadPool.Instance().QueueWorkItem(t); }
public override void QueryReset() { ReSetInfo(); if (QueryPars.enableResult) { //string aa = gridView_Results.ActiveFilterString; gridView_Results.ActiveFilterString = String.Format("[ng_str] = '{0}'", QueryPars.ng_type); } MySmartThreadPool.Instance().QueueWorkItem(() => { if (!splashScreenManager.IsSplashFormVisible) { splashScreenManager.ShowWaitForm(); } SpcModel spcModel = DB.Instance(); try { List <AoiPcbs> aoiPcbs = spcModel.pcbs.SqlQuery(QueryPars.GetPcbsQueryStr()).ToList(); this.BeginInvoke((Action)(() => { gridControl_Pcbs.DataSource = aoiPcbs; })); } catch (Exception er) { } finally { if (splashScreenManager.IsSplashFormVisible) { splashScreenManager.CloseWaitForm(); } spcModel.Dispose(); } }); }
private void MessagePopupForm_Load(object sender, EventArgs e) { MySmartThreadPool.InstanceLoadModel().QueueWorkItem(() => { try { LoadBalance.Ini(INIHelper.ReadInteger("AiBaseConfig", "LoadModelNum", 0, Application.StartupPath + "/config.ini")); this.DialogResult = DialogResult.OK; } catch (System.AccessViolationException er) { LogHelper.WriteLog("AI初始化失败", er); this.DialogResult = DialogResult.No; } finally { this.BeginInvoke((Action)(() => { this.Close(); })); } }); }
private void gridLookUpEdit_Software_EditValueChanged(object sender, EventArgs e) { MySmartThreadPool.Instance().QueueWorkItem((val) => { SpcModel spcModel = DB.Instance(); try { List <AoiNgTypes> ngTypes = spcModel.ngTypes.Where(p => p.software_id == val.ToString()).ToList(); this.BeginInvoke((Action)(() => { gridLookUpEdit_NgTypeList.Properties.DataSource = ngTypes; gridLookUpEdit_NgTypeList.Properties.DisplayMember = "ng_str"; gridLookUpEdit_NgTypeList.Properties.ValueMember = "id"; })); } catch (Exception er) { } finally { spcModel.Dispose(); } }, gridLookUpEdit_Software.EditValue); }
// 队列处理回调!!所有的界面操作方法写在这个函数里 public void doWork(string message) { if (InvokeRequired) { // If called from a different thread, we must use the Invoke method to marshal the call to the proper GUI thread. // The grab result will be disposed after the event call. Clone the event arguments for marshaling to the GUI thread. BeginInvoke(new RabbitmqMessageCallback(doWork), message); return; } LogHelper.WriteLog("接收到数据\n" + message); //mainChannel = channel; //处理完成,手动确认 //channel.BasicAck(Rabbitmq.deliveryTag, false); //Thread.Sleep(1000); if (workPause) { return; } if (isLeisure) { isLeisure = false; try { // 反序列化json JsonData <Pcb> lst2 = JsonConvert.DeserializeObject <JsonData <Pcb> >(message, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); if (lst2 == null) { RabbitMQClientHandler.ListenChannel.BasicAck(RabbitMQClientHandler.deliveryTag, false); return; } ; #region 开启线程更新数据库 string path = ConfigurationManager.AppSettings["FtpPath"] + lst2.data.PcbPath + "/"; string frontImg = path + "front.jpg"; string backImg = path + "back.jpg"; AoiModel aoiModel = DB.GetAoiModel(); Action <Pcb> t = (pcb) => { lock (aoiModel) { string res = ""; try { if (pcb.results.Count > 0) { pcb.IsError = 1; } aoiModel.pcbs.Add(pcb); aoiModel.results.AddRange(pcb.results); //aoiModel.markers.AddRange(pcb.markers); if (aoiModel.SaveChanges() > 0) { res = pcb.Id + "-" + pcb.PcbNumber + " 已入库"; } else { res = pcb.Id + "-" + pcb.PcbNumber + " 入库失败"; } aoiModel.Dispose(); } catch (Exception er)//UpdateException { res = pcb.Id + "-" + pcb.PcbNumber + " 入库失败,ID冲突"; } this.BeginInvoke((Action)(() => { this.Text = "检验端-v2.0 [" + res + "]"; })); #region 加载ng列表 pcbDetails.BeginInvoke((Action)(() => { pcbDetails.xxxx(lst2.data); pcbDetails.changePause("暂停", true); })); #endregion } }; MySmartThreadPool.Instance().QueueWorkItem <Pcb>(t, lst2.data); #endregion #region 硬盘监控 //MySmartThreadPool.Instance().QueueWorkItem((str, lim) => { // try // { // string disk = str.Split(':')[0]; // long freeGb = Utils.GetHardDiskFreeSpace(disk); // if (freeGb < lim) // { // MessageBox.Show(disk +"盘空间已经不足"+lim+"GB,请及时清理", "报警", MessageBoxButtons.OK, MessageBoxIcon.Warning); // } // } // catch (Exception ex) // { // throw ex; // } //}, ConfigurationManager.AppSettings["FtpPath"], Convert.ToInt32(ConfigurationManager.AppSettings["DiskRemind"])); #endregion #region 处理图片 //Graphics ghFront = null; //Graphics ghBack = null; //int drawNum = 0; //int allNum = lst2.data.results.Count; //// 画框所有线程中调用显示图片的委托 //Action showImg = () => //{ // drawNum++; // if (drawNum >= allNum) // { // if (imageFront != null) // { // twoSidesPcb.BeginInvoke((Action)(() => // { // twoSidesPcb.showFrontImg(imageFront); // })); // imageFront.Save(path + "drawfront.jpg"); // } // if (imageBack != null) // { // twoSidesPcb.BeginInvoke((Action)(() => // { // twoSidesPcb.showBackImg(imageBack); // })); // imageBack.Save(path + "drawback.jpg"); // //stpwth.Stop(); // //long a = stpwth.ElapsedMilliseconds; // //stpwth.Restart(); // } // } //}; //// 裁剪 //Action<Rectangle, string, string, int> actCrop = (rect, pp, fi, ii) => //{ // if (!File.Exists(pp)) // { // var partImg = new ImageFactory().Load(fi); // partImg.Crop(rect); // partImg.Save(pp); // if (ii == 0) // { // if (File.Exists(pp)) // { // partOfPcb.BeginInvoke((Action)(() => // { // partOfPcb.showImgThread(pp); // })); // partImg.Dispose(); // //break; // } // //int timeOut = 0; // //while (timeOut < 50) // //{ // // timeOut++; // // Thread.Sleep(10); // //} // } // } //}; //// 正面图画框的委托 //Action<Result, Rectangle, int> actFrontDrawImg = (result, rect, index) => //{ // lock (ghFront) // { // #region 在画框之前先裁剪下来用作局部窗体显示使用 // //MySmartThreadPool.Instance().QueueWorkItem(actCrop, rect, path + result.PartImagePath, frontImg, index); // #endregion // ghFront.DrawString(result.NgType, new Font("宋体", 10, FontStyle.Bold), Brushes.Red, rect.X, rect.Y - 15); // ghFront.DrawRectangle( // new Pen(Color.Red, 3), // rect); // this.BeginInvoke(showImg); // } //}; //// 背面图画框的委托 //Action<Result, Rectangle, int> actBackDrawImg = (result, rect, index) => //{ // lock (ghBack) // { // #region 在画框之前先裁剪下来用作局部窗体显示使用 // //MySmartThreadPool.Instance().QueueWorkItem(actCrop, rect, path + result.PartImagePath, backImg, index); // #endregion // ghBack.DrawString(result.NgType, new Font("宋体", 10, FontStyle.Bold), Brushes.Red, rect.X, rect.Y - 15); // ghBack.DrawRectangle( // new Pen(Color.Red, 3), // rect); // this.BeginInvoke(showImg); // } //}; //for (int i = 0; i < lst2.data.results.Count; i++) //{ // var result = lst2.data.results[i]; // string[] reg = result.Region.Split(','); // Rectangle rect = new Rectangle( // int.Parse(reg[0]), // int.Parse(reg[1]), // int.Parse(reg[2]), // int.Parse(reg[3])); // if (result.IsBack == 1) // { // if (imageBack == null) // { // imageBack = new Bitmap(backImg); // ghBack = Graphics.FromImage(imageBack); // } // MySmartThreadPool.Instance().QueueWorkItem(actBackDrawImg, result, rect, i); // } // else // { // if (imageFront == null) // { // //if (!stpwth.IsRunning) // //{ // // stpwth.Restart(); // //} // imageFront = new Bitmap(frontImg); // //stpwth.Stop(); // //long a = stpwth.ElapsedMilliseconds; // //a = 0; // ghFront = Graphics.FromImage(imageFront); // } // MySmartThreadPool.Instance().QueueWorkItem(actFrontDrawImg, result, rect, i); // } //} //} //catch (Exception err) //{ // string aa = err.Message; //} #endregion } catch (Exception err) { isLeisure = true; RabbitMQClientHandler.ListenChannel.BasicAck(RabbitMQClientHandler.deliveryTag, false); this.BeginInvoke((Action)(() => { this.Text = "检验端-v2.0 [数据异常-请把当前板放回重新检测]"; MessageBox.Show("数据异常-请把当前板放回重新检测", "异常报警", MessageBoxButtons.OK, MessageBoxIcon.Error); })); LogHelper.WriteLog("处理失败\n" + message, err); } } else { RabbitMQClientHandler.ListenChannel.BasicNack(RabbitMQClientHandler.deliveryTag, false, true); } // isLeisure = true; // 这个需要在pcbDetails页面最后一个执行完成后执行 // mainChannel.BasicAck(Rabbitmq.deliveryTag, false); // 这个需要在pcbDetails页面最后一个执行完成后执行 //htmlLabel1.Invoke((Action)(() => //{ // htmlLabel1.Text = $"{message} is news, deal it"; //})); //channel.BasicNack(Rabbitmq.deliveryTag, false, true); }
private void ShowResultInfo(RetAllInfoPcbs currentRetResult) { string[] reg = currentRetResult.area.Split(','); int x = Convert.ToInt32(double.Parse(reg[0])); int y = Convert.ToInt32(double.Parse(reg[1])); int w = Convert.ToInt32(double.Parse(reg[2])); int h = Convert.ToInt32(double.Parse(reg[3])); Rectangle rect = new Rectangle(x, y, w, h); DrawCrossLine(Convert.ToBoolean(currentRetResult.is_back), rect); MySmartThreadPool.Instance().QueueWorkItem((ap) => { try { if (frontImg != ap.PathConcatenate(ap.GetBasePath(), "front.jpg")) { frontImg = ap.PathConcatenate(ap.GetBasePath(), "front.jpg"); MySmartThreadPool.Instance().QueueWorkItem((f1, f2) => { bool f1IsExist, f2IsExist; f1IsExist = File.Exists(f1) ? true : false; f2IsExist = File.Exists(f2) ? true : false; this.BeginInvoke((Action <bool, bool>)((a1, a2) => { pictureBox_Front.Image = null; pictureBox_Back.Image = null; if (a1) { pictureBox_Front.Load(f1); } else { pictureBox_Front.LoadAsync("showErrImg"); } if (a2) { pictureBox_Back.Load(f2); } else { pictureBox_Back.LoadAsync("showErrImg"); } }), f1IsExist, f2IsExist); }, ap.PathConcatenate(ap.GetBasePath(), "front.jpg"), ap.PathConcatenate(ap.GetBasePath(), "back.jpg")); } string[] region = ap.region.Split(','); Rectangle rectRegion = new Rectangle(Convert.ToInt32(double.Parse(region[0])), Convert.ToInt32(double.Parse(region[1])), Convert.ToInt32(double.Parse(region[2])), Convert.ToInt32(double.Parse(region[3]))); string file = ap.PathConcatenate(ap.GetBasePath(), ap.part_image_path); if (File.Exists(file)) { Image image = Image.FromFile(file); { using (Graphics g = Graphics.FromImage(image)) { using (Pen pen = new Pen(Color.Red, 3)) { g.DrawRectangle(pen, rectRegion.X, rectRegion.Y, rectRegion.Width, rectRegion.Height); } } } this.BeginInvoke((Action <Image, int, Rectangle>)((img, isback, r2) => { imageBox_Part.TextDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.None; xtraTabControl1.SelectedTabPageIndex = isback; if (imageBox_Part.Image != null) { imageBox_Part.Image.Dispose(); } imageBox_Part.Image = img; imageBox_Part.CenterAt(new Point(r2.X, r2.Y)); imageBox_Part.Invalidate(); }), image.Clone(), ap.is_back, rectRegion); image.Dispose(); } else { this.BeginInvoke((Action)(() => { if (imageBox_Part.Image != null) { imageBox_Part.Image.Dispose(); } imageBox_Part.TextDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.Client; })); } } catch (Exception er) { } }, currentRetResult); }
private void CreatePieChart(string software_id, DataTable dt, DataTable dt2) { chartControl3.Series.Clear(); Series series = new Series("饼图2", ViewType.Pie); series.DataSource = dt; //series.ArgumentScaleType = ScaleType.Qualitative; //项目名称 series.ArgumentDataMember = "ItemName"; series.ValueScaleType = ScaleType.Numerical; //取值字段 series.ValueDataMembers.AddRange(new string[] { "ItemValue" }); //(series.Label as PieSeriesLabel).Position = PieSeriesLabelPosition.Inside; ////显示百分比和项目名称(业务员姓名) series.PointOptions.PointView = PointView.ArgumentAndValues; series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent; chartControl3.Series.Add(series); series = new Series("饼图3", ViewType.Pie); series.DataSource = dt2; //series.ArgumentScaleType = ScaleType.Qualitative; //项目名称 series.ArgumentDataMember = "ItemName"; series.ValueScaleType = ScaleType.Numerical; //取值字段 series.ValueDataMembers.AddRange(new string[] { "ItemValue" }); //(series.Label as PieSeriesLabel).Position = PieSeriesLabelPosition.Inside; ////显示百分比和项目名称(业务员姓名) series.PointOptions.PointView = PointView.ArgumentAndValues; series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent; chartControl3.Series.Add(series); //右上角分组视图 //chartControl2.Legend.MarkerSize = new System.Drawing.Size(20, 20); //chartControl2.Legend.TextOffset = 5; //chartControl2.Legend.VerticalIndent = 5; //chartControl2.Legend.Border.Color = Color.Red;//红色边框 MySmartThreadPool.Instance().QueueWorkItem(() => { if (!splashScreenManager.IsSplashFormVisible) { splashScreenManager.ShowWaitForm(); } SpcModel spcModel = DB.Instance(); try { List <RetNgTypesPai> rets = spcModel.Database.SqlQuery <RetNgTypesPai>(string.Format("SELECT ng_str, COUNT(*) as num FROM softwares_ngtype WHERE software_id = '{0}' GROUP BY ng_str", software_id)).ToList(); this.BeginInvoke((Action)(() => { chartControl_NG.Series.Clear(); Series series2 = new Series("饼图1", ViewType.Pie); series2.DataSource = rets; //series.ArgumentScaleType = ScaleType.Qualitative; //项目名称 series2.ArgumentDataMember = "ng_str"; series2.ValueScaleType = ScaleType.Numerical; //取值字段 series2.ValueDataMembers.AddRange(new string[] { "num" }); //(series2.Label as PieSeriesLabel).Position = PieSeriesLabelPosition.Inside; ////显示百分比和项目名称(业务员姓名) series2.PointOptions.PointView = PointView.ArgumentAndValues; series2.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent; chartControl_NG.Series.Add(series2); })); } catch (Exception er) { } finally { if (splashScreenManager.IsSplashFormVisible) { splashScreenManager.CloseWaitForm(); } spcModel.Dispose(); } }); }
public void Tab0Ini(QueryPars q) { TopGridView(dgvAll); queryPars.nums = int.Parse(combPageNums.Text); queryPars.pages = int.Parse(tbNowPage.Text) - 1; #region 开启线程查询数据库 AoiModel aoiModel = DB.GetAoiModel(); Action <QueryPars> t = (v) => { lock (aoiModel) { var db = aoiModel.pcbs.Where(p => p.CreateTime >= queryPars.startTime && p.CreateTime <= queryPars.endTime); if (queryPars.pcbName != null && queryPars.pcbNumber == null) { db = aoiModel.pcbs.Where(p => p.CreateTime >= queryPars.startTime && p.CreateTime <= queryPars.endTime && p.PcbName == queryPars.pcbName); } else if (queryPars.pcbName == null && queryPars.pcbNumber != null) { if (queryPars.searchPcbNumberAccurate) { db = aoiModel.pcbs.Where(p => p.CreateTime >= queryPars.startTime && p.CreateTime <= queryPars.endTime && p.PcbNumber == queryPars.pcbNumber); } else { db = aoiModel.pcbs.Where(p => p.CreateTime >= queryPars.startTime && p.CreateTime <= queryPars.endTime && p.PcbNumber.Contains(queryPars.pcbNumber)); } } else if (queryPars.pcbName != null && queryPars.pcbNumber != null) { if (queryPars.searchPcbNumberAccurate) { db = aoiModel.pcbs.Where(p => p.CreateTime >= queryPars.startTime && p.CreateTime <= queryPars.endTime && p.PcbNumber == queryPars.pcbNumber && p.PcbName == queryPars.pcbName); } else { db = aoiModel.pcbs.Where(p => p.CreateTime >= queryPars.startTime && p.CreateTime <= queryPars.endTime && p.PcbNumber.Contains(queryPars.pcbNumber) && p.PcbName == queryPars.pcbName); } } var list = db.OrderByDescending(p => p.CreateTime) .Skip(queryPars.pages * queryPars.nums) .Take(queryPars.nums) .ToList(); //#region 最上面的报表 ///**select (select count(*) from pcbs) as AllPcbNums, // * (select count(*) from pcbs where is_error = 1) as ErrorPcbNums, // * (select count(*) from pcbs where is_misjudge = 1) as MisreportPcbNums, // * (select count(*) from pcbs where is_misjudge = 1)/(select count(*) from pcbs) as MisreportRate, // * (select count(*) from pcbs where is_misjudge = 0 and is_error = 0)/(select count(*) from pcbs) as PassRate; // * **/ //string AllPcbNums = "(select count(*) from pcbs)"; //string PassPcbNums = "(select count(*) from pcbs where is_misjudge = 0 and is_error = 0)"; //string ErrorPcbNums = "(select count(*) from pcbs)"; //string MisreportPcbNums = "(select count(*) from pcbs where is_misjudge = 1)"; //string MisreportRate = MisreportPcbNums + "/" + AllPcbNums; //string PassRate = PassPcbNums + "/" + AllPcbNums; //string final = "select " + AllPcbNums + " as AllPcbNums, " //+ ErrorPcbNums + " as ErrorPcbNums, " //+ MisreportPcbNums + " as MisreportPcbNums, " //+ MisreportRate + " as MisreportRate, " //+ PassRate + "as PassRate"; //var tables = aoiModel.Database.SqlQuery<SqlQueryData1>(final).ToList(); //.SqlQuery("select *from BlogMaster where UserId='3'"); //this.BeginInvoke((Action)(() => //{ // bindingSourceAll.DataSource = tables; // dgvAll.DataSource = bindingSourceAll; //})); //#endregion #region 更新底部页数据 int totalRows = totalRows = db.Count();//aoiModel.Database.SqlQuery<int>("select count(*) from pcbs").ToArray()[0]; int totalPage = 1; if (totalRows > queryPars.nums) { totalPage = (totalRows + v.nums - 1) / v.nums; } this.BeginInvoke((Action)(() => { lbTotalPages.Text = totalPage + ""; lbTotalRows.Text = totalRows + ""; })); #endregion aoiModel.Dispose(); this.BeginInvoke((Action)(() => { bindingSourcePcbs.DataSource = list; dgvOriginalData.DataSource = bindingSourcePcbs; })); } }; MySmartThreadPool.Instance().QueueWorkItem <QueryPars>(t, queryPars); #endregion }
private void ShowResultInfo(RetResults currentRetResult) { string[] reg = currentRetResult.area.Split(','); int x = Convert.ToInt32(double.Parse(reg[0])); int y = Convert.ToInt32(double.Parse(reg[1])); int w = Convert.ToInt32(double.Parse(reg[2])); int h = Convert.ToInt32(double.Parse(reg[3])); Rectangle rect = new Rectangle(x, y, w, h); DrawCrossLine(Convert.ToBoolean(currentRetResult.is_back), rect); MySmartThreadPool.Instance().QueueWorkItem((ap) => { try { string[] region = currentRetResult.region.Split(','); Rectangle rectRegion = new Rectangle(Convert.ToInt32(double.Parse(region[0])), Convert.ToInt32(double.Parse(region[1])), Convert.ToInt32(double.Parse(region[2])), Convert.ToInt32(double.Parse(region[3]))); string file = ap.PathConcatenate(ap.GetBasePath(), ap.part_image_path); if (File.Exists(file)) { Image image = Image.FromFile(file); { using (Graphics g = Graphics.FromImage(image)) { using (Pen pen = new Pen(Color.Red, 3)) { g.DrawRectangle(pen, rectRegion.X, rectRegion.Y, rectRegion.Width, rectRegion.Height); } } } this.BeginInvoke((Action <Image, int, Rectangle>)((img, isback, r2) => { imageBox_Part.TextDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.None; xtraTabControl1.SelectedTabPageIndex = isback; if (imageBox_Part.Image != null) { imageBox_Part.Image.Dispose(); } imageBox_Part.Image = img; imageBox_Part.CenterAt(new Point(r2.X, r2.Y)); imageBox_Part.Invalidate(); }), image.Clone(), ap.is_back, rectRegion); image.Dispose(); } else { this.BeginInvoke((Action)(() => { LogHelper.WriteLog(file); if (imageBox_Part.Image != null) { imageBox_Part.Image.Dispose(); } imageBox_Part.TextDisplayMode = Cyotek.Windows.Forms.ImageBoxGridDisplayMode.Client; })); } } catch (Exception er) { } }, currentRetResult); }
private void GridView_Pcbs_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { AoiPcbs currentPcb = gridView_Pcbs.GetFocusedRow() as AoiPcbs; MySmartThreadPool.Instance().QueueWorkItem((ap) => { SplashScreenManager sp = new SplashScreenManager(this, typeof(global::spc_client.MyWaitForm), true, true); sp.ShowWaitForm(); SpcModel spcModel = DB.Instance(); try { MySmartThreadPool.Instance().QueueWorkItem((f1, f2) => { bool f1IsExist, f2IsExist; f1IsExist = File.Exists(f1) ? true : false; f2IsExist = File.Exists(f2) ? true : false; this.BeginInvoke((Action <bool, bool>)((a1, a2) => { pictureBox_Front.Image = null; pictureBox_Back.Image = null; if (a1) { pictureBox_Front.Load(f1); } else { pictureBox_Front.LoadAsync("showErrImg"); } if (a2) { pictureBox_Back.Load(f2); } else { pictureBox_Back.LoadAsync("showErrImg"); } }), f1IsExist, f2IsExist); }, ap.PathConcatenate(ap.GetBasePath(), "front.jpg"), ap.PathConcatenate(ap.GetBasePath(), "back.jpg")); //this.BeginInvoke((Action)(() => //{ //})); List <RetResults> retResults = spcModel.Database.SqlQuery <RetResults>(String.Format("SELECT is_back,score,area,region,ng_str,result_ng_type_id, ng_type_id, result_ng_type_id != '' as NG,pc_ip,pcb_path,part_image_path, pcb_id FROM (SELECT * FROM aoi_results WHERE aoi_results.pcb_id = '{0}') as ss LEFT JOIN aoi_pcbs ON ss.pcb_id = aoi_pcbs.id LEFT JOIN aoi_softwares ON aoi_pcbs.software_id = aoi_softwares.id LEFT JOIN aoi_ng_types ON aoi_ng_types.id = ss.result_ng_type_id LEFT JOIN aoi_pcs ON aoi_pcs.id = aoi_softwares.pc_id", ap.id)).ToList(); foreach (RetResults r in retResults) { r.NG = r.NG == "1" ? "NG" : "OK"; } this.BeginInvoke((Action)(() => { gridControl_Results.DataSource = retResults; //gridView_Pcbs.FocusedRowHandle = 0; //gridView_Results.FocusedRowHandle = 0; //gridControl_Results.Focus(); })); if (retResults.Count > 0) { MySmartThreadPool.Instance().QueueWorkItem((a) => { this.BeginInvoke((Action)(() => { ShowResultInfo(retResults[0]); })); }, retResults[0]); } } catch (Exception er) { //LogHelper.WriteLog(er.Message); } finally { sp.CloseWaitForm(); spcModel.Dispose(); } }, currentPcb); }
/// <summary> /// 执行打X板子 /// </summary> /// <param name="frontImg"></param> /// <param name="backImg"></param> /// <param name="pcb"></param> public void xxxx(Pcb pcb) { checkedNum = 0; needCheckNumAll = 0; xboardDoneNum = 0; nowWorkingPcb = pcb; frontBoard = null; backBoard = null; string frontImgPath = ConfigurationManager.AppSettings["FtpPath"] + pcb.Id + "/front.jpg"; string backImgPath = ConfigurationManager.AppSettings["FtpPath"] + pcb.Id + "/back.jpg"; if (File.Exists(frontImgPath)) { frontBoard = new XBoard(frontImgPath, false); } if (File.Exists(backImgPath)) { backBoard = new XBoard(backImgPath, false); backBoard.isBack = true; } for (int i = 0; i <= 7; i++) { if (frontBoard != null) { MySmartThreadPool.Instance().QueueWorkItem((act, n) => { lock (frontBoard) { try { DPoint point = new DPoint(); double dres = Aoi.marker_match_crop(frontBoard.matImg.Ptr, marker.Ptr, ref point, ref act); this.BeginInvoke((Action <int, double, XBoard>)((bn, bdress, board) => { xBoardAddTree(bn, bdress, board); }), n, dres, frontBoard); //if (dres > threshold) //{ // //CvInvoke.PutText(frontMatImg, dres + "", new DPoint(point.X + act.X, point.Y + act.Y), FontFace.HersheyComplex, 3, new MCvScalar(0, 0, 255)); //} //CvInvoke.PutText(frontMatImg, dres + "", new DPoint(point.X + act.X, point.Y + act.Y), FontFace.HersheyComplex, 3, new MCvScalar(0, 0, 255)); //CvInvoke.Rectangle(frontMatImg, new DRectangle(new DPoint(point.X + act.X, point.Y + act.Y), new Size(75, 75)), new MCvScalar(0, 0, 255), 20); //frontMatImg.Save(@"C:\res\f" + point.X + ".jpg"); //Console.WriteLine(dres); //Console.WriteLine("正面:" + dres); } catch (Exception er) { LogHelper.WriteLog("front marker error", er); } } }, frontMarkerCheckArea[i], i); } if (backBoard != null) { MySmartThreadPool.Instance().QueueWorkItem((act, n) => { lock (backBoard) { try { DPoint point = new DPoint(); double dres = Aoi.marker_match_crop(backBoard.matImg.Ptr, marker.Ptr, ref point, ref act); this.BeginInvoke((Action <int, double, XBoard>)((bn, bdress, board) => { xBoardAddTree(bn, bdress, board); }), n, dres, backBoard); //if (dres > threshold) //{ //} //CvInvoke.PutText(backMatImg, dres + "", new DPoint(point.X + act.X, point.Y + act.Y), FontFace.HersheyComplex, 3, new MCvScalar(0, 0, 255)); //CvInvoke.Rectangle(backMatImg, new DRectangle(new DPoint(point.X + act.X, point.Y + act.Y), new Size(75, 75)), new MCvScalar(255, 0, 0), 3); //backMatImg.Save(@"C:\res\b" + point.X + ".jpg"); //Console.WriteLine(dres); //Console.WriteLine("反面:" + dres); } catch (Exception er) { LogHelper.WriteLog("back marker error", er); } } }, backMarkerCheckArea[i], i); } //DPoint point = new DPoint(); //double dres = Aoi.marker_match(img.Ptr, marker.Ptr, ref point); //CvInvoke.Rectangle(img, new DRectangle(point, new Size(200, 200)), new MCvScalar(0, 0, 255), 20); //img.Save(@"E:\索米测试图片\result\" + i + ".jpg"); //Console.WriteLine(res); } }