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

FrmMain.cs 196 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636
  1. using Advantech.Motion;
  2. using HalconDotNet;
  3. using Microsoft.VisualBasic;
  4. using Models;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Linq;
  7. using OpenCvSharp;
  8. using ProductionControl.Device;
  9. using ProductionControl.UI;
  10. using ProductionControl.Utils;
  11. using SqlSugar;
  12. using System;
  13. using System.Collections;
  14. using System.Collections.Generic;
  15. using System.ComponentModel;
  16. using System.Data;
  17. using System.Diagnostics;
  18. using System.Drawing;
  19. using System.Drawing.Imaging;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Security.Cryptography;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using System.Windows.Forms;
  27. using static ProductionControl.Device.AxisDev;
  28. using static ProductionControl.Device.DefectLib;
  29. using static ProductionControl.Device.SizeLib;
  30. namespace ProductionControl
  31. {
  32. public partial class FrmMain : Form
  33. {
  34. WebService webService = new WebService();
  35. private List<string> productCodeList = new List<string>();
  36. private DevContainer devContainer = new DevContainer();
  37. private Service.ProductService svcProduct = new Service.ProductService();
  38. private Service.OrderService svcOrder = new Service.OrderService();
  39. private bool bExitApp = false;
  40. //禁用蜂鸣器,门磁
  41. private bool disableBuzzer, disableDoorSensor;
  42. //线宽,张力,厚度,PT
  43. private List<double> lstTension = new List<double>();
  44. private List<double> lstHeight = new List<double>();
  45. private List<double> lstLineWidth = new List<double>();
  46. private List<double> lstPT = new List<double>();
  47. private Queue<scannerGBmpLoc> scannerGBmpQueue = new Queue<scannerGBmpLoc>();
  48. private Queue<scannerCBmpLoc> scannerCBmpQueue = new Queue<scannerCBmpLoc>();
  49. //private int scannerCBmpIndex = 0;//scannerCBmpQueue中使用当前项的计数器
  50. private int compBmpIndex = 0;//比对777图的索引
  51. private int defectBmpNum = 0;
  52. private int defectBmpNumResult = 0;
  53. /// <summary>
  54. /// 比对失败的图片
  55. /// </summary>
  56. private List<Bitmap> lstCompareFailZoomImage = new List<Bitmap>();
  57. private object myLock=new object();
  58. private WarningEnum warningLevel;//警告等级
  59. private CurrentPTEnum currentPT;//当前点位
  60. private CurrentStateEnum currentState;//当前状态
  61. /// <summary>
  62. /// 当前流程ID,暂停/继续时使用
  63. /// </summary>
  64. private int currProcessIndex = -1;
  65. private Models.Product currProductModel = null;//当前产品
  66. private bool autoMakeTagRuning = false;
  67. private bool isProductRevise = false;
  68. //产品-厚度base校正点位索引
  69. private int ProductPT_HeightBaseNum = 0;
  70. private Stopwatch stopWatch = new Stopwatch();
  71. private Order order = new Order();
  72. //--333输出变量供后面多个777使用
  73. public HObject contoursAffineTrans1_Out;
  74. private System.Timers.Timer timer = new System.Timers.Timer();
  75. private class scannerGBmpLoc
  76. {
  77. public scannerGBmpLoc(Mat mat, double xmm, double ymm)
  78. {
  79. bmp = mat;
  80. Xmm = xmm;
  81. Ymm = ymm;
  82. }
  83. public Mat bmp { get; private set; }
  84. public double Xmm { get; private set; }
  85. public double Ymm { get; private set; }
  86. }
  87. private class scannerCBmpLoc
  88. {
  89. public scannerCBmpLoc(string path, double posX, double posY)
  90. {
  91. Path = path;
  92. PosX=posX;
  93. PosY=posY;
  94. }
  95. public scannerCBmpLoc(Bitmap bmp, double posX, double posY)
  96. {
  97. BMP = bmp;
  98. PosX = posX;
  99. PosY = posY;
  100. }
  101. public Bitmap BMP { get; private set; }
  102. public string Path { get; private set; }
  103. public double PosX { get; private set; }
  104. public double PosY { get; private set; }
  105. }
  106. public FrmMain()
  107. {
  108. InitializeComponent();
  109. this.dgvProcess.AutoGenerateColumns = false;
  110. this.tsbtnCloseDev.Visible = false;
  111. this.tsslLoginInfo.Text = $"操作员:{Config.loginUser.Code}({Config.loginUser.Name})";
  112. this.tsslLoginTime.Text = $" 登录时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}";
  113. //显示行号与列宽度自动调整
  114. dgvProcess.RowHeadersVisible = true;
  115. dgvProcess.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
  116. dgvProcess.RowPostPaint += (sender, e) =>
  117. {
  118. Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dgvProcess, sender, e);
  119. };
  120. checkCustomerVer();
  121. }
  122. private void checkCustomerVer()
  123. {
  124. //if(Config.CustomerVer=="A")
  125. // this.tsMenuOrderProduct.Visible = false;
  126. }
  127. private void FrmMian_Load(object sender, EventArgs e)
  128. {
  129. if (Config.loginUser.RoleInfo.Code!="admin")
  130. checkRoleRight();
  131. loadProductCodeList();
  132. this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
  133. this.tsslLoginTime.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
  134. this.tsslLoginInfo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
  135. this.tsAxisState.Text = "";
  136. //
  137. webService.LogEvent = (warning, msg) =>
  138. {
  139. AddTextEvent("HTTP服务", msg, warning);
  140. webService.LogEvent = null;
  141. };
  142. webService.start();
  143. }
  144. private void loadProductCodeList()
  145. {
  146. try
  147. {
  148. productCodeList = svcProduct.GetList().Select(m => m.Code).OrderBy(m=>m).ToList();
  149. }
  150. catch(Exception ex)
  151. {
  152. AddTextEvent("启动", "加载产品料号失败:" + ex.Message,WarningEnum.High);
  153. }
  154. }
  155. private void checkRoleRight()
  156. {
  157. this.流程管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Step") != null);
  158. this.产品管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Product") != null);
  159. this.设备调试ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Debug") != null);
  160. //this.tsMenuOrderQuery.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Order") != null);
  161. //this.tsMenuStatistics.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Statistics") != null);
  162. this.角色管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Role") != null);
  163. this.用户管理ToolStripMenuItem.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "User") != null);
  164. this.tsbtnProductRevise.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "HeightBase") != null);
  165. this.tsMenuSysSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "SysSetting") != null);
  166. this.tsMenuCmdSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "CmdSetting") != null);
  167. this.tsMenuPTSetting.Enabled = (Config.loginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "PTSetting") != null);
  168. }
  169. private void txtProductName_KeyPress(object sender, KeyPressEventArgs e)
  170. {
  171. //if (e.KeyChar == '\r' && devContainer.state && currentState == CurrentStateEnum.ScanBarcode)// && currentPT== CurrentPTEnum.UpPT )
  172. //{
  173. // runStep();
  174. //}
  175. }
  176. //后台线程运行
  177. /// <summary>
  178. /// 中断工序运行
  179. /// </summary>
  180. /// <returns></returns>
  181. private bool isBreakProcessRun()
  182. {
  183. return warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.运行中;
  184. }
  185. private void runStep()
  186. {
  187. compBmpIndex = defectBmpNum = defectBmpNumResult = 0;
  188. AddTextEvent("启动", "等待扫码枪扫码...");
  189. if (devContainer.devCodeScanner != null)
  190. {
  191. devContainer.devCodeScanner.stop();
  192. devContainer.devCodeScanner = null;
  193. }
  194. devContainer.devCodeScanner = new CodeScannerDev();
  195. if (!devContainer.devCodeScanner.start())
  196. {
  197. AddTextEvent("扫码枪", "扫码枪初始化失败!");
  198. return;
  199. }
  200. //2023-12-06 无输入料号防呆
  201. if(string.IsNullOrEmpty(this.txtProductCode.Text))
  202. {
  203. AddTextEvent("料号", "未选择料号!");
  204. return;
  205. }
  206. //2023-10-20 不使用扫码枪事件处理
  207. //devContainer.devCodeScanner.ScanerEvent = (code) =>
  208. string code = this.txtProductCode.Text;
  209. {
  210. if (!devContainer.state || currentState != CurrentStateEnum.等待扫码 || string.IsNullOrWhiteSpace(code))
  211. return;
  212. //
  213. scannerGBmpQueue.Clear();
  214. scannerCBmpQueue.Clear();
  215. lstCompareFailZoomImage.Clear();
  216. contoursAffineTrans1_Out = null;
  217. Thread threadtest = new System.Threading.Thread(() =>
  218. {
  219. int errStep = 0;
  220. try
  221. {
  222. var model = svcProduct.GetModelNav(code);
  223. if (model != null && model.StepInfo.ProcessList.Count > 0)
  224. {
  225. errStep = 1;
  226. //根据产品设置动态加载外观检测模型文件
  227. string onnxFile;
  228. if (!string.IsNullOrWhiteSpace(model.DefectModelFile))
  229. onnxFile = $"{Application.StartupPath}\\onnxFiles\\{model.DefectModelFile}";
  230. else
  231. onnxFile = $"{Application.StartupPath}\\onnxFiles\\default.onnx";
  232. devContainer.libDefect.loadModelFile(onnxFile);
  233. //
  234. errStep = 2;
  235. string sn = "";
  236. AutoResetEvent waitEvent = new AutoResetEvent(false);
  237. this.Invoke(new System.Action(() =>
  238. {
  239. FrmInput frm = new FrmInput(null, "请输入网版编码:");
  240. if (frm.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(frm.inputData))
  241. sn = frm.inputData;
  242. waitEvent.Set();
  243. }));
  244. errStep = 3;
  245. waitEvent.WaitOne();
  246. if (string.IsNullOrWhiteSpace(sn))
  247. {
  248. AddTextEvent("扫码枪", $"料号{code}未输入网版编码,流程中止!");
  249. return;
  250. }
  251. AddTextEvent("扫码枪", $"料号:{code},网版编码:{sn}");
  252. //是否闪退需观察
  253. errStep = 4;
  254. devContainer.devCodeScanner.stop();
  255. devContainer.devCodeScanner = null;
  256. errStep = 5;
  257. //判断SN数量是否达到批次上限
  258. //创建表达式
  259. if (!string.IsNullOrWhiteSpace(model.BatchId) && model.TargetCount > 0)
  260. {
  261. var exp1 = Expressionable.Create<Order>()
  262. .And(m => m.ProductId == model.Id)
  263. .And(m => m.BatchId == model.BatchId)
  264. .And(m => m.SN != sn)
  265. .ToExpression();//注意 这一句 不能少
  266. errStep = 6;
  267. if (svcOrder.Count(exp1) >= model.TargetCount)
  268. {
  269. AddTextEvent("扫码枪", $"当前产品本批次检测数已达目标数量,请更换检测批次号!");
  270. return;
  271. }
  272. errStep = 7;
  273. }
  274. //
  275. this.Invoke(new System.Action(() =>
  276. {
  277. this.txtProductSN.Text = sn;
  278. }));
  279. //
  280. model.HeightBaseDec = "";
  281. currentState = CurrentStateEnum.运行中;
  282. currentPT = CurrentPTEnum.Moving;
  283. currProductModel = model;
  284. AddTextEvent("扫码枪", $"{model.Name} {model.Spec} [{model.Code}]");
  285. this.Invoke(new System.Action(() =>
  286. {
  287. this.txtProductCode.Text = model.Code;
  288. this.txtProductName.Text = model.Name;
  289. this.dgvProcess.DataSource = new BindingSource(model.StepInfo.ProcessList, null);
  290. devContainer.libFor.clear();
  291. devContainer.libIF.clear();
  292. tsbtnSizeTag.Enabled = tsbtnSizeImage.Enabled = tsbtnDefectImage.Enabled = true;
  293. }));
  294. errStep = 8;
  295. //
  296. ProductPT_HeightBaseNum = 0;
  297. this.setButtonEnabled(this.tsbtnPause, true);
  298. this.setButtonEnabled(this.tsbtnStopNow, true);
  299. order = new Order();
  300. order.Qualified = true;//默认合格,中间有一项指标不合格则改为false
  301. order.ProductId = currProductModel.Id;
  302. order.StepId = (int)currProductModel.StepId;
  303. order.SN = sn;
  304. order.BatchId = currProductModel.BatchId;
  305. errStep = 9;
  306. int nextStepId = 0;
  307. do
  308. {
  309. nextStepId = nextProcess(model, nextStepId);
  310. } while (nextStepId >= 0 && !isBreakProcessRun());
  311. errStep = 10;
  312. }
  313. else
  314. AddTextEvent("扫码枪", model != null ? $"料号{code}不存在!" : $"产品({model.Name})未配置检测流程!");
  315. }
  316. catch (Exception ex)
  317. {
  318. //AddTextEvent("扫码后", $"errcode({errStep}):" + ex.Message);//会有空对象引用,但不知哪里报的
  319. //warning(WarningEnum.High);
  320. }
  321. });
  322. threadtest.IsBackground = true;
  323. threadtest.Start();
  324. };
  325. }
  326. //model.Type=1 系统校正
  327. /// <summary>
  328. ///
  329. /// </summary>
  330. /// <param name="model"></param>
  331. /// <param name="stepIndex">0-n</param>
  332. /// <returns>大于等于0正常工序; -1:结束 -2:异常</returns>
  333. private int nextProcess(Models.Product model, int stepIndex)
  334. {
  335. try
  336. {
  337. //记录当前index
  338. this.currProcessIndex = stepIndex;
  339. this.Invoke(new System.Action(() =>
  340. {
  341. try
  342. {
  343. this.dgvProcess.Rows[stepIndex].Selected = true;
  344. dgvProcess.CurrentCell = dgvProcess.Rows[stepIndex].Cells[1];
  345. }
  346. catch { }
  347. }));
  348. lock (myLock)
  349. {
  350. if (isBreakProcessRun())
  351. return stepIndex;
  352. }
  353. //开始计时
  354. if(!isProductRevise && model.StepInfo.StartTimeIndex>0 && model.StepInfo.StartTimeIndex==stepIndex+1)
  355. stopWatch.Restart();
  356. var processList = isProductRevise ? model.ReviseStepInfo.ProcessList : model.StepInfo.ProcessList;
  357. var processInfo = processList[stepIndex];
  358. string processName = processInfo.ProcessName;
  359. //AddTextEvent($"{stepIndex + 1}-{processName}", $"工序开始...");
  360. string jsonParams = null;//配方
  361. if (model.ProductProcessList != null && model.ProductProcessList.Count > 0)//使用产品配方
  362. {
  363. ProductProcess productProcessParams = model.ProductProcessList.First(m => m.ProcessCode == processInfo.ProcessCode);
  364. if (productProcessParams != null)
  365. {
  366. jsonParams = productProcessParams.ProcessParams;
  367. AddTextEvent($"{stepIndex + 1}-{processName}", $"使用产品专用配方:{jsonParams}");
  368. }
  369. }
  370. if (jsonParams == null)//使用流程默认配方
  371. {
  372. jsonParams = processInfo.ProcessParams;
  373. if (jsonParams == null) throw new Exception("配方为null!!");
  374. AddTextEvent($"{stepIndex + 1}-{processName}", $"使用流程默认配方:{jsonParams}");
  375. }
  376. //
  377. JObject processParam = JObject.Parse(jsonParams);
  378. if (!processParam.ContainsKey("Disable") || !processParam.Value<bool>("Disable"))
  379. {
  380. AutoResetEvent endEvent;
  381. uint sleepPre = processParam.Value<uint>("SleepPre");
  382. uint sleepLater = processParam.Value<uint>("SleepLater");
  383. if (sleepPre > 0)
  384. Thread.Sleep((int)sleepPre);
  385. double limitThresholdVal, lowerThresholdVal; //张力,厚度,Size,Defect
  386. //======Switch 工序类型
  387. bool asynRun;
  388. string gbxBmpPath = "";
  389. Models.Attachment attachmentFile;
  390. int liStatocStepIndex = stepIndex;
  391. switch (processInfo.ProcessCode)
  392. {
  393. case "IOCard":
  394. #region
  395. var direction = (IODirectionEnum)processParam.Value<int>("Direction");
  396. if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出)
  397. {
  398. uint IN_Waiting_Timeout = processParam.Value<uint>("IN_Waiting_Timeout");
  399. AddTextEvent($"{stepIndex + 1}-{processName}", $"等待I/O输入信号{(IN_Waiting_Timeout > 0 ? $"(超时时长: {IN_Waiting_Timeout})" : "...")}");
  400. string[] inValue = processParam.Value<JArray>("IN_OP_SHOW").ToObject<List<string>>().ToArray();
  401. uint inWaitingTime = 0;
  402. while (true)
  403. {
  404. if (isBreakProcessRun())
  405. return stepIndex;
  406. if (Util.compareIOInput(inValue, devContainer.devIOCard.DIData))
  407. break;
  408. Thread.Sleep(10);
  409. inWaitingTime += 10;
  410. if (IN_Waiting_Timeout>0 && inWaitingTime >= IN_Waiting_Timeout)
  411. {
  412. AddTextEvent($"{stepIndex + 1}-{processName}", $"输入等待超时告警!", WarningEnum.High);
  413. warning(WarningEnum.Low);//暂停
  414. return stepIndex;
  415. }
  416. }
  417. AddTextEvent($"{stepIndex + 1}-{processName}", $"I/O输入信号对比完成!");
  418. }
  419. if (direction == IODirectionEnum.输出 || direction == IODirectionEnum.输入输出)
  420. devContainer.io_output($"{stepIndex + 1}-{processName}", processParam);
  421. #endregion
  422. break;
  423. case "Tension":
  424. #region
  425. //limitThresholdVal = processParam.Value<double>("LimitThresholdVal");
  426. //lowerThresholdVal = processParam.Value<double>("LowerThresholdVal");
  427. //double tensionValue = 0;
  428. //int timeoutTension = 0;
  429. //do
  430. //{
  431. // tensionValue = devContainer.devTension.getValue();
  432. // setDgvContentCol(liStatocStepIndex, $"张力值:{tensionValue}");
  433. // Thread.Sleep(10);
  434. // timeoutTension += 10;
  435. // if (tensionValue <= 0 && timeoutTension >= 600)//3秒超时
  436. // {
  437. // AddTextEvent($"{stepIndex + 1}-{processName}", $"张力测量失败,确认设备是否正常!", WarningEnum.High);
  438. // warning(WarningEnum.Low);//暂停
  439. // devContainer.io_output(CMDName.张力读取结束输出);
  440. // currProcessIndex--;
  441. // return stepIndex;
  442. // }
  443. //} while (tensionValue <= 0);
  444. //devContainer.io_output(CMDName.张力读取结束输出);
  445. //lstTension.Add(tensionValue);
  446. //updateTensionValue(model.TensionBaseValue+model.TensionUpFloatValue,model.TensionBaseValue-model.TensionDownFloatValue);
  447. //if (limitThresholdVal > 0 && tensionValue >= limitThresholdVal)
  448. //{
  449. // AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue},达到上限阀值:{limitThresholdVal},进行下料...", WarningEnum.Low);
  450. // currProcessIndex = stepIndex + 1;
  451. // warning(WarningEnum.Low);//暂停
  452. // return stepIndex;
  453. //}
  454. //else if (lowerThresholdVal > 0 && tensionValue < lowerThresholdVal)
  455. //{
  456. // AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue},达到下限阀值:{lowerThresholdVal},进行下料...", WarningEnum.Low);
  457. // currProcessIndex = stepIndex + 1;
  458. // warning(WarningEnum.Low);//暂停
  459. // return stepIndex;
  460. //}
  461. //AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{tensionValue}");
  462. #endregion
  463. break;
  464. case "Height":
  465. #region
  466. if (Config.SkipHeight)
  467. {
  468. AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!");
  469. setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!");
  470. break;
  471. }
  472. while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待
  473. {
  474. Thread.Sleep(100);
  475. if (isBreakProcessRun())
  476. {
  477. //currProcessIndex = stepIndex;//本工序没执行,step不变
  478. return stepIndex;
  479. }
  480. }
  481. limitThresholdVal = processParam.Value<double>("LimitThresholdVal");
  482. lowerThresholdVal = processParam.Value<double>("LowerThresholdVal");
  483. bool IsRevise = processParam.Value<bool>("IsRevise");
  484. double relBaseValue = processParam.Value<double>("RelBaseValue"); //配方中相对偏移值
  485. var heightValue = devContainer.devHeight.getHeight();
  486. heightValue = Math.Round(heightValue, 2);//保留2位小数
  487. File.AppendAllText(Application.StartupPath + "\\厚度测量记录.txt", heightValue+"\r\n");//TEMP
  488. if (!IsRevise && heightValue < 0)
  489. {
  490. AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue},异常数据,终止任务!", WarningEnum.Low);
  491. warning(WarningEnum.Low);//暂停
  492. return stepIndex;
  493. }
  494. //厚度Base校正
  495. if (isProductRevise)
  496. {
  497. setDgvContentCol(liStatocStepIndex, $"厚度值:{heightValue}");
  498. model.HeightBaseDec += heightValue + ";";
  499. AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue}");
  500. }
  501. else if (IsRevise)
  502. {
  503. var reviseHeight = heightValue + relBaseValue;
  504. model.HeightBaseDec += reviseHeight + ";";
  505. setDgvContentCol(liStatocStepIndex, $"base值:{reviseHeight} = 厚度值:{heightValue}+偏移值:{relBaseValue}");
  506. AddTextEvent($"{stepIndex + 1}-{processName}", $"base值:{reviseHeight} = 厚度值:{heightValue}+偏移值:{relBaseValue},校正索引队列:{model.HeightBaseDec}");
  507. }
  508. else
  509. {
  510. AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue},base值:{model.HeightBaseDec},偏移值:{relBaseValue},当前base索引:{ProductPT_HeightBaseNum}");
  511. double heightDev = 0;
  512. var heightDev_BaseList=model.HeightBaseDec.Split(new char[] {';',','});
  513. if (heightDev_BaseList.Count() > ProductPT_HeightBaseNum && heightDev_BaseList[ProductPT_HeightBaseNum].Trim() != "")
  514. heightDev = Convert.ToDouble(heightDev_BaseList[ProductPT_HeightBaseNum].Trim());
  515. ProductPT_HeightBaseNum++;
  516. double heightValue2 =Math.Abs(heightDev - heightValue ) + relBaseValue;
  517. heightValue2 = Math.Round(heightValue2, 2);
  518. setDgvContentCol(liStatocStepIndex, $"厚度值:{heightValue2}");
  519. lstHeight.Add(heightValue2);
  520. updateHeightValue(model.HeightBaseValue + model.HeightUpFloatValue, model.HeightBaseValue - model.HeightDownFloatValue);
  521. if (limitThresholdVal > 0 && heightValue2 >= limitThresholdVal)
  522. {
  523. AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue2},达到上限阀值:{limitThresholdVal},进行下料...", WarningEnum.Low);
  524. currProcessIndex = stepIndex + 1;
  525. warning(WarningEnum.Low);//终止
  526. return stepIndex;
  527. }
  528. else if (lowerThresholdVal > 0 && heightValue2 < lowerThresholdVal)
  529. {
  530. AddTextEvent($"{stepIndex + 1}-{processName}", $"读取数据:{heightValue2},达到下限阀值:{lowerThresholdVal},进行下料...", WarningEnum.Low);
  531. currProcessIndex = stepIndex + 1;
  532. warning(WarningEnum.Low);//终止
  533. return stepIndex;
  534. }
  535. AddTextEvent($"{stepIndex + 1}-{processName}", $"厚度值:{heightValue2} (Base值:{heightDev} - 读取数据:{heightValue} + 偏移值:{relBaseValue})");
  536. }
  537. #endregion
  538. break;
  539. case "Axis":
  540. #region 多轴后遗留问题:暂停后再启动不知哪几个轴已执行
  541. JObject processParamTmp = new JObject();
  542. //兼容旧版单轴
  543. if (!processParam.ContainsKey("0") && !processParam.ContainsKey("1") && !processParam.ContainsKey("2") && !processParam.ContainsKey("3"))
  544. {
  545. processParam.Add("Enable", true);
  546. processParamTmp.Add(processParam.Value<int>("AxisIndex").ToString(), processParam);
  547. processParam = processParamTmp;
  548. }
  549. //-
  550. foreach (var processParamSub in processParam.Properties())
  551. {
  552. processParam = processParamSub.Value as JObject;
  553. AddTextEvent($"{stepIndex + 1}-{processName}", processParam.ToString());
  554. if (!processParam.ContainsKey("Disable") || !processParam.Value<bool>("Disable"))
  555. {
  556. //asynRun = processParam.Value<bool>("AsynRun");//异步
  557. int AxisIndex = processParam.Value<int>("AxisIndex");
  558. int DeviceType = processParam.Value<int>("DeviceType");
  559. double VelLow = processParam.Value<double>("VelLow");
  560. double VelHigh = processParam.Value<double>("VelHigh");
  561. double Acc = processParam.Value<double>("Acc");
  562. double Dec = processParam.Value<double>("Dec");
  563. AxMoveMode MoveMode = (AxMoveMode)processParam.Value<int>("MoveMode");//绝对位置
  564. double PPUValue = processParam.Value<double>("Value");
  565. AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}准备({(MoveMode == AxMoveMode.绝对位置 ? "绝对" : "相对")})运动至{PPUValue}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[AxisIndex]).ToString()})...");
  566. //移动Axis前等待厚度传感器收回
  567. if (!Config.SkipHeight)
  568. {
  569. while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue))
  570. {
  571. if (isBreakProcessRun())
  572. return stepIndex;
  573. Thread.Sleep(10);
  574. }
  575. }
  576. while (!devContainer.devAxis.isReady(AxisIndex))
  577. {
  578. Thread.Sleep(100);
  579. if (isBreakProcessRun())
  580. return stepIndex;
  581. }
  582. devContainer.devAxis.setAxisVelParam(VelLow, VelHigh, Acc, Dec, AxisIndex);
  583. if (!devContainer.devAxis.move_ptp(AxisIndex, PPUValue, MoveMode))
  584. {
  585. AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}运动失败!", WarningEnum.Low);
  586. warning(WarningEnum.Low);//终止
  587. return stepIndex;
  588. }
  589. //多轴运行自动使用异步,全部执行后强制等待各轴完成 asynRun属性已无用
  590. //AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴{AxisIndex}运行完成...");
  591. //while (!asynRun && !devContainer.devAxis.isReady(AxisIndex))
  592. //{
  593. // Thread.Sleep(100);
  594. // if (isBreakProcessRun())
  595. // {
  596. // currProcessIndex = stepIndex + 1;
  597. // return stepIndex;
  598. // }
  599. //}
  600. //if (devContainer.devAxis.isReady(AxisIndex))
  601. // AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndex}运行完成,当前命令位置:{devContainer.devAxis.getCmdPos_mm(AxisIndex)},反馈位置:{devContainer.devAxis.getActualPos_mm(AxisIndex)}");
  602. }
  603. }
  604. //多轴同时运行后强制等待各轴完成
  605. AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴组运行完成...");
  606. while (!devContainer.devAxis.isReady())
  607. {
  608. Thread.Sleep(100);
  609. if (isBreakProcessRun())
  610. {
  611. currProcessIndex = stepIndex + 1;
  612. return stepIndex;
  613. }
  614. }
  615. AddTextEvent($"{stepIndex + 1}-{processName}", $"轴组运行完成。");
  616. #endregion
  617. break;
  618. case "AxisTag":
  619. #region
  620. //asynRun = processParam.Value<bool>("AsynRun");//异步
  621. string axisSizeTag= processParam.Value<string>("SizeTag");
  622. int useIndex = processParam.Value<int>("UseIndex");//消费posePT中的索引
  623. AxMoveMode TagMoveMode = (AxMoveMode)processParam.Value<int>("MoveMode");//绝对位置
  624. var AxisIndexList = processParam.Value<JArray>("AxisIndexList").ToObject<List<int>>();
  625. double TagVelLow = processParam.Value<double>("VelLow");
  626. double TagVelHigh = processParam.Value<double>("VelHigh");
  627. double TagAcc = processParam.Value<double>("Acc");
  628. double TagDec = processParam.Value<double>("Dec");
  629. var sizeTagObj = order.SizeTagDataList.LastOrDefault(m => m.SizeTag == axisSizeTag);//用最新的last
  630. if (sizeTagObj == null)
  631. {
  632. AddTextEvent($"{stepIndex + 1}-{processName}", $"偏移校正轴工序找不到数据提供者Tag:{axisSizeTag}!", WarningEnum.High);
  633. warning(WarningEnum.High);
  634. return stepIndex;
  635. }
  636. string[] posePT= sizeTagObj.posePT.Split(',');
  637. if(posePT.Length < useIndex+ AxisIndexList.Count)
  638. {
  639. AddTextEvent($"{stepIndex + 1}-{processName}", $"Tag:{axisSizeTag}对应消费索引:{useIndex},Axis数量:{AxisIndexList.Count} 超出postPT:{sizeTagObj.posePT} 范围!", WarningEnum.High);
  640. warning(WarningEnum.High);
  641. return stepIndex;
  642. }
  643. double[] TagPPUValue = new double[AxisIndexList.Count];
  644. for (int i = 0; i < AxisIndexList.Count; i++)
  645. TagPPUValue[i] = double.Parse(posePT[useIndex + i]);
  646. string axisTagMsg = $"消费Tag:{axisSizeTag},索引:{useIndex}, 轴:{string.Join(",", AxisIndexList.ToList())},数据:{(TagMoveMode== AxMoveMode.绝对位置 ? "绝对" : "相对")}({string.Join(",", TagPPUValue.ToList())})";
  647. AddTextEvent($"{stepIndex + 1}-{processName}", axisTagMsg);
  648. setDgvContentCol(liStatocStepIndex, axisTagMsg);
  649. //移动Axis前等待厚度传感器收回
  650. if (!Config.SkipHeight)
  651. {
  652. while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue))
  653. {
  654. if (isBreakProcessRun())
  655. return stepIndex; //如果是相对位置,这里返回会有问题
  656. Thread.Sleep(10);
  657. }
  658. }
  659. for (int i = 0; i < AxisIndexList.Count && i < TagPPUValue.Length; i++)
  660. {
  661. while (!devContainer.devAxis.isReady(AxisIndexList[i]))
  662. {
  663. Thread.Sleep(100);
  664. if (isBreakProcessRun())
  665. return stepIndex;
  666. }
  667. devContainer.devAxis.setAxisVelParam(TagVelLow, TagVelHigh, TagAcc, TagDec, AxisIndexList[i]);
  668. if (!devContainer.devAxis.move_ptp(AxisIndexList[i], TagPPUValue[i], TagMoveMode))
  669. {
  670. AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndexList[i]}运动失败!", WarningEnum.Low);
  671. warning(WarningEnum.Low);//终止
  672. return stepIndex;//如果是相对位置,这里返回会有问题
  673. }
  674. //AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴{AxisIndexList[i]}运行完成...");
  675. //while (!asynRun && !devContainer.devAxis.isReady(AxisIndexList[i]))
  676. //{
  677. // Thread.Sleep(100);
  678. // if (isBreakProcessRun())
  679. // {
  680. // currProcessIndex = stepIndex + 1;
  681. // return stepIndex;//如果是相对位置,这里返回会有问题
  682. // }
  683. //}
  684. //if (devContainer.devAxis.isReady(AxisIndexList[i]))
  685. // AddTextEvent($"{stepIndex + 1}-{processName}", $"轴{AxisIndexList[i]}运行完成,当前命令位置:{devContainer.devAxis.getCmdPos_mm(AxisIndexList[i])},反馈位置:{devContainer.devAxis.getActualPos_mm(AxisIndexList[i])}");
  686. }
  687. if (sizeTagObj.ConsumeStepIndex == null) sizeTagObj.ConsumeStepIndex = "";
  688. sizeTagObj.ConsumeStepIndex += $"{stepIndex + 1}-{useIndex}, ";//消费工序ID
  689. //多轴同时运行后强制等待各轴完成
  690. AddTextEvent($"{stepIndex + 1}-{processName}", $"等待轴组运行完成...");
  691. while (!devContainer.devAxis.isReady())
  692. {
  693. Thread.Sleep(100);
  694. if (isBreakProcessRun())
  695. {
  696. currProcessIndex = stepIndex + 1;
  697. return stepIndex;
  698. }
  699. }
  700. AddTextEvent($"{stepIndex + 1}-{processName}", $"轴组运行完成。");
  701. #endregion
  702. break;
  703. case "Light":
  704. #region
  705. if (Config.SkipLight)
  706. {
  707. AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!");
  708. setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!");
  709. break;
  710. }
  711. int ChannelIndex = processParam.Value<int>("ChannelIndex"); //通道
  712. int DigitalValue = processParam.Value<int>("DigitalValue"); //亮度
  713. int nowDiaitalValue = devContainer.devLight.getDigitalValue(ChannelIndex);
  714. AddTextEvent($"{stepIndex + 1}-{processName}", $"通道{ChannelIndex}当前值:{nowDiaitalValue},准备更新值:{DigitalValue}...");
  715. devContainer.devLight.setDigitalValue(ChannelIndex, DigitalValue);
  716. nowDiaitalValue = devContainer.devLight.getDigitalValue(ChannelIndex);
  717. AddTextEvent($"{stepIndex + 1}-{processName}", $"通道{ChannelIndex}更新后当前值:{nowDiaitalValue}。");
  718. #endregion
  719. break;
  720. case "Scanner_GENTL":
  721. #region
  722. if (Config.SkipScannerGL)
  723. {
  724. AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!");
  725. setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!");
  726. break;
  727. }
  728. while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待
  729. {
  730. Thread.Sleep(100);
  731. if (isBreakProcessRun())
  732. {
  733. //currProcessIndex = stepIndex;//本工序没执行,step不变
  734. return stepIndex;
  735. }
  736. }
  737. AIEngineLibEnum AIEngineLib = AIEngineLibEnum.缺陷库;
  738. if(processParam.ContainsKey("AIEngineLib"))
  739. AIEngineLib=(AIEngineLibEnum)processParam.Value<int>("AIEngineLib");
  740. float ExposureTime = processParam.Value<float>("ExposureTime"); //曝光
  741. float Gain = processParam.Value<float>("Gain"); //增益
  742. float ResultingFrameRate = processParam.Value<float>("ResultingFrameRate"); //帧率
  743. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机开始采集照片...");
  744. devContainer.devScannerGentl.setParam(ExposureTime, Gain, ResultingFrameRate);
  745. endEvent = new AutoResetEvent(false);
  746. devContainer.devScannerGentl.ScanEvent = (num, bmpout) =>
  747. {
  748. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成。");
  749. //----缺陷队列
  750. //bool cloneUse = false;
  751. if (AIEngineLib == AIEngineLibEnum.缺陷库 || AIEngineLib == AIEngineLibEnum.缺陷与测量库)
  752. {
  753. //cloneUse = true;
  754. var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmpout);
  755. scannerGBmpQueue.Enqueue(new scannerGBmpLoc(mat,
  756. devContainer.devAxis.getActualPos_mm(1),
  757. devContainer.devAxis.getActualPos_mm(2)));//Dequeue
  758. AddTextEvent($"{stepIndex + 1}-{processName}", $"缺陷图像队列数量: {scannerGBmpQueue.Count}");
  759. }
  760. if (AIEngineLib == AIEngineLibEnum.测量库 || AIEngineLib == AIEngineLibEnum.缺陷与测量库)
  761. {
  762. //v1.2.2. 修改传图
  763. //scannerCBmpQueue.Enqueue(new scannerCBmpLoc(
  764. // cloneUse?(Bitmap)bmpout.Clone(): bmpout,
  765. // devContainer.devAxis.getActualPos_mm(1),
  766. // devContainer.devAxis.getActualPos_mm(2)));//Dequeue
  767. scannerCBmpQueue.Enqueue(new scannerCBmpLoc(
  768. (Bitmap)bmpout.Clone(),
  769. devContainer.devAxis.getActualPos_mm(1),
  770. devContainer.devAxis.getActualPos_mm(2)));//Dequeue
  771. AddTextEvent($"{stepIndex + 1}-{processName}", $"添加尺寸图像队列,X:{devContainer.devAxis.getActualPos_mm(1)},y:{devContainer.devAxis.getActualPos_mm(2)},数量: {scannerCBmpQueue.Count}");
  772. }
  773. endEvent.Set();//线程返回
  774. };
  775. //AddTextEvent($"{stepIndex + 1}-{processName}", $"软触发拍照...");
  776. if (!devContainer.devScannerGentl.scan(1))//软触发拍照
  777. {
  778. devContainer.devScannerGentl.ScanEvent = null;
  779. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片失败!", WarningEnum.Low);
  780. warning(WarningEnum.Low);//终止
  781. return stepIndex;
  782. }
  783. if (!endEvent.WaitOne(10000))
  784. {
  785. devContainer.devScannerGentl.ScanEvent = null;
  786. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片超时!", WarningEnum.Low);
  787. warning(WarningEnum.Low);//终止
  788. return stepIndex;
  789. }
  790. devContainer.devScannerGentl.ScanEvent = null;
  791. #endregion
  792. break;
  793. case "Scanner_CC":
  794. #region
  795. if (Config.SkipScannerCC)
  796. {
  797. AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!");
  798. setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!");
  799. break;
  800. }
  801. while (!devContainer.devAxis.isReady())//因启用轴异步功能,使用前需等待
  802. {
  803. Thread.Sleep(100);
  804. if (isBreakProcessRun())
  805. {
  806. //currProcessIndex = stepIndex;//本工序没执行,step不变
  807. return stepIndex;
  808. }
  809. }
  810. float ExposureTimeCC = processParam.Value<float>("ExposureTime"); //曝光
  811. float GainCC = processParam.Value<float>("Gain"); //增益
  812. float ResultingFrameRateCC = processParam.Value<float>("ResultingFrameRate"); //帧率
  813. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机开始采集照片...");
  814. devContainer.devScannerCC.setParam(ExposureTimeCC, GainCC, ResultingFrameRateCC);
  815. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机参数设置完成。");
  816. AutoResetEvent endEventCC = new AutoResetEvent(false);
  817. //devContainer.devScannerCC.ScanEvent = (num, bmp2) =>
  818. //{
  819. // AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成.");
  820. // scannerCBmpQueue.Enqueue(bmp2);//Dequeue
  821. // endEventCC.Set();//线程返回
  822. //};
  823. devContainer.devScannerCC.ScanEventPath += new System.Action<int, string>((num, path2) =>
  824. {
  825. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片完成.");
  826. scannerCBmpQueue.Enqueue(new scannerCBmpLoc(path2,
  827. devContainer.devAxis.getActualPos_mm(0),
  828. devContainer.devAxis.getActualPos_mm(2)));//Dequeue
  829. AddTextEvent($"{stepIndex + 1}-{processName}", $"添加尺寸图像队列,X:{ devContainer.devAxis.getActualPos_mm(0)},y: { devContainer.devAxis.getActualPos_mm(2)},数量: { scannerCBmpQueue.Count}");
  830. endEventCC.Set();//线程返回
  831. });
  832. if (!devContainer.devScannerCC.scan(1))//软触发拍照
  833. {
  834. devContainer.devScannerCC.ScanEventPath = null;
  835. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片失败!", WarningEnum.Low);
  836. warning(WarningEnum.Low);//终止
  837. return stepIndex;
  838. }
  839. if (!endEventCC.WaitOne(10000))
  840. {
  841. devContainer.devScannerCC.ScanEventPath = null;
  842. AddTextEvent($"{stepIndex + 1}-{processName}", $"相机采集照片超时!", WarningEnum.Low);
  843. warning(WarningEnum.Low);//终止
  844. return stepIndex;
  845. }
  846. devContainer.devScannerCC.ScanEventPath = null;
  847. #endregion
  848. break;
  849. case "SmallAxis":
  850. #region
  851. if (Config.SkipSmallAxis)
  852. {
  853. AddTextEvent($"{stepIndex + 1}-{processName}", $"设备禁用,忽略此步骤!");
  854. setDgvContentCol(liStatocStepIndex, $"设备禁用,忽略此步骤!");
  855. break;
  856. }
  857. int CmdPos = processParam.Value<int>("CmdPos"); //命令脉冲
  858. AddTextEvent($"{stepIndex + 1}-{processName}", $"开始由起始位置{devContainer.devSmallAxis.getCurrPPU()}运动到{CmdPos}...");
  859. devContainer.devSmallAxis.gotoPos(CmdPos, true);
  860. AddTextEvent($"{stepIndex + 1}-{processName}", $"运动完成,当前位置:{devContainer.devSmallAxis.getCurrPPU()}");
  861. #endregion
  862. break;
  863. case "Size":
  864. #region
  865. asynRun = processParam.Value<bool>("AsynRun");//异步
  866. limitThresholdVal = processParam.Value<double>("LimitThresholdVal");
  867. lowerThresholdVal = processParam.Value<double>("LowerThresholdVal");
  868. int sizeIndex = processParam.Value<int>("Index");
  869. string sizeTag = processParam.ContainsKey("SizeTag") ? processParam.Value<string>("SizeTag") : "";
  870. //2023-10-27
  871. bool useMap = false;
  872. List<double> getPosList = new List<double>();
  873. try
  874. {
  875. useMap = processParam.Value<bool>("UseMapPoints");
  876. if (useMap) {
  877. var list = model.GetPointList.Split(',');
  878. List<double> dList = new List<double>();
  879. if (list.Length < 28)
  880. {
  881. for (int i = 0; i < 28; i++)
  882. {
  883. dList.Add(0);
  884. }
  885. }
  886. else
  887. {
  888. for (int i = 0; i < list.Length; i++)
  889. {
  890. dList.Add(double.Parse(list[i]));
  891. }
  892. }
  893. getPosList = dList;
  894. }
  895. else
  896. {
  897. for (int i = 0; i < 28; i++)
  898. getPosList.Add(0);
  899. }
  900. //getPosList = processParam.Value<JArray>("GetPointList").ToObject<List<double>>();
  901. }
  902. catch
  903. {
  904. for (int i = 0; i < 28; i++)
  905. getPosList.Add(0);
  906. }
  907. double[] getPosArray = getPosList.ToArray();
  908. if (scannerCBmpQueue.Count < 1)
  909. {
  910. AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测异常,无源图像!!", WarningEnum.Low);
  911. warning(WarningEnum.Low);//暂停
  912. return stepIndex;
  913. }
  914. var bmpCBmpQueue = scannerCBmpQueue.Dequeue();
  915. AddTextEvent($"{stepIndex + 1}-{processName}", $"开始尺寸检测,index:{sizeIndex},posX:{bmpCBmpQueue.PosX},posY:{bmpCBmpQueue.PosY},图像队列数量: {scannerCBmpQueue.Count}...");
  916. attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0);
  917. AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},{model.AttachmentList.Count}|{(attachmentFile == null ? "null": attachmentFile.NameTimestamp+ attachmentFile.ExtendName)}");
  918. if (attachmentFile != null)
  919. {
  920. gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}";
  921. if (!File.Exists(gbxBmpPath+ attachmentFile.ExtendName)) gbxBmpPath = "";
  922. }
  923. if ((sizeIndex == 333 || sizeIndex == 777) && gbxBmpPath == "")
  924. AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},图纸不存在!", WarningEnum.Low);
  925. //2023-10-27
  926. //if ((sizeIndex == 3333)&&(getPosList != null) && (getPosList.Count() != 28))
  927. // AddTextEvent($"{stepIndex + 1}-{processName}", $"尺寸检测,index:{sizeIndex},图纸读点不存在!", WarningEnum.Low);
  928. if (useMap&&(sizeIndex == 3333) && (getPosArray != null) && (getPosArray.Count() == 28) && (getPosArray[0] != 0))
  929. AddTextEvent($"{stepIndex + 1}-{processName}", $"开始图纸读点,index:{sizeIndex},PT1:{getPosArray[0]},PT2:{getPosArray[2]},PT3:{getPosArray[4]},PT4:{getPosArray[6]},PT5:{getPosArray[8]}," +
  930. $"线宽1:[{getPosArray[10]},{getPosArray[11]}],线宽2:[{getPosArray[12]},{getPosArray[13]}],线宽3:[{getPosArray[14]},{getPosArray[15]}]," +
  931. $"线宽4:[{getPosArray[16]},{getPosArray[17]}],线宽5:[{getPosArray[18]},{getPosArray[19]}],线宽6:[{getPosArray[20]},{getPosArray[21]}]," +
  932. $"线宽7:[{getPosArray[22]},{getPosArray[23]}],线宽8:[{getPosArray[24]},{getPosArray[25]}],线宽9:[{getPosArray[26]},{getPosArray[27]}]");
  933. //需要偏移校正,index=0时不能异步 //10,20,30... 
  934. endEvent = new AutoResetEvent(false);
  935. devContainer.libSize.add(new SizeTask()
  936. {
  937. stepIndex = stepIndex,
  938. processName = processName,
  939. sizeTag = sizeTag,
  940. engineName = processParam.Value<string>("EngineName"),
  941. bmp = (Bitmap)bmpCBmpQueue.BMP.Clone(),//bmp/file_path二选一,优先bmp
  942. file_path = bmpCBmpQueue.Path,
  943. drawingPagePath = gbxBmpPath,
  944. posX= bmpCBmpQueue.PosX,
  945. posY= bmpCBmpQueue.PosY,
  946. //2023-10-27
  947. PTandLinePos = getPosArray,
  948. index = sizeIndex,// scannerCBmpIndex++,
  949. ContoursAffineTrans1_Out=this.contoursAffineTrans1_Out,//只有777时才使用最近333输出的结果
  950. finishEvent = (res) =>
  951. {
  952. try
  953. {
  954. //比对
  955. if (res.index == 777)//比对
  956. {
  957. if (res.isSucceed)
  958. {
  959. setDgvContentCol(liStatocStepIndex, $"index:{res.index}-{compBmpIndex},posX:{res.posX},posY:{res.posY},图像比对:{(res.CompResult ? "通过" : "未通过")} ");
  960. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对,index:{res.index}-{compBmpIndex},posX:{res.posX},posY:{res.posY},结果:{(res.CompResult ? "通过" : "未通过")}");
  961. //
  962. if (order.CompareResult < 2)
  963. order.CompareResult = res.CompResult ? 1 : 2;
  964. updateCompareResult(res.CompResult);//更新比对看板
  965. if (!res.CompResult)
  966. {
  967. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对,未通过结果:{JsonConvert.SerializeObject(res.defectInfor2RestorationDesk)}");
  968. //转为图纸上坐标位置
  969. if (res.defectInfor2RestorationDeskPage != null && res.defectInfor2RestorationDeskPage.Count > 0)
  970. {
  971. //AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"转换到图纸后坐标数据:{JsonConvert.SerializeObject(res.defectInfor2RestorationDeskPage)}");
  972. if (order.DefectInfoList == null)
  973. order.DefectInfoList = new List<DefectInfo>();
  974. foreach (var item in res.defectInfor2RestorationDeskPage)
  975. order.DefectInfoList.Add(new DefectInfo()
  976. {
  977. Type = 1,
  978. Code = item[3],
  979. X = double.Parse(item[1]),
  980. Y = double.Parse(item[2]),
  981. ZXD = double.Parse(item[4]),
  982. ModifyUserCode = Config.loginUser.Code,
  983. CreateUserCode = Config.loginUser.Code,
  984. });
  985. }
  986. //比对失败的图片 -- 用于修复台调用
  987. Bitmap bmpCompareFailZoomImage = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.Zoom_Image_mat);
  988. lstCompareFailZoomImage.Add(bmpCompareFailZoomImage);
  989. if (Config.SizeBmp_Zoom_Image_SavePath != "" && Directory.Exists(Config.SizeBmp_Zoom_Image_SavePath))
  990. {
  991. string path = Util.createSubDir(Config.SizeBmp_Zoom_Image_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  992. //path += $"Size_SN{order.SN}_I{res.index}_X{res.Defects_X}_Y{res.Defects_Y}_C0_{ model.StepInfo.Name}";
  993. path += $"Size_SN{order.SN}_I{compBmpIndex}_X{res.posX}_Y{res.posY}_C0_{ model.StepInfo.Name}";
  994. bmpCompareFailZoomImage.Save(path + ".bmp", ImageFormat.Bmp);
  995. if (res.defectInfor2RestorationDesk != null && res.defectInfor2RestorationDesk.Count > 0)
  996. File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.defectInfor2RestorationDesk));
  997. }
  998. //保存原图
  999. if (Config.SizeBmp_Compare_SavePath != "" && Directory.Exists(Config.SizeBmp_Compare_SavePath))
  1000. {
  1001. string path = Util.createSubDir(Config.SizeBmp_Compare_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1002. path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp";
  1003. AddTextEvent($"{res.stepIndex + 1}-{processName}", $"未通过图片保存:{path}");
  1004. if (res.bmp != null)
  1005. res.bmp.Save(path, ImageFormat.Bmp);
  1006. else
  1007. API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快
  1008. }
  1009. }
  1010. }
  1011. else
  1012. {
  1013. //warning(WarningEnum.Low);//暂停
  1014. setDgvContentCol(liStatocStepIndex, $"index:{res.index},图像比对失败!");
  1015. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"图像比对失败,index:{res.index}-{compBmpIndex}.", WarningEnum.Low);
  1016. }
  1017. compBmpIndex++;
  1018. }
  1019. //MARK
  1020. else if (res.index == 111 || res.index == 222 || res.index == 333 || res.index == 444)
  1021. {
  1022. AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index},结果记录...");
  1023. if (res.index == 333) this.contoursAffineTrans1_Out = res.ContoursAffineTrans1_Out;//不管成功失败都替换
  1024. if (res.isSucceed)
  1025. {
  1026. Thread.Sleep(100);
  1027. AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index}; 当前值:{string.Join(",", res.MarkPointList)}");
  1028. JArray markDatas;
  1029. if (string.IsNullOrWhiteSpace(order.MarkData))
  1030. markDatas = new JArray() { 0, 0, 0, 0, 0, 0, 0, 0 };
  1031. else
  1032. markDatas = JArray.Parse(order.MarkData);
  1033. for (int i = 0; i < res.MarkPointList.Count(); i++)
  1034. if (res.MarkPointList[i] != 0)
  1035. markDatas[i] = res.MarkPointList[i];
  1036. order.MarkData = markDatas.ToString();
  1037. setDgvContentCol(liStatocStepIndex, $"index:{res.index},Mark点:{order.MarkData} ");
  1038. AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点 Index={res.index};合并后:{order.MarkData}");
  1039. }
  1040. else
  1041. {
  1042. //warning(WarningEnum.Low);//暂停
  1043. setDgvContentCol(liStatocStepIndex, $"index:{res.index},Mark点计算失败!");
  1044. AddTextEvent($"{res.stepIndex + 1}-{processName}", $"Mark点计算失败,index:{res.index}.", WarningEnum.Low);
  1045. //2023-10-20 make暂停
  1046. if (Config.OpenMarkErrorStop)
  1047. warning(WarningEnum.Low);//暂停
  1048. }
  1049. //保存
  1050. if (Config.SizeBmp_SavePath != "" && Directory.Exists(Config.SizeBmp_SavePath))
  1051. {
  1052. string path = Util.createSubDir(Config.SizeBmp_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1053. path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp";
  1054. if (res.bmp != null)
  1055. res.bmp.Save(path, ImageFormat.Bmp);
  1056. else
  1057. API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快
  1058. }
  1059. }
  1060. else
  1061. {
  1062. int roundIndex = res.index % 10;
  1063. if (res.isSucceed)
  1064. {
  1065. string tagOutData = "";
  1066. if (res.index == 3333 && !string.IsNullOrWhiteSpace(res.sizeTag))
  1067. {
  1068. tagOutData = $"Tag:{res.sizeTag},posePT:[{string.Join(",", res.posePT)}]";
  1069. if (res.posePT.Length < 2 || res.posePT.Length % 2 != 0)
  1070. {
  1071. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测输出Tag对应posePT非法: {tagOutData}", WarningEnum.High);
  1072. warning(WarningEnum.High);//急停
  1073. return;
  1074. }
  1075. //2023-10-27
  1076. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"Tag对应posePT: {tagOutData}", WarningEnum.Normal);
  1077. if (order.SizeTagDataList == null)
  1078. order.SizeTagDataList = new List<SizeTagData>();
  1079. order.SizeTagDataList.Add(new SizeTagData()
  1080. {
  1081. SizeTag = res.sizeTag,
  1082. CreateStepIndex = res.stepIndex + 1,
  1083. posePT= string.Join(",", res.posePT)// 回转 Array.ConvertAll(sNums , double.Parse);
  1084. });
  1085. }
  1086. setDgvContentCol(liStatocStepIndex, $"index:{res.index},PT1:{res.PT1},PT2:{res.PT2},Shanxian:{res.Shanxian},Circle_Xmm:{res.Circle_Xmm},Circle_Ymm:{res.Circle_Ymm},offsetX:{res.offsetX},offsetY:{res.offsetY}, {tagOutData}");
  1087. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测完成 index:{res.index},PT1:{res.PT1},PT2:{res.PT2},Shanxian:{res.Shanxian},Circle_Xmm:{res.Circle_Xmm},Circle_Ymm:{res.Circle_Ymm},offsetX:{res.offsetX},offsetY:{res.offsetY}, {tagOutData} ");
  1088. //测量
  1089. //------TEST
  1090. if (res.index>20 && res.index<30)
  1091. {
  1092. lock (lstPT)
  1093. {
  1094. lstPT.Add(Math.Round(res.PT1, 4));
  1095. updatePTValueTest(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue);
  1096. }
  1097. }
  1098. //------
  1099. if (roundIndex > 0)//1-9测量
  1100. {
  1101. if (res.index < 10)//11-13 (PT: 7-9 => 21-29(PT1)) 不用管,李工处理
  1102. {
  1103. //if (roundIndex >= 7)
  1104. //{
  1105. // lock (lstPT)
  1106. // {
  1107. // lstPT.Add(Math.Round(res.PT1, 4));
  1108. // lstPT.Add(res.index == 8 ? 0 : Math.Round(res.PT2, 4));
  1109. // updatePTValue(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue);
  1110. // }
  1111. //}
  1112. lock (lstLineWidth)
  1113. {
  1114. lstLineWidth.Add(res.Shanxian > 0 ? Math.Round(res.Shanxian, 2) : 0);
  1115. updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue);
  1116. }
  1117. }
  1118. }
  1119. //校正偏移 10,20,30...:偏移
  1120. else
  1121. {
  1122. AxMoveMode axSizeMode = AxMoveMode.绝对位置;
  1123. double xPos = 0;
  1124. double yPos = 0;
  1125. //绝对偏移
  1126. if (res.offsetX != 0 || res.offsetY != 0)
  1127. {
  1128. xPos += res.offsetX;
  1129. yPos += res.offsetY;
  1130. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"offsetX/Y绝对校正, 0轴:{xPos}mm, 2轴:{yPos}mm");
  1131. }
  1132. else if (res.Circle_Xmm != 0 || res.Circle_Ymm != 0)//相对偏移校正
  1133. {
  1134. axSizeMode = AxMoveMode.相对位置;
  1135. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"原点相对校正, 0轴:{res.Circle_Xmm}mm, 2轴:{res.Circle_Ymm}mm");
  1136. if (res.Circle_Xmm != 0) xPos = res.Circle_Xmm;
  1137. if (res.Circle_Ymm != 0) yPos = res.Circle_Ymm;
  1138. }
  1139. //当前工序直接移动
  1140. if (xPos != 0 || yPos != 0)
  1141. {
  1142. devContainer.devAxis.setAxisVelParam(0.1, 1, 1, 1, 0);
  1143. devContainer.devAxis.setAxisVelParam(0.1, 1, 1, 1, 2);
  1144. if (xPos != 0) devContainer.devAxis.move_ptp(0, xPos, axSizeMode);
  1145. if (yPos != 0) devContainer.devAxis.move_ptp(2, yPos, axSizeMode);
  1146. while (!devContainer.devAxis.isReady(0) || !devContainer.devAxis.isReady(2))
  1147. {
  1148. Thread.Sleep(100);
  1149. if (isBreakProcessRun())
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. //保存
  1155. //string sizeFileName = Config.Size_SavePath + "\\" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
  1156. //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//更快
  1157. //File.WriteAllText(defectFileName + ".json", JsonConvert.SerializeObject(res.informationList));
  1158. }
  1159. //失败
  1160. else
  1161. {
  1162. //------TEST
  1163. if (res.index > 20 && res.index < 30)
  1164. {
  1165. lock (lstPT)
  1166. {
  1167. lstPT.Add(0);
  1168. updatePTValueTest(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue);
  1169. }
  1170. }
  1171. //------
  1172. if (roundIndex > 0)
  1173. {
  1174. //if (roundIndex >= 7)
  1175. //{
  1176. // lock (lstPT)
  1177. // {
  1178. // lstPT.Add(0);
  1179. // lstPT.Add(0);
  1180. // updatePTValue(model.PTBaseValue + model.PTUpFloatValue, model.PTBaseValue - model.PTDownFloatValue);
  1181. // }
  1182. //}
  1183. lock (lstLineWidth)
  1184. {
  1185. lstLineWidth.Add(0);
  1186. updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue);
  1187. }
  1188. }
  1189. setDgvContentCol(liStatocStepIndex, $"失败:{res.resultInfo}");
  1190. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测失败index:{res.index}:{res.resultInfo}");
  1191. //warning(WarningEnum.Low);//暂停 这里不能暂停,stepIndex和scannerBmpQueue队列也不对了
  1192. }
  1193. //保存
  1194. if (Config.SizeBmp_SavePath != "" && Directory.Exists(Config.SizeBmp_SavePath))
  1195. {
  1196. string path = Util.createSubDir(Config.SizeBmp_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1197. path += $"Size_SN{order.SN}_I{res.index}_X{res.posX}_Y{res.posY}_{ model.StepInfo.Name}.bmp";
  1198. if (res.bmp != null)
  1199. res.bmp.Save(path, ImageFormat.Bmp);
  1200. else
  1201. API.CopyFile(res.file_path, path, false);//比.NET(File.Copy)更快
  1202. }
  1203. }
  1204. }
  1205. catch(Exception ex)
  1206. {
  1207. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"尺寸检测回调处理异常 index:{res.index},ex={ex.Message}");
  1208. }
  1209. //
  1210. //if (!asynRun)//是否异步执行endEvent.Set()都没问题
  1211. endEvent.Set();//roundIndex=0成功或失败线程返回
  1212. //---
  1213. if (res.bmp != null)
  1214. {
  1215. res.bmp.Dispose();
  1216. res.bmp = null;
  1217. }
  1218. else
  1219. {
  1220. API.DeleteFile(res.file_path);
  1221. }
  1222. }
  1223. });
  1224. //需等上面异步回调中的相对偏移校正完成再继续
  1225. if (!asynRun || sizeIndex % 10==0)
  1226. {
  1227. if (!endEvent.WaitOne(60000))
  1228. AddTextEvent($"{stepIndex + 1}-{processName}", $"{sizeIndex}等待超时,忽略继续!", WarningEnum.Low);
  1229. }
  1230. #endregion
  1231. break;
  1232. case "Defect":
  1233. #region
  1234. limitThresholdVal = processParam.Value<double>("LimitThresholdVal");
  1235. lowerThresholdVal = processParam.Value<double>("LowerThresholdVal");
  1236. if (scannerGBmpQueue.Count < 1)
  1237. {
  1238. AddTextEvent($"{stepIndex + 1}-{processName}", $"缺陷检测异常,无源图像!!", WarningEnum.Low);
  1239. warning(WarningEnum.Low);//终止
  1240. return stepIndex;
  1241. }
  1242. var bmpLoc = scannerGBmpQueue.Dequeue();
  1243. AddTextEvent($"{stepIndex + 1}-{processName}", $"开始缺陷检测,源图索引:{defectBmpNum},图像队列数量: {scannerGBmpQueue.Count}...");
  1244. string[] aarCut_size = processParam.Value<string>("CutSize").Split(',');
  1245. string[] aarResize = processParam.Value<string>("Resize").Split(',');
  1246. //图纸
  1247. attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0);
  1248. if (attachmentFile != null)
  1249. {
  1250. gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}";
  1251. if (!File.Exists(gbxBmpPath + attachmentFile.ExtendName)) gbxBmpPath = "";
  1252. }
  1253. AddTextEvent($"{stepIndex + 1}-{processName}", $"图纸路径:{gbxBmpPath}");
  1254. devContainer.libDefect.add(new DefectTask()
  1255. {
  1256. stepIndex= stepIndex,
  1257. processName= processName,
  1258. drawingPagePath= gbxBmpPath,
  1259. index = defectBmpNum++,
  1260. bmp = bmpLoc.bmp,
  1261. Xmm = bmpLoc.Xmm,
  1262. Ymm = bmpLoc.Ymm,
  1263. cut_size = new System.Drawing.Size(Convert.ToInt32(aarCut_size[0]), Convert.ToInt32(aarCut_size[1])),
  1264. resize = new System.Drawing.Size(Convert.ToInt32(aarResize[0]), Convert.ToInt32(aarResize[1])),
  1265. thresholds = processParam.Value<float>("Thresholds"),
  1266. thresholdsClass = processParam.Value<string>("ThresholdsClass"),
  1267. recAreaThreshold= getProductAreaThreshol(model), //qxName,面积; qxName,面积; qxName,面积;
  1268. finishEvent = (res) =>
  1269. {
  1270. if (res.isSucceed)
  1271. {
  1272. setDgvContentCol(liStatocStepIndex, $"源图索引:{res.index},缺陷数:{res.defectCount},处理时间(ms):{string.Join("->", res.stopwatch.Select(i => i.ToString()).ToArray())}");
  1273. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"缺陷检测完成(源图索引:{res.index}),缺陷数:{res.defectCount},处理时间(ms):{string.Join("->", res.stopwatch.Select(i => i.ToString()).ToArray())}");
  1274. string path;
  1275. if (res.defectCount > 0)
  1276. {
  1277. //UI显示小图 (含统计缺陷类型数量)
  1278. showDefectSmallBmps(res.bmps_tag, res.bmps_cut, res.Xmm, res.Ymm, res.informationList);
  1279. if (res.defectInfor2RestorationDeskPage != null && res.defectInfor2RestorationDeskPage.Count > 0)
  1280. {
  1281. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"转换后坐标数据:{JsonConvert.SerializeObject(res.defectInfor2RestorationDeskPage)}");
  1282. if (order.DefectInfoList == null)
  1283. order.DefectInfoList = new List<DefectInfo>();
  1284. foreach (var item in res.defectInfor2RestorationDeskPage)
  1285. order.DefectInfoList.Add(new DefectInfo()
  1286. {
  1287. Type = 0,
  1288. Code = item[3],
  1289. X = double.Parse(item[1]),
  1290. Y = double.Parse(item[2]),
  1291. ZXD = double.Parse(item[4]),
  1292. ModifyUserCode = Config.loginUser.Code,
  1293. CreateUserCode = Config.loginUser.Code,
  1294. });
  1295. }
  1296. //保存原始大图
  1297. if (Config.Defect_SavePath != "" && Directory.Exists(Config.Defect_SavePath))
  1298. {
  1299. path = Util.createSubDir(Config.Defect_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1300. path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}";
  1301. //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//比.NET(File.Copy)更快
  1302. //res.bmp.SaveImage(path + ".bmp");//opencv保存格式与BMP不同
  1303. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save(path + ".bmp", ImageFormat.Bmp);
  1304. File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.informationList));
  1305. }
  1306. //保存小图
  1307. if (Config.Defect_Small_SavePath != "" && Directory.Exists(Config.Defect_Small_SavePath))
  1308. {
  1309. path = Util.createSubDir(Config.Defect_Small_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1310. path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_{ model.StepInfo.Name}";
  1311. for (int i = 0; i < res.bmps_tag.Count(); i++)
  1312. res.bmps_tag[i].Save(path + $"_i{i}.bmp", ImageFormat.Bmp);
  1313. }
  1314. //保存压缩大图 -- 用于修复台调用
  1315. if (Config.Defect_Compress_SavePath != "" && Directory.Exists(Config.Defect_Compress_SavePath))
  1316. {
  1317. path = Util.createSubDir(Config.Defect_Compress_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1318. path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}";
  1319. //res.bmpCompress.SaveImage(path + ".bmp");//opencv保存格式与BMP不同
  1320. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmpCompress).Save(path + ".bmp", ImageFormat.Bmp);
  1321. File.WriteAllText(path + ".json", JsonConvert.SerializeObject(res.defectInfor2RestorationDesk));
  1322. }
  1323. }
  1324. else//没有缺陷
  1325. {
  1326. if (Config.SaveAllDefectImg && Config.Defect_SavePath != "" && Directory.Exists(Config.Defect_SavePath))
  1327. {
  1328. path = Util.createSubDir(Config.Defect_SavePath, new List<string> { order.CreateTime.ToString("yyyyMMdd"), order.SN });
  1329. path += $"Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}_{ model.StepInfo.Name}";
  1330. //API.CopyFile(res.file_path, defectFileName + ".bmp", false);//比.NET(File.Copy)更快
  1331. //res.bmp.SaveImage(path + ".bmp");//opencv保存格式与BMP不同
  1332. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(res.bmp).Save(path + ".bmp", ImageFormat.Bmp);
  1333. }
  1334. }
  1335. }
  1336. else
  1337. {
  1338. setDgvContentCol(liStatocStepIndex, $"失败:{res.resultInfo}");
  1339. AddTextEvent($"{res.stepIndex + 1}-{res.processName}", $"缺陷检测失败:{res.resultInfo}");
  1340. //warning(WarningEnum.Low);//暂停 这里不能暂停,stepIndex和scannerBmpQueue队列也不对了
  1341. }
  1342. defectBmpNumResult++;
  1343. foreach (var item in res.bmps_cut)
  1344. item.Dispose();
  1345. res.bmp.Dispose();
  1346. res.bmp = null;
  1347. res.bmps_tag = null;
  1348. if (res.bmpCompress != null)
  1349. {
  1350. res.bmpCompress.Dispose();
  1351. res.bmpCompress = null;
  1352. }
  1353. System.GC.Collect();
  1354. }
  1355. });
  1356. #endregion
  1357. break;
  1358. case "For":
  1359. #region
  1360. long UniqueId = processParam.Value<long>("UniqueId");
  1361. int GotoStepIndex = processParam.Value<int>("GotoStepIndex");//1-n
  1362. int LimitNum = processParam.Value<int>("LimitNum");//1-n
  1363. bool Reset = processParam.Value<bool>("Reset");
  1364. if (GotoStepIndex - 1 == stepIndex)
  1365. {
  1366. AddTextEvent($"{stepIndex + 1}-{processName}", $"For死循环!!!");
  1367. warning(WarningEnum.High);
  1368. return stepIndex;
  1369. }
  1370. if (!devContainer.libFor.dicData.ContainsKey(UniqueId))
  1371. devContainer.libFor.dicData.Add(UniqueId, 0);
  1372. //
  1373. int Num = devContainer.libFor.dicData[UniqueId];
  1374. Num++;
  1375. if (Num <= LimitNum)
  1376. {
  1377. if (Num == LimitNum)
  1378. {
  1379. setDgvContentCol(liStatocStepIndex, $"第[{Num}/{LimitNum}]次,循环完成");
  1380. AddTextEvent($"{stepIndex + 1}-{processName}", $"第[{Num}/{LimitNum}]次,循环完成。");
  1381. }
  1382. else
  1383. {
  1384. setDgvContentCol(liStatocStepIndex, $"第[{Num}/{LimitNum}]次");
  1385. AddTextEvent($"{stepIndex + 1}-{processName}", $"第[{Num}/{LimitNum}]次跳转到步骤[{GotoStepIndex}]...");
  1386. stepIndex = GotoStepIndex - 2;
  1387. }
  1388. devContainer.libFor.dicData[UniqueId] = Num;
  1389. }
  1390. else
  1391. {
  1392. setDgvContentCol(liStatocStepIndex, $"已失效不执行");
  1393. AddTextEvent($"{stepIndex + 1}-{processName}", $"本循环已失效不执行!");
  1394. }
  1395. //达到limit重置0
  1396. if (devContainer.libFor.dicData[UniqueId] >= LimitNum && Reset)
  1397. {
  1398. devContainer.libFor.dicData[UniqueId] = 0;
  1399. setDgvContentCol(liStatocStepIndex, $"第[0/{LimitNum}]次");
  1400. AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器已重置。");
  1401. }
  1402. #endregion
  1403. break;
  1404. case "If":
  1405. #region
  1406. long UniqueId_if = processParam.Value<long>("UniqueId");
  1407. int GotoStepIndex_if = processParam.Value<int>("GotoStepIndex");//1-n
  1408. int LimitNum_if = processParam.Value<int>("LimitNum");//1-n
  1409. bool Reset_if = processParam.Value<bool>("Reset");
  1410. if (GotoStepIndex_if - 1 == stepIndex)
  1411. {
  1412. AddTextEvent($"{stepIndex + 1}-{processName}", $"If死循环,不可自我跳转!!!");
  1413. warning(WarningEnum.High);
  1414. return stepIndex;
  1415. }
  1416. //
  1417. if (!devContainer.libIF.dicData.ContainsKey(UniqueId_if))
  1418. devContainer.libIF.dicData.Add(UniqueId_if, 0);
  1419. //
  1420. int Num_if = devContainer.libIF.dicData[UniqueId_if];
  1421. Num_if++;
  1422. if (Num_if <= LimitNum_if)
  1423. {
  1424. if (Num_if == LimitNum_if)
  1425. {
  1426. setDgvContentCol(liStatocStepIndex, $"第[{Num_if}/{LimitNum_if}]次,跳转至[{GotoStepIndex_if}]");
  1427. AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器[{Num_if}/{LimitNum_if}],跳转至步骤[{GotoStepIndex_if}]...");
  1428. stepIndex = GotoStepIndex_if - 2;
  1429. }
  1430. else
  1431. {
  1432. setDgvContentCol(liStatocStepIndex, $"第[{Num_if}/{LimitNum_if}]次,不跳转");
  1433. AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器[{Num_if}/{LimitNum_if}],不跳转。");
  1434. }
  1435. //
  1436. devContainer.libIF.dicData[UniqueId_if] = Num_if;
  1437. }
  1438. else
  1439. {
  1440. setDgvContentCol(liStatocStepIndex, $"已失效不执行");
  1441. AddTextEvent($"{stepIndex + 1}-{processName}", $"本IF已失效不执行。");
  1442. }
  1443. //达到limit重置0
  1444. if (devContainer.libIF.dicData[UniqueId_if] >= LimitNum_if && Reset_if)
  1445. {
  1446. devContainer.libIF.dicData[UniqueId_if] = 0;
  1447. setDgvContentCol(liStatocStepIndex, $"第[0/{LimitNum_if}]次");
  1448. AddTextEvent($"{stepIndex + 1}-{processName}", $"计数器已重置。");
  1449. }
  1450. #endregion
  1451. break;
  1452. default:
  1453. AddTextEvent($"{stepIndex + 1}-{processName}", $"未知工序:{processInfo.ProcessCode}");
  1454. warning(WarningEnum.High);
  1455. return stepIndex;
  1456. }
  1457. if (sleepLater > 0) Thread.Sleep((int)sleepLater);
  1458. }
  1459. //============结束,判断是否自动下料
  1460. if (stepIndex == processList.Count - 1)
  1461. {
  1462. //厚度校正 直接更新并保存
  1463. if (isProductRevise)
  1464. {
  1465. isProductRevise = false;
  1466. if (MessageBox.Show($"厚度校正完成,是否保存?\r\nBase值:{model.HeightBaseDec}", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
  1467. {
  1468. //保存 //更新指定列
  1469. if (svcProduct.Update(it => new Product() { HeightBaseDec = model.HeightBaseDec }, it => it.Id == model.Id))
  1470. AddTextEvent($"产品校正", $"保存成功。");
  1471. else
  1472. AddTextEvent($"产品校正", $"保存失败!!");
  1473. }
  1474. //下料
  1475. currentState = CurrentStateEnum.自动流程结束;
  1476. gotoDownPT();
  1477. }
  1478. else//生产
  1479. {
  1480. //等待缺陷图显示完成
  1481. while (defectBmpNum != defectBmpNumResult)
  1482. Thread.Sleep(100);
  1483. //判断是否合格
  1484. DefectCodeEnum defectCode;
  1485. string defectNames = "";
  1486. if (model.QualifiedCriterionList!= null && model.QualifiedCriterionList.Count >0)
  1487. {
  1488. int itemDefectCount;
  1489. foreach (var item in model.QualifiedCriterionList)
  1490. {
  1491. defectCode = EnumUtil.Convert2Enum<DefectCodeEnum>(item.DefectCode);
  1492. itemDefectCount = getDefectCountFromCode(order, defectCode);
  1493. if (item.MaxDefectCount>-1 && itemDefectCount > item.MaxDefectCount)
  1494. {
  1495. order.Qualified = false;
  1496. defectNames += $"{((DefectNameEnum)(int)defectCode).ToString()}({itemDefectCount}),";
  1497. }
  1498. }
  1499. }
  1500. stopWatch.Stop();
  1501. long timeLen = stopWatch.ElapsedMilliseconds / 1000;
  1502. this.BeginInvoke(new System.Action(() =>
  1503. {
  1504. lblTimeLen.Visible = true;
  1505. lblTimeLen.Text = $"检测时长: {timeLen} 秒";
  1506. if (defectNames != "")
  1507. {
  1508. lblDefectResult.Text = "未通过";
  1509. lblDefectResultCount.Text = defectNames.Substring(0, defectNames.Length - 1);
  1510. this.toolTip1.SetToolTip(lblDefectResultCount, lblDefectResultCount.Text);
  1511. lblDefectResult.ForeColor = lblDefectResultCount.ForeColor = Color.Red;
  1512. }
  1513. }));
  1514. order.TimeLen = timeLen;
  1515. order.DefectCount = (int)this.gboxDefectList.Tag;
  1516. order.Succeed = true;
  1517. order.ModifyUserCode = order.CreateUserCode = Config.loginUser.Code;
  1518. order.Abnormalities = "";//无异常
  1519. order.RepairCode = "";//无修复人员
  1520. //如SN检测已存在,先删除
  1521. var oldSNOrder= svcOrder.GetFirst(m=> m.SN==order.SN);
  1522. if(oldSNOrder!=null)
  1523. {
  1524. AddTextEvent("删除记录", $"删除上一重复SN检测记录:SN={oldSNOrder.SN}, Date={oldSNOrder.CreateTime}");
  1525. svcOrder.DelNav(oldSNOrder);
  1526. }
  1527. if (!svcOrder.InsertNav(order))//导航插入
  1528. AddTextEvent("保存失败", $"保存生产记录失败!");
  1529. //更新本批次检测数量
  1530. if (!string.IsNullOrWhiteSpace(model.BatchId))
  1531. {
  1532. var expOrder = Expressionable.Create<Order>()
  1533. .And(m => m.ProductId == model.Id)
  1534. .And(m => m.BatchId == model.BatchId)
  1535. .ToExpression();//注意 这一句 不能少
  1536. currProductModel.CompleteCount = svcOrder.Count(expOrder);
  1537. }
  1538. //以主键为条件更新CompleteCount单列值
  1539. svcProduct.Update(it => new Product() { CompleteCount = currProductModel.CompleteCount }, it => it.Id == currProductModel.Id);
  1540. if (Config.MakeTag && order.DefectCount > 0)//要打标 and 有缺陷图
  1541. {
  1542. AddTextEvent("完成", $"工序结束,用时 {order.TimeLen} 秒;缺陷 {order.DefectCount} 张.");
  1543. //+(Config.MakeTag ? "开始自动打标...":"手动打标..."));
  1544. currentPT = CurrentPTEnum.MakeTag;
  1545. currentState = CurrentStateEnum.打标中;
  1546. setButtonEnabled(tsbtnGoDownPT, true);
  1547. setButtonEnabled(tsbtnReset, true);
  1548. setButtonEnabled(btnMakeTags, true);
  1549. //if (!Config.MakeTag)//自动打标
  1550. {
  1551. this.Invoke(new System.Action(() =>
  1552. {
  1553. btnMakeTag_Click(null, null);
  1554. }));
  1555. }
  1556. }
  1557. else//下料
  1558. {
  1559. AddTextEvent("完成", $"用时 {order.TimeLen} 秒,进行下料...");
  1560. currentState = CurrentStateEnum.自动流程结束;
  1561. gotoDownPT();
  1562. }
  1563. }
  1564. currProcessIndex = -1;
  1565. return -1;
  1566. }
  1567. else //继续
  1568. {
  1569. return ++stepIndex;
  1570. //return nextProcess(model, ++stepIndex);
  1571. }
  1572. }
  1573. catch (Exception ex)
  1574. {
  1575. AddTextEvent("工序", $"[{stepIndex+1}] Err:" + ex.Message+"\n"+ex.StackTrace);
  1576. warning(WarningEnum.Low);
  1577. return -2;
  1578. }
  1579. }
  1580. private Dictionary<string, float> getProductAreaThreshol(Product m)
  1581. {
  1582. Dictionary<string, float> dic = new Dictionary<string, float>();
  1583. foreach(var item in m.QualifiedCriterionList)
  1584. dic.Add(item.DefectCode, (float)(item.Size * 25.4 * 25.4 / m.HoleCount / m.HoleCount) );//网目 => mm^2
  1585. //全缺陷项
  1586. var lstDefect = Utils.EnumUtil.GetArrayList<DefectCodeEnum>();
  1587. foreach (DictionaryEntry item in lstDefect)
  1588. {
  1589. string code = item.Value.ToString();
  1590. if (!dic.ContainsKey(code))
  1591. dic.Add(code, 0);
  1592. }
  1593. return dic;
  1594. }
  1595. private void setDgvContentCol(int rowIndex, string info)
  1596. {
  1597. int row = rowIndex;//why -1 ???
  1598. this.Invoke(new System.Action(() =>
  1599. {
  1600. this.dgvProcess.Rows[row].Cells["colValue"].Value = info;
  1601. }));
  1602. }
  1603. /// <summary>
  1604. /// 报警,只响应low,high
  1605. /// </summary>
  1606. private void warning(WarningEnum level, bool buzzer = true)
  1607. {
  1608. if (level == WarningEnum.Normal)
  1609. return;
  1610. lock(myLock)
  1611. warningLevel = level;
  1612. if (level == WarningEnum.Low)//暂停
  1613. {
  1614. currentState = CurrentStateEnum.暂停;
  1615. pauseCommand(buzzer);
  1616. }
  1617. else if (level == WarningEnum.High)//急停
  1618. {
  1619. currentState = CurrentStateEnum.急停;
  1620. devContainer.devAxis.stopNow();
  1621. stopNowCommand();
  1622. }
  1623. //启用报警消除按钮
  1624. this.Invoke(new System.Action(() =>
  1625. {
  1626. tsbtnWarning.Enabled = true;
  1627. }));
  1628. }
  1629. private void updateTensionValue(double upperLimit,double lowerLimit)
  1630. {
  1631. int count = lstTension.Count();
  1632. if (count < 1) return;
  1633. switch (count)
  1634. {
  1635. case 1:
  1636. order.Tension1 = lstTension[count - 1];
  1637. AddTextEvent("张力值", $"张力1:{order.Tension1}");
  1638. break;
  1639. case 2:
  1640. order.Tension2 = lstTension[count - 1];
  1641. AddTextEvent("张力值", $"张力2:{order.Tension2}");
  1642. break;
  1643. case 3:
  1644. order.Tension3 = lstTension[count - 1];
  1645. AddTextEvent("张力值", $"张力3:{order.Tension3}");
  1646. break;
  1647. case 4:
  1648. order.Tension4 = lstTension[count - 1];
  1649. AddTextEvent("张力值", $"张力4:{order.Tension4}");
  1650. break;
  1651. case 5:
  1652. order.Tension5 = lstTension[count - 1];
  1653. AddTextEvent("张力值", $"张力5:{order.Tension5}");
  1654. break;
  1655. }
  1656. double value = Math.Round(lstTension.Average(), 2);
  1657. double valueMax = lstTension.Max();
  1658. double valueMin = lstTension.Min();
  1659. if (order != null) order.TensionValue = value;
  1660. Color color = (upperLimit+ lowerLimit>0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White;
  1661. Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White;
  1662. Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White;
  1663. this.BeginInvoke(new System.Action(() =>
  1664. {
  1665. this.lblTension.Text = Math.Round(value, 2).ToString();
  1666. this.lblTension.ForeColor = color;
  1667. this.lblTensionMax.Text = Math.Round(valueMax, 2).ToString();
  1668. this.lblTensionMax.ForeColor = colorMax;
  1669. this.lblTensionMin.Text = Math.Round(valueMin, 2).ToString();
  1670. this.lblTensionMin.ForeColor = colorMin;
  1671. }));
  1672. //不合格
  1673. if (color == Color.Red) order.Qualified = false;
  1674. }
  1675. private void updateHeightValue(double upperLimit, double lowerLimit)
  1676. {
  1677. int count = lstHeight.Count();
  1678. if (count < 1) return;
  1679. AddTextEvent("厚度", string.Join(",", lstHeight));
  1680. switch (count)
  1681. {
  1682. case 1:
  1683. order.Height1 = lstHeight[count - 1];
  1684. AddTextEvent("厚度值", $"厚度1:{order.Height1}");
  1685. break;
  1686. case 2:
  1687. order.Height2 = lstHeight[count - 1];
  1688. AddTextEvent("厚度值", $"厚度2:{order.Height2}");
  1689. break;
  1690. case 3:
  1691. order.Height3 = lstHeight[count - 1];
  1692. AddTextEvent("厚度值", $"厚度3:{order.Height3}");
  1693. break;
  1694. case 4:
  1695. order.Height4 = lstHeight[count - 1];
  1696. AddTextEvent("厚度值", $"厚度4:{order.Height4}");
  1697. break;
  1698. case 5:
  1699. order.Height5 = lstHeight[count - 1];
  1700. AddTextEvent("厚度值", $"厚度5:{order.Height5}");
  1701. break;
  1702. }
  1703. double value = Math.Round(lstHeight.Average(), 2);
  1704. double valueMax = lstHeight.Max();
  1705. double valueMin = lstHeight.Min();
  1706. if (order != null) order.HeightValue = value;
  1707. Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White;
  1708. Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White;
  1709. Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White;
  1710. this.Invoke(new System.Action(() =>
  1711. {
  1712. this.lblHeight.Text = Math.Round(value, 2).ToString();
  1713. this.lblHeight.ForeColor = color;
  1714. this.lblHeightMax.Text = Math.Round(valueMax, 2).ToString();
  1715. this.lblHeightMax.ForeColor = colorMax;
  1716. this.lblHeightMin.Text = Math.Round(valueMin, 2).ToString();
  1717. this.lblHeightMin.ForeColor = colorMin;
  1718. }));
  1719. //不合格
  1720. if (color == Color.Red) order.Qualified = false;
  1721. }
  1722. private void updateLineWidthValue(double upperLimit, double lowerLimit)
  1723. {
  1724. int count = lstLineWidth.Count();
  1725. if (count < 1) return;
  1726. switch (count)
  1727. {
  1728. case 1:
  1729. order.LineWidth1 = lstLineWidth[count - 1];
  1730. AddTextEvent("线宽值", $"线宽1:{order.LineWidth1}");
  1731. break;
  1732. case 2:
  1733. order.LineWidth2 = lstLineWidth[count - 1];
  1734. AddTextEvent("线宽值", $"线宽2:{order.LineWidth2}");
  1735. break;
  1736. case 3:
  1737. order.LineWidth3 = lstLineWidth[count - 1];
  1738. AddTextEvent("线宽值", $"线宽3:{order.LineWidth3}");
  1739. break;
  1740. case 4:
  1741. order.LineWidth4 = lstLineWidth[count - 1];
  1742. AddTextEvent("线宽值", $"线宽4:{order.LineWidth4}");
  1743. break;
  1744. case 5:
  1745. order.LineWidth5 = lstLineWidth[count - 1];
  1746. AddTextEvent("线宽值", $"线宽5:{order.LineWidth5}");
  1747. break;
  1748. case 6:
  1749. order.LineWidth6 = lstLineWidth[count - 1];
  1750. AddTextEvent("线宽值", $"线宽6:{order.LineWidth6}");
  1751. break;
  1752. case 7:
  1753. order.LineWidth7 = lstLineWidth[count - 1];
  1754. AddTextEvent("线宽值", $"线宽7:{order.LineWidth7}");
  1755. break;
  1756. case 8:
  1757. order.LineWidth8 = lstLineWidth[count - 1];
  1758. AddTextEvent("线宽值", $"线宽8:{order.LineWidth8}");
  1759. break;
  1760. case 9:
  1761. order.LineWidth9 = lstLineWidth[count - 1];
  1762. AddTextEvent("线宽值", $"线宽9:{order.LineWidth9}");
  1763. break;
  1764. }
  1765. List<double> lstValidValue = new List<double>();
  1766. for (int i = 0; i < count; i++)
  1767. {
  1768. if (lstLineWidth[i] > 0)
  1769. lstValidValue.Add(lstLineWidth[i]);
  1770. }
  1771. if (lstValidValue.Count < 1) return;//WLQ 前面失败时会向lstLineWidth.add(0)
  1772. double value = Math.Round(lstValidValue.Average(), 2);
  1773. double valueMax = lstValidValue.Max();
  1774. double valueMin = lstValidValue.Min();
  1775. if (order != null) order.LineWidthValue = value;
  1776. Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White;
  1777. Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White;
  1778. Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White;
  1779. this.Invoke(new System.Action(() =>
  1780. {
  1781. this.lblLineWidth.Text = Math.Round(value, 2).ToString();
  1782. this.lblLineWidth.ForeColor = color;
  1783. this.lblLineWidthMax.Text = Math.Round(valueMax, 2).ToString();
  1784. this.lblLineWidthMax.ForeColor = colorMax;
  1785. this.lblLineWidthMin.Text = Math.Round(valueMin, 2).ToString();
  1786. this.lblLineWidthMin.ForeColor = colorMin;
  1787. }));
  1788. //不合格
  1789. if (color == Color.Red) order.Qualified = false;
  1790. }
  1791. private void updatePTValue(double upperLimit, double lowerLimit)
  1792. {
  1793. //每次加2个:PT1,PT2
  1794. int count = lstPT.Count();
  1795. if (count < 1) return;
  1796. switch (count)
  1797. {
  1798. case 2:
  1799. order.PT1 = lstPT[count - 2];
  1800. order.PT2 = lstPT[count - 1];
  1801. AddTextEvent("PT值",$"PT1:{order.PT1},PT2:{order.PT2}");
  1802. break;
  1803. case 4:
  1804. order.PT3 = lstPT[count - 2];
  1805. order.PT4 = lstPT[count - 1];
  1806. AddTextEvent("PT值", $"PT3:{order.PT3},PT4:{order.PT4}");
  1807. break;
  1808. case 6:
  1809. order.PT5 = lstPT[count - 2];
  1810. order.PT6 = lstPT[count - 1];
  1811. AddTextEvent("PT值", $"PT5:{order.PT5},PT6:{order.PT6}");
  1812. break;
  1813. }
  1814. List<double> lstValidValue = new List<double>();
  1815. for (int i = 0; i < count; i++)
  1816. {
  1817. if (lstPT[i] > 0)
  1818. lstValidValue.Add(lstPT[i]);
  1819. }
  1820. double value = Math.Round(lstValidValue.Average(), 4);
  1821. double valueMax = lstValidValue.Max();
  1822. double valueMin = lstValidValue.Min();
  1823. if (order != null) order.PTValue = value;
  1824. Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White;
  1825. Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White;
  1826. Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White;
  1827. this.Invoke(new System.Action(() =>
  1828. {
  1829. this.lblPT.Text = value.ToString();
  1830. this.lblPT.ForeColor = color;
  1831. this.lblPTMax.Text = Math.Round(valueMax, 4).ToString();
  1832. this.lblPTMax.ForeColor = colorMax;
  1833. this.lblPTMin.Text = Math.Round(valueMin, 4).ToString();
  1834. this.lblPTMin.ForeColor = colorMin;
  1835. }));
  1836. //不合格
  1837. if (color == Color.Red) order.Qualified = false;
  1838. }
  1839. private void updatePTValueTest(double upperLimit, double lowerLimit)
  1840. {
  1841. //每次加2个:PT1,PT2
  1842. int count = lstPT.Count();
  1843. if (count < 1) return;
  1844. switch (count)
  1845. {
  1846. case 1:
  1847. order.PT1 = lstPT[count - 1];
  1848. AddTextEvent("PT1", $"PT1:{order.PT1}");
  1849. break;
  1850. case 2:
  1851. order.PT2 = lstPT[count - 1];
  1852. AddTextEvent("PT2", $"PT2:{order.PT2}");
  1853. break;
  1854. case 3:
  1855. order.PT3 = lstPT[count - 1];
  1856. order.PT4 = 0;
  1857. AddTextEvent("PT3", $"PT3:{order.PT3}");
  1858. break;
  1859. case 4:
  1860. order.PT5 = lstPT[count - 1];
  1861. AddTextEvent("PT4", $"PT4:{order.PT5}");
  1862. break;
  1863. case 5:
  1864. order.PT6 = lstPT[count - 1];
  1865. AddTextEvent("PT5", $"PT5:{order.PT6}");
  1866. break;
  1867. }
  1868. List<double> lstValidValue = new List<double>();
  1869. for (int i = 0; i < count; i++)
  1870. {
  1871. if (lstPT[i] > 0)
  1872. lstValidValue.Add(lstPT[i]);
  1873. }
  1874. double value = Math.Round(lstValidValue.Average(), 4);
  1875. double valueMax = lstValidValue.Max();
  1876. double valueMin = lstValidValue.Min();
  1877. if (order != null) order.PTValue = value;
  1878. Color color = (upperLimit + lowerLimit > 0 && (value > upperLimit || value < lowerLimit)) ? Color.Red : Color.White;
  1879. Color colorMax = (upperLimit + lowerLimit > 0 && (valueMax > upperLimit || valueMax < lowerLimit)) ? Color.Red : Color.White;
  1880. Color colorMin = (upperLimit + lowerLimit > 0 && (valueMin > upperLimit || valueMin < lowerLimit)) ? Color.Red : Color.White;
  1881. this.Invoke(new System.Action(() =>
  1882. {
  1883. this.lblPT.Text = value.ToString();
  1884. this.lblPT.ForeColor = color;
  1885. this.lblPTMax.Text = Math.Round(valueMax, 4).ToString();
  1886. this.lblPTMax.ForeColor = colorMax;
  1887. this.lblPTMin.Text = Math.Round(valueMin, 4).ToString();
  1888. this.lblPTMin.ForeColor = colorMin;
  1889. }));
  1890. //不合格
  1891. if (color == Color.Red) order.Qualified = false;
  1892. }
  1893. private void updateCompareResult(bool compareResult)
  1894. {
  1895. this.Invoke(new System.Action(() =>
  1896. {
  1897. this.lblCompareResult.Text = (order.CompareResult==1 ? "通过" : "未通过");
  1898. if (!compareResult)
  1899. {
  1900. this.lblCompareResultCount.Text = (Convert.ToInt16(lblCompareResultCount.Text) + 1).ToString();
  1901. this.lblCompareResult.ForeColor = lblCompareResultCount.ForeColor=Color.Red;
  1902. //不合格
  1903. order.Qualified = false;
  1904. }
  1905. }));
  1906. }
  1907. private void resetUIValue()
  1908. {
  1909. this.Invoke(new System.Action(() =>
  1910. {
  1911. //保持产品名称和料号
  1912. //txtProductName.Text = txtProductCode.Text = txtProductSN.Text = "";
  1913. txtProductSN.Text = "";
  1914. lstHeight.Clear();
  1915. lstLineWidth.Clear();
  1916. lstTension.Clear();
  1917. lstPT.Clear();
  1918. this.lblTension.Text = this.lblHeight.Text = this.lblLineWidth.Text = "0.00";
  1919. this.lblPT.Text = this.lblPTMax.Text= this.lblPTMin.Text="0.0000";
  1920. this.lblCompareResult.Text =this.lblDefectResult.Text = "无";
  1921. this.lblTensionMax.Text = this.lblHeightMax.Text = this.lblLineWidthMax.Text
  1922. = this.lblTensionMin.Text = this.lblHeightMin.Text = this.lblLineWidthMin.Text = "0.00";
  1923. this.lblCompareResultCount.Text = "0";
  1924. this.lblDefectResultCount.Text = "无";
  1925. this.toolTip1.SetToolTip(lblDefectResultCount, lblDefectResultCount.Text);
  1926. //
  1927. this.lblTension.ForeColor = this.lblHeight.ForeColor = this.lblLineWidth.ForeColor = this.lblPT.ForeColor = this.lblCompareResult.ForeColor= this.lblDefectResult.ForeColor=Color.White;
  1928. this.lblTensionMax.ForeColor = this.lblHeightMax.ForeColor = this.lblLineWidthMax.ForeColor = this.lblPTMax.ForeColor
  1929. = this.lblTensionMin.ForeColor = this.lblHeightMin.ForeColor = this.lblLineWidthMin.ForeColor = this.lblPTMin.ForeColor = Color.White;
  1930. this.lblCompareResultCount.ForeColor = this.lblDefectResultCount.ForeColor=Color.White;
  1931. this.dgvProcess.DataSource = null;
  1932. this.lstLog.Items.Clear();
  1933. this.clearDefectBmps();
  1934. this.picScanner1.Image = this.picScanner2.Image = null;
  1935. picScanner1.Refresh();
  1936. picScanner2.Refresh();
  1937. this.btnMakeTags.Enabled = false;
  1938. }));
  1939. }
  1940. //info: [{"1":[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]},
  1941. private void showDefectSmallBmps(Bitmap[] bmps, Mat[] bmps_cut, double Xmm, double Ymm, List<Dictionary<int, List<string>[]>> info)
  1942. {
  1943. this.Invoke(new System.Action(() =>
  1944. {
  1945. int imgWidth = this.pnlBmpList.ClientSize.Width - 50;
  1946. int imgHeight = (int)((bmps[0].Height * 1.0f / bmps[0].Width) * imgWidth + 0.5);
  1947. int splitWidth = 20;
  1948. int pnlWidth = this.pnlBmpList.ClientSize.Width;
  1949. int index = (int)this.gboxDefectList.Tag;
  1950. for (int x = 0; x < info.Count(); x++)
  1951. {
  1952. foreach (var item in info[x]) //单个info[x] = {"1":[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]}
  1953. {
  1954. //统计缺陷类型
  1955. countDefectClass(item.Value);//[["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]
  1956. //
  1957. PictureBox picbox = new PictureBox();
  1958. picbox.Width = imgWidth;
  1959. picbox.Height = imgHeight;
  1960. CheckBox checkBox = new CheckBox();
  1961. picbox.Image = (Bitmap)bmps[x].Clone();
  1962. picbox.Name = "imgDefect_" + index;
  1963. picbox.Tag = item.Key + "," + Xmm + "," + Ymm;
  1964. checkBox.Tag = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(bmps_cut[item.Key]); //Mat转Bitmap ;//原始小图
  1965. checkBox.Name = "chkDefect_" + index;
  1966. checkBox.Text = $"第{index + 1}张";
  1967. checkBox.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged);
  1968. if (Config.MakeTag)//自动打标
  1969. {
  1970. checkBox.Checked = true;
  1971. checkBox.Enabled = false;
  1972. }
  1973. picbox.Click += new EventHandler(defectBmpBox_Click);
  1974. picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
  1975. picbox.BorderStyle = BorderStyle.FixedSingle;
  1976. picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth,0, 0);
  1977. checkBox.Margin = new Padding((pnlWidth - checkBox.Width) / 2 + splitWidth,
  1978. 0, 0, 0);
  1979. //
  1980. //if (this.pnlBmpList.Controls.Count > 0)
  1981. //{
  1982. // if ((this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + imgWidth + splitWidth) > this.pnlBmpList.Width)
  1983. // picbox.Location = new System.Drawing.Point(splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Bottom + splitWidth);
  1984. // else
  1985. // picbox.Location = new System.Drawing.Point(this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Location.Y);
  1986. //}
  1987. //else
  1988. //{
  1989. // picbox.Location = new System.Drawing.Point(splitWidth, 0);
  1990. //}
  1991. //checkBox.Location = new System.Drawing.Point(picbox.Location.X + 5, picbox.Location.Y + 5);
  1992. //checkBox.ForeColor = Color.Black;
  1993. this.pnlBmpList.Controls.Add(picbox);
  1994. this.pnlBmpList.Controls.Add(checkBox);
  1995. break;
  1996. }
  1997. //
  1998. index++;
  1999. };
  2000. this.gboxDefectList.Tag = index;
  2001. this.gboxDefectList.Text = $"缺陷图像:{index} 张";
  2002. if (Config.MakeTag) {
  2003. lblDefectAddTag.Text = $"待打标数:{index}";
  2004. lblDefectAddTag.Tag = index;
  2005. }
  2006. pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum;
  2007. }));
  2008. }
  2009. //统计缺陷类型 [["92.7542","80.85799","99.54083","86.05363","dk","0.52"]]
  2010. private void countDefectClass(List<string>[] list)
  2011. {
  2012. string className;
  2013. for(int i=0; i<list.Length; i++)
  2014. {
  2015. className = list[i][4];
  2016. switch (className)
  2017. {
  2018. case "dk":
  2019. order.DKCount++;
  2020. break;
  2021. case "zw":
  2022. order.ZWCount++;
  2023. break;
  2024. case "gsyc":
  2025. order.GSYCCount++;
  2026. break;
  2027. case "xws":
  2028. order.XWSCount++;
  2029. break;
  2030. case "qk":
  2031. order.QKCount++;
  2032. break;
  2033. case "zk":
  2034. order.ZKCount++;
  2035. break;
  2036. case "pp":
  2037. order.PPCount++;
  2038. break;
  2039. case "hs":
  2040. order.HSCount++;
  2041. break;
  2042. case "yx":
  2043. order.YXCount++;
  2044. break;
  2045. case "xb":
  2046. order.XBCount++;
  2047. break;
  2048. case "sx":
  2049. order.SXCount++;
  2050. break;
  2051. }
  2052. }
  2053. }
  2054. private int getDefectCountFromCode(Order order, DefectCodeEnum defectCodeEnum)
  2055. {
  2056. switch (defectCodeEnum)
  2057. {
  2058. case DefectCodeEnum.dk:
  2059. return order.DKCount;
  2060. case DefectCodeEnum.zw:
  2061. return order.ZWCount;
  2062. case DefectCodeEnum.gsyc:
  2063. return order.GSYCCount;
  2064. case DefectCodeEnum.xws:
  2065. return order.XWSCount;
  2066. case DefectCodeEnum.qk:
  2067. return order.QKCount;
  2068. case DefectCodeEnum.zk:
  2069. return order.ZKCount;
  2070. case DefectCodeEnum.pp:
  2071. return order.PPCount;
  2072. case DefectCodeEnum.hs:
  2073. return order.HSCount;
  2074. case DefectCodeEnum.yx:
  2075. return order.YXCount;
  2076. case DefectCodeEnum.xb:
  2077. return order.XBCount;
  2078. case DefectCodeEnum.sx:
  2079. return order.SXCount;
  2080. default:
  2081. return 0;
  2082. }
  2083. }
  2084. private void CheckBox_CheckedChanged(object sender, EventArgs e)
  2085. {
  2086. CheckBox ck = (CheckBox)sender;
  2087. int cout = Convert.ToInt32(this.lblDefectAddTag.Tag);
  2088. if (ck.Checked)
  2089. cout++;
  2090. else
  2091. cout--;
  2092. lblDefectAddTag.Text = $"待打标数:{cout}";
  2093. lblDefectAddTag.Tag = cout;
  2094. }
  2095. private void defectBmpBox_Click(object sender, EventArgs e)
  2096. {
  2097. // if(autoMakeTagRuning) //自动打标中不可打开人工达标窗
  2098. PictureBox picbox = sender as PictureBox;
  2099. if (!devContainer.state || defectBmpNum != defectBmpNumResult || autoMakeTagRuning || currentState != CurrentStateEnum.自动流程结束)//检测中
  2100. {
  2101. //只查看
  2102. FrmPhoto frm = new FrmPhoto(this.pnlBmpList.Controls, Convert.ToInt32(picbox.Name.Split(new char[] { '_' })[1]));
  2103. frm.ShowDialog(this);
  2104. }
  2105. else//完成
  2106. {
  2107. FrmPhotoTag frm = new FrmPhotoTag(this.pnlBmpList.Controls, Convert.ToInt32(picbox.Name.Split(new char[] { '_' })[1])
  2108. ,(defectBmpNum == defectBmpNumResult ? this.devContainer : null));
  2109. frm.ShowDialog(this);
  2110. //
  2111. if (devContainer.state && !Config.SkipScannerCC)
  2112. {
  2113. devContainer.devScannerCC.setMode(false);
  2114. devContainer.devScannerCC.setPreviewWin(this.picScanner1.Handle);
  2115. }
  2116. }
  2117. }
  2118. private void clearDefectBmps()
  2119. {
  2120. this.pnlBmpList.Controls.Clear();
  2121. this.gboxDefectList.Text = $"缺陷图像";
  2122. this.gboxDefectList.Tag = 0;
  2123. this.lblDefectAddTag.Text = "";
  2124. this.lblDefectAddTag.Tag = 0;
  2125. }
  2126. public delegate void AddTextDelegate(string tag, string msg, WarningEnum level);
  2127. /// <summary>
  2128. /// 异步输出日志
  2129. /// </summary>
  2130. /// <param name="tag">模板标识</param>
  2131. /// <param name="msg">内容</param>
  2132. /// <param name="type"></param>
  2133. private void AddTextEvent(string tag, string msg, WarningEnum level = WarningEnum.Normal)
  2134. {
  2135. try
  2136. {
  2137. if (InvokeRequired)
  2138. {
  2139. Invoke(new AddTextDelegate(AddTextEvent), new object[]
  2140. {
  2141. tag,
  2142. msg,
  2143. level
  2144. });
  2145. }
  2146. else
  2147. {
  2148. if (tag != null && tag != "")
  2149. tag = $" - [{tag}]";
  2150. var now = DateTime.Now;
  2151. msg = now.ToString("HH:mm:ss fff") + tag + " - " + msg;
  2152. //cont = MyHelper.subString(cont, 300);
  2153. //写日志,warn和error日志直接写
  2154. writeLog(now, level, msg);
  2155. //
  2156. //if (type > 0)
  2157. // cont = $"<color=\"{(type == 1 ? "Yellow" : "Red")}\">{cont}</color>";
  2158. msg = (level == WarningEnum.Normal ? "B" : level == WarningEnum.Low ? "Y" : "R") + msg;
  2159. this.Invoke(new System.Action(() =>
  2160. {
  2161. if (this.lstLog.Items.Count > 1000)
  2162. this.lstLog.Items.Clear();
  2163. lstLog.Items.Insert(0, msg);
  2164. }));
  2165. //日志滚动
  2166. //lstLog.SelectedIndex = lstLog.Items.Count - 1;
  2167. }
  2168. }
  2169. catch (Exception ex)
  2170. {
  2171. //MessageBox.Show("AddTextEvent ex=(" + ex.Message + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
  2172. }
  2173. }
  2174. private void lstLog_DrawItem(object sender, DrawItemEventArgs e)
  2175. {
  2176. e.DrawBackground();
  2177. if (e.Index < 0) return;
  2178. try
  2179. {
  2180. string str = lstLog.Items[e.Index].ToString();
  2181. e.Graphics.DrawString(str.Substring(1), e.Font,
  2182. new SolidBrush(str[0] == 'R' ? Color.Red : (str[0] == 'Y' ? Color.Orange : Color.Black)),
  2183. e.Bounds);
  2184. }
  2185. catch
  2186. {
  2187. ;
  2188. }
  2189. }
  2190. private void writeLog(DateTime now, WarningEnum level, string text)
  2191. {
  2192. string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\";
  2193. //if (type == 0) directory = Application.StartupPath + "\\Log\\Info\\";
  2194. //else if (type == 1) directory = Application.StartupPath + "\\Log\\Warn\\";
  2195. //else directory = Application.StartupPath + "\\Log\\Error\\";
  2196. if (!System.IO.Directory.Exists(directory))
  2197. System.IO.Directory.CreateDirectory(directory);
  2198. File.AppendAllText(directory + now.ToString("yyyyMMdd") + ".log", text + "\r\n");
  2199. }
  2200. private void FrmMian_FormClosing(object sender, FormClosingEventArgs e)
  2201. {
  2202. if (devContainer.state)
  2203. {
  2204. MessageBox.Show("请先停止生产后才能关闭程序!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2205. e.Cancel = true;
  2206. return;
  2207. }
  2208. if (!bExitApp && MessageBox.Show($"确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
  2209. {
  2210. e.Cancel = true;
  2211. return;
  2212. }
  2213. }
  2214. private void FrmMian_FormClosed(object sender, FormClosedEventArgs e)
  2215. {
  2216. webService.stop();
  2217. Application.Exit();
  2218. System.GC.Collect();
  2219. System.Environment.Exit(0);
  2220. }
  2221. private void tsbtnOpenDev_Click(object sender, EventArgs e)
  2222. {
  2223. //FrmGetPosByPic frr = new FrmGetPosByPic(new SizeLibProp());
  2224. //frr.ShowDialog();
  2225. Config.LoadAllConfig();
  2226. //设置程序最小/大线程池
  2227. // Get the current settings.
  2228. int minWorker, minIOC;
  2229. ThreadPool.GetMinThreads(out minWorker, out minIOC);
  2230. ThreadPool.SetMinThreads(25, minIOC);
  2231. //ThreadPool.SetMaxThreads(256, 256);
  2232. this.tsbtnProductRevise.Enabled = false;
  2233. this.tsbtnOpenDev.Enabled = false;
  2234. //scannerCBmpIndex = 0;
  2235. isProductRevise = false;
  2236. this.resetUIValue();
  2237. currProcessIndex = -1;
  2238. currentState = CurrentStateEnum.等待复位;
  2239. warningLevel = WarningEnum.Normal;
  2240. currentPT = CurrentPTEnum.InitPT;
  2241. this.tsbtnWarning.Enabled=this.tsbtnGoDownPT.Enabled=this.tsbtnStart.Enabled=this.tsbtnStopNow.Enabled=this.tsbtnPause.Enabled=this.tsbtnReset.Enabled=false;
  2242. //后台线程回调事件
  2243. devContainer.StateChange = (state, msg) =>
  2244. {
  2245. if (state)
  2246. {
  2247. //全局中断
  2248. devContainer.devIOCard.INEvent = globalBreakEvent;
  2249. devContainer.OutDebugEvent = (tag, debugInfo) =>
  2250. {
  2251. AddTextEvent(tag, debugInfo);
  2252. };
  2253. //
  2254. AddTextEvent("设备启动", "请先进行复位操作!");
  2255. this.Invoke(new System.Action(() =>
  2256. {
  2257. this.tsbtnReset.Enabled = true;
  2258. tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled
  2259. = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = false;
  2260. this.tsbtnOpenDev.Enabled = true;
  2261. this.tsbtnOpenDev.Visible = false;
  2262. this.tsbtnCloseDev.Visible = true;
  2263. }));
  2264. timer.Elapsed += Timer_Elapsed;
  2265. timer.Interval = 500;
  2266. timer.Start();
  2267. }
  2268. else
  2269. {
  2270. AddTextEvent("设备启动", $"启动失败,{msg}", WarningEnum.High);
  2271. this.Invoke(new System.Action(() =>
  2272. {
  2273. this.tsbtnOpenDev.Enabled = true;
  2274. this.tsbtnOpenDev.Visible = true;
  2275. this.tsbtnCloseDev.Visible = false;
  2276. }));
  2277. }
  2278. };
  2279. devContainer.WarningEvent = (level, msg) =>
  2280. {
  2281. AddTextEvent("设备事件", msg, level);
  2282. if (level == WarningEnum.High)
  2283. warning(level,true);
  2284. };
  2285. devContainer.start(this.picScanner1.Handle, this.picScanner2.Handle);
  2286. }
  2287. private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  2288. {
  2289. this.Invoke(new System.Action(() =>
  2290. {
  2291. this.tsAxisState.Text = $"[命令位:{devContainer.devAxis.CmdPos[0]} 反馈位:{devContainer.devAxis.ActualPos[0]}] | " +
  2292. $"[命令位:{devContainer.devAxis.CmdPos[1]} 反馈位:{devContainer.devAxis.ActualPos[1]}] | " +
  2293. $"[命令位:{devContainer.devAxis.CmdPos[2]} 反馈位:{devContainer.devAxis.ActualPos[2]}] | " +
  2294. $"[命令位:{devContainer.devAxis.CmdPos[3]} 反馈位:{devContainer.devAxis.ActualPos[3]}]";
  2295. }));
  2296. }
  2297. private void tsbtnCloseDev_Click(object sender, EventArgs e)
  2298. {
  2299. AddTextEvent("设备停止", $"设备停止...");
  2300. this.tsbtnProductRevise.Enabled = false;
  2301. this.tsbtnOpenDev.Visible = true;
  2302. this.tsbtnCloseDev.Visible = false;
  2303. this.btnMakeTags.Enabled = false;
  2304. this.lblTimeLen.Visible = false;
  2305. this.tsbtnReset.Enabled = tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled
  2306. = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = false;
  2307. this.tsbtnSizeTag.Enabled = tsbtnSizeImage.Enabled = tsbtnDefectImage.Enabled = false;
  2308. if (devContainer.state)
  2309. {
  2310. devContainer.devIOCard.reset();
  2311. devContainer.io_output(CMDName.IO默认输出);
  2312. }
  2313. timer.Stop();
  2314. devContainer.stop();
  2315. }
  2316. /// <summary>
  2317. /// 全局中断
  2318. /// </summary>
  2319. private void globalBreakEvent(int portIndex, byte data)
  2320. {
  2321. if (compareIOInput(CMDName.启动按钮) && this.tsbtnStart.Enabled)
  2322. startCommand();
  2323. else if (compareIOInput(CMDName.暂停按钮) && this.tsbtnPause.Enabled)
  2324. warning(WarningEnum.Low, false);
  2325. else if (compareIOInput(CMDName.复位按钮) && this.tsbtnReset.Enabled)
  2326. resetCommand();
  2327. else if (compareIOInput(CMDName.张力读取) && currentPT == CurrentPTEnum.Moving)
  2328. readTension();
  2329. else if (!this.disableBuzzer && compareIOInput(CMDName.门磁告警输入))
  2330. warning(WarningEnum.Low, true);
  2331. else if (!this.disableBuzzer && compareIOInput(CMDName.喷墨告警输入))
  2332. warning(WarningEnum.Low, true);
  2333. }
  2334. private bool compareIOInput(CMDName key)
  2335. {
  2336. JObject joJson = Config.CMDProcess[key];
  2337. IODirectionEnum direction = (IODirectionEnum)joJson.Value<int>("Direction");
  2338. if (direction == IODirectionEnum.输入 || direction == IODirectionEnum.输入输出)
  2339. {
  2340. return Util.compareIOInput(
  2341. joJson.Value<JArray>("IN_OP_SHOW").ToObject<List<string>>().ToArray(),
  2342. devContainer.devIOCard.DIData);
  2343. }
  2344. return false;
  2345. }
  2346. private void readTension()
  2347. {
  2348. if (Config.SkipTension)
  2349. {
  2350. AddTextEvent("张力读取", $"张力设备禁用,忽略此步骤!");
  2351. return;
  2352. }
  2353. devContainer.io_output(CMDName.张力读取);
  2354. double tensionValue = devContainer.devTension.getValue() + Config.Tension_Offset;//加入张力偏差
  2355. tensionValue=Math.Round(tensionValue, 2);//保留2位小数
  2356. AddTextEvent("张力读取", $"张力值:{tensionValue}");
  2357. devContainer.io_output(CMDName.张力读取,false,true,500);
  2358. lstTension.Add(tensionValue);
  2359. updateTensionValue(currProductModel.TensionBaseValue + currProductModel.TensionUpFloatValue, currProductModel.TensionBaseValue - currProductModel.TensionDownFloatValue);
  2360. }
  2361. /// <summary>
  2362. /// 启动
  2363. /// </summary>
  2364. private void startCommand()
  2365. {
  2366. this.setButtonEnabled(this.tsbtnProductRevise, false);
  2367. //2023-10-23 运行前清除过期图片文件
  2368. Config.DelectPictureFile();
  2369. if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.等待启动)
  2370. return;
  2371. if (currentPT == CurrentPTEnum.MakeTag)
  2372. {
  2373. AddTextEvent("启动", "打标未结束,非可启动状态!", warningLevel);
  2374. return;
  2375. }
  2376. if (!devContainer.devAxis.isReady())
  2377. {
  2378. AddTextEvent("启动", "轴状态异常,不可启动!", warningLevel);
  2379. return;
  2380. }
  2381. if (!devContainer.devAxis.IsReset)
  2382. {
  2383. AddTextEvent("启动", "轴需先进行复位操作!", WarningEnum.High);
  2384. return;
  2385. }
  2386. devContainer.io_output(CMDName.启动按钮);
  2387. devContainer.io_output(CMDName.绿灯输出);
  2388. devContainer.io_output(CMDName.暂停按钮, false, true, 0);
  2389. devContainer.io_output(CMDName.红灯输出, false, true, 0);
  2390. devContainer.io_output(CMDName.黄灯输出, false, true, 0);
  2391. //暂停-》继续
  2392. if (currProcessIndex >= 0 && currentPT == CurrentPTEnum.Moving && currentState == CurrentStateEnum.等待启动)
  2393. {
  2394. AddTextEvent("启动", $"暂停 -> 继续 当前工序索引:{currProcessIndex + 1}");
  2395. threadProcess = new System.Threading.Thread(() =>
  2396. {
  2397. int nextStepId = currProcessIndex;
  2398. do
  2399. {
  2400. currentState = CurrentStateEnum.运行中;
  2401. nextStepId = nextProcess(currProductModel, nextStepId);
  2402. } while (nextStepId >= 0 && !isBreakProcessRun());
  2403. //nextProcess(currProductModel, currProcessIndex);
  2404. });
  2405. threadProcess.IsBackground = true;
  2406. threadProcess.Start();
  2407. this.setButtonEnabled(this.tsbtnPause, true);
  2408. this.setButtonEnabled(this.tsbtnStopNow, true);
  2409. }
  2410. else//开始/重新开始
  2411. {
  2412. //校正从复位-》运行,不会新启动
  2413. isProductRevise = false;
  2414. resetUIValue();
  2415. AddTextEvent("启动", "移动至上料位...");
  2416. gotoUpPT();
  2417. this.Invoke(new System.Action(() =>
  2418. {
  2419. //新开始
  2420. lblTimeLen.Visible = false;
  2421. runStep();
  2422. }));
  2423. this.setButtonEnabled(this.tsbtnPause, false);
  2424. this.setButtonEnabled(this.tsbtnStopNow, false);
  2425. }
  2426. this.setButtonEnabled(this.tsbtnStart, false);
  2427. this.setButtonEnabled(this.tsbtnReset, false);
  2428. this.setButtonEnabled(this.tsbtnGoDownPT, false);
  2429. }
  2430. /// <summary>
  2431. /// 暂停
  2432. /// </summary>
  2433. /// <param name="buzzer">是否响蜂鸣</param>
  2434. private void pauseCommand(bool buzzer = false)
  2435. {
  2436. devContainer.io_output(CMDName.暂停按钮);
  2437. if (buzzer)
  2438. {
  2439. devContainer.io_output(CMDName.红灯输出);
  2440. devContainer.io_output(CMDName.蜂鸣器输出);
  2441. }
  2442. else
  2443. devContainer.io_output(CMDName.黄灯输出);
  2444. devContainer.io_output(CMDName.启动按钮, false, true, 0);
  2445. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  2446. this.setButtonEnabled(this.tsbtnWarning, true);
  2447. this.setButtonEnabled(this.tsbtnGoDownPT, false);
  2448. this.setButtonEnabled(this.tsbtnStart, false);
  2449. this.setButtonEnabled(this.tsbtnPause, false);
  2450. this.setButtonEnabled(this.tsbtnStopNow, false);
  2451. this.setButtonEnabled(this.tsbtnReset, false);
  2452. AddTextEvent("暂停", $"当前工序索引:{currProcessIndex + 1}", WarningEnum.Low);
  2453. }
  2454. /// <summary>
  2455. /// 急停
  2456. /// </summary>
  2457. private void stopNowCommand()
  2458. {
  2459. if (!devContainer.state)
  2460. {
  2461. this.setButtonEnabled(this.tsbtnStopNow, false);
  2462. return;
  2463. }
  2464. devContainer.io_output(CMDName.Y轴复位输出, false, true, 0);
  2465. devContainer.io_output(CMDName.红灯输出);
  2466. if (!this.disableBuzzer) devContainer.io_output(CMDName.蜂鸣器输出);
  2467. devContainer.io_output(CMDName.暂停按钮, false, true, 0);
  2468. devContainer.io_output(CMDName.黄灯输出, false, true, 0);
  2469. devContainer.io_output(CMDName.启动按钮, false, true, 0);
  2470. devContainer.io_output(CMDName.绿灯输出, false, true, 0);
  2471. this.setButtonEnabled(this.tsbtnWarning, true);
  2472. this.setButtonEnabled(this.tsbtnGoDownPT, false);
  2473. this.setButtonEnabled(this.tsbtnStart, false);
  2474. this.setButtonEnabled(this.tsbtnPause, false);
  2475. this.setButtonEnabled(this.tsbtnStopNow, false);
  2476. this.setButtonEnabled(this.tsbtnReset, false);
  2477. AddTextEvent("急停", $"当前工序索引:{currProcessIndex + 1}", WarningEnum.High);
  2478. }
  2479. private bool reseting = false;
  2480. private void resetCommand()
  2481. {
  2482. currentState = CurrentStateEnum.等待复位;
  2483. warningLevel = WarningEnum.Normal;
  2484. currentPT = CurrentPTEnum.InitPT;
  2485. this.Invoke(new System.Action(() =>
  2486. {
  2487. lblTimeLen.Visible = false;
  2488. this.tsbtnWarning.Enabled = this.tsbtnGoDownPT.Enabled = this.tsbtnStart.Enabled = this.tsbtnStopNow.Enabled = this.tsbtnPause.Enabled = this.tsbtnReset.Enabled = false;
  2489. }));
  2490. try
  2491. {
  2492. if (devContainer.state && !reseting)
  2493. {
  2494. reseting = true;
  2495. isProductRevise = false;
  2496. resetUIValue();
  2497. AddTextEvent("复位", $"设备复位中...");
  2498. currProcessIndex = -1;
  2499. this.setButtonEnabled(this.tsbtnReset, false);
  2500. // I/O reset后,输出默认状态
  2501. AddTextEvent("复位", $"I/O复位中...");
  2502. if (!devContainer.devIOCard.reset())
  2503. {
  2504. AddTextEvent("复位", "I/O板卡复位失败!", WarningEnum.High);
  2505. return;
  2506. }
  2507. if (!devContainer.io_output(CMDName.IO默认输出))
  2508. {
  2509. //AddTextEvent("复位", "I/O板卡复位默认值失败!", WarningEnum.High);
  2510. //return;
  2511. }
  2512. //板卡复位输出灯
  2513. devContainer.io_output(CMDName.复位按钮);
  2514. devContainer.io_output(CMDName.黄灯输出, true);
  2515. //4.5X
  2516. if(!Config.SkipSmallAxis)
  2517. devContainer.devSmallAxis.gotoPos((int)SmallAxCmdPos.倍率4_5X, false);
  2518. //移动Axis前等待厚度传感器收回
  2519. AddTextEvent("复位", $"检测厚度传感器安全值...");
  2520. if (!Config.SkipHeight)
  2521. {
  2522. while (devContainer.devHeight.getHeight() < (double)Math.Abs(Config.HeightDev_SafeValue))
  2523. {
  2524. if (!devContainer.state || currentState != CurrentStateEnum.等待复位)
  2525. return;
  2526. Thread.Sleep(100);
  2527. Application.DoEvents();
  2528. }
  2529. }
  2530. //goto ORG
  2531. AddTextEvent("复位", $"轴正在回原点...");
  2532. devContainer.devAxis.closeJogMode();
  2533. devContainer.devAxis.resetAxisState(-1);//reset state
  2534. //AddTextEvent("复位", $"重置轴状态...");
  2535. for (int i = 0; i < Config.Axis_HomeMode.Length; i++)
  2536. {
  2537. //到起始位速度使用回HOME速度
  2538. devContainer.devAxis.setAxisVelParam((double)Config.Axis_HomeVelLow[i], (double)Config.Axis_HomeVelHigh[i],
  2539. (double)Config.Axis_HomeAcc[i], (double)Config.Axis_HomeDec[i], i);
  2540. if (i != 2)
  2541. {
  2542. //devContainer.devAxis.setAxisVelParam(40000,200000,5000000, 5000000,i,true);
  2543. devContainer.devAxis.home(i, (uint)Config.Axis_HomeMode[i], (uint)Config.Axis_HomeDir[i]);
  2544. }
  2545. else//Y轴 I/O控制回HOME
  2546. {
  2547. devContainer.io_output(CMDName.Y轴复位输出);
  2548. }
  2549. }
  2550. AddTextEvent("复位", $"等待轴状态完成...");
  2551. while (!devContainer.devAxis.isReady())
  2552. {
  2553. if (!devContainer.state || currentState != CurrentStateEnum.等待复位)
  2554. {
  2555. AddTextEvent("复位", $"当前状态:"+ ((CurrentStateEnum)currentState).ToString());
  2556. return;
  2557. }
  2558. //AddTextEvent("复位", $"轴0状态:"+ ((AxisState)devContainer.devAxis.AxState[0]).ToString());
  2559. //AddTextEvent("复位", $"轴1状态:" + ((AxisState)devContainer.devAxis.AxState[1]).ToString());
  2560. //AddTextEvent("复位", $"轴2状态:" + ((AxisState)devContainer.devAxis.AxState[2]).ToString());
  2561. //AddTextEvent("复位", $"轴3状态:" + ((AxisState)devContainer.devAxis.AxState[3]).ToString());
  2562. Thread.Sleep(1000);
  2563. Application.DoEvents();
  2564. }
  2565. //判断Y轴回原点完成I/O信号
  2566. AddTextEvent("复位", $"等待Y轴回HOME完成...");
  2567. while (!this.compareIOInput(CMDName.Y轴复位完成输入))
  2568. {
  2569. Thread.Sleep(100);
  2570. Application.DoEvents();
  2571. }
  2572. AddTextEvent("复位", $"Y轴回HOME已完成.");
  2573. devContainer.io_output(CMDName.Y轴复位输出, false, true, 0);
  2574. AddTextEvent("复位", $"重置Y轴反馈位置与命令位置.");
  2575. devContainer.devAxis.resetCmdPosition(2);
  2576. devContainer.devAxis.resetActualPosition(2);
  2577. //
  2578. if (devContainer.devAxis.isError())
  2579. throw new Exception("轴回原点失败!");
  2580. //
  2581. //goto InitPT
  2582. //AddTextEvent("复位", $"轴回原点完成,回到初始位...");
  2583. JArray arrPT = Config.joPTSetting.Value<JArray>("initPT");
  2584. for (int i = 0; i < arrPT.Count; i++)
  2585. {
  2586. if (!devContainer.state || currentState != CurrentStateEnum.等待复位)
  2587. return;
  2588. AddTextEvent($"复位", $"轴{i}准备运动至初始位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})...");
  2589. devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置);
  2590. }
  2591. while (!devContainer.devAxis.isReady())
  2592. {
  2593. if (!devContainer.state || warningLevel != WarningEnum.Normal)
  2594. return;
  2595. Thread.Sleep(100);
  2596. }
  2597. if (devContainer.devAxis.isError())
  2598. throw new Exception("轴移动至初始位失败!");
  2599. //
  2600. this.setButtonEnabled(this.tsbtnReset, true);
  2601. this.setButtonEnabled(this.tsbtnStart, true);
  2602. this.setButtonEnabled(this.tsbtnStopNow, true);
  2603. this.setButtonEnabled(this.tsbtnPause, false);
  2604. this.setButtonEnabled(this.tsbtnGoDownPT, false);
  2605. this.setButtonEnabled(this.tsbtnWarning, false);
  2606. devContainer.io_output(CMDName.复位按钮, false, true, 0);//熄灭
  2607. devContainer.io_output(CMDName.黄灯输出);//长亮
  2608. currentPT = CurrentPTEnum.InitPT;
  2609. currentState = CurrentStateEnum.等待启动;
  2610. AddTextEvent("复位", $"复位完成。");
  2611. this.setButtonEnabled(this.tsbtnProductRevise, true);
  2612. }
  2613. else
  2614. {
  2615. AddTextEvent("复位", "非可复位状态,请先停止后再复位!", WarningEnum.High);
  2616. }
  2617. }
  2618. catch (Exception ex)
  2619. {
  2620. AddTextEvent("复位", "复位失败 Err:" + ex.Message, WarningEnum.High);
  2621. warning(WarningEnum.High, true);
  2622. }
  2623. finally
  2624. {
  2625. reseting = false;
  2626. }
  2627. }
  2628. /// <summary>
  2629. /// 上料
  2630. /// </summary>
  2631. private void gotoUpPT()
  2632. {
  2633. try
  2634. {
  2635. JArray arrPT = Config.joPTSetting.Value<JArray>("upPT");
  2636. for (int i = 0; i < arrPT.Count; i++)
  2637. {
  2638. if (!devContainer.state || warningLevel != WarningEnum.Normal)
  2639. return;
  2640. AddTextEvent($"上料", $"轴{i}准备运动至上料位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})...");
  2641. devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置);
  2642. }
  2643. while (!devContainer.devAxis.isReady())
  2644. {
  2645. if (!devContainer.state || warningLevel != WarningEnum.Normal)
  2646. return;
  2647. Thread.Sleep(100);
  2648. }
  2649. if (devContainer.devAxis.isError())
  2650. throw new Exception("轴移动至上料位失败!");
  2651. //
  2652. currentPT = CurrentPTEnum.UpPT;
  2653. currentState = CurrentStateEnum.等待扫码;
  2654. AddTextEvent($"上料", "到达上料位!");
  2655. }
  2656. catch (Exception ex)
  2657. {
  2658. AddTextEvent("上料", "上料初始失败 Err:" + ex.Message, WarningEnum.High);
  2659. warning(WarningEnum.High);
  2660. }
  2661. }
  2662. /// <summary>
  2663. /// 下料
  2664. /// </summary>
  2665. private void gotoDownPT()
  2666. {
  2667. try
  2668. {
  2669. if (currentState != CurrentStateEnum.打标中 && currentState != CurrentStateEnum.等待启动 && currentState != CurrentStateEnum.自动流程结束)
  2670. {
  2671. AddTextEvent($"下料", $"非可下料状态:{currentState.ToString()}");
  2672. return;
  2673. }
  2674. currentState = CurrentStateEnum.下料中;
  2675. isProductRevise = false;
  2676. JArray arrPT = Config.joPTSetting.Value<JArray>("downPT");
  2677. for (int i = 0; i < arrPT.Count; i++)
  2678. {
  2679. if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.下料中)
  2680. return;
  2681. AddTextEvent($"下料", $"轴{i}准备运动至下料位:{(double)arrPT[i]}(当前轴状态:{((AxisState)devContainer.devAxis.AxState[i]).ToString()})...");
  2682. devContainer.devAxis.move_ptp(i, (double)arrPT[i], AxMoveMode.绝对位置);
  2683. }
  2684. while (!devContainer.devAxis.isReady())
  2685. {
  2686. if (!devContainer.state || warningLevel != WarningEnum.Normal || currentState != CurrentStateEnum.下料中)
  2687. return;
  2688. Thread.Sleep(100);
  2689. }
  2690. if (devContainer.devAxis.isError())
  2691. throw new Exception("轴移动至下料位失败!");
  2692. //
  2693. currentPT = CurrentPTEnum.DownPT;
  2694. currentState = CurrentStateEnum.等待启动;
  2695. devContainer.io_output(CMDName.下料完成输出);
  2696. setButtonEnabled(tsbtnStart, true);
  2697. AddTextEvent($"下料", "下料完成!");
  2698. }
  2699. catch (Exception ex)
  2700. {
  2701. AddTextEvent("下料", "下料失败 Err:" + ex.Message, WarningEnum.High);
  2702. warning(WarningEnum.High);
  2703. }
  2704. }
  2705. private void setButtonEnabled(ToolStripButton button, bool Enabled)
  2706. {
  2707. this.Invoke(new System.Action(() =>
  2708. {
  2709. button.Enabled = Enabled;
  2710. }));
  2711. }
  2712. private void setButtonEnabled(ToolStripMenuItem button, bool Enabled)
  2713. {
  2714. this.Invoke(new System.Action(() =>
  2715. {
  2716. button.Enabled = Enabled;
  2717. }));
  2718. }
  2719. private void setButtonEnabled(Control button, bool Enabled)
  2720. {
  2721. this.Invoke(new System.Action(() =>
  2722. {
  2723. button.Enabled = Enabled;
  2724. }));
  2725. }
  2726. private void FrmMian_Shown(object sender, EventArgs e)
  2727. {
  2728. }
  2729. private void FrmMian_Resize(object sender, EventArgs e)
  2730. {
  2731. }
  2732. private void 流程管理ToolStripMenuItem_Click(object sender, EventArgs e)
  2733. {
  2734. if (devContainer.state)
  2735. {
  2736. MessageBox.Show("请先停止生产,再进行流程修改!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2737. return;
  2738. }
  2739. FrmStepList frm = new FrmStepList();
  2740. frm.ShowDialog();
  2741. }
  2742. private void 产品管理ToolStripMenuItem_Click(object sender, EventArgs e)
  2743. {
  2744. if (devContainer.state)
  2745. {
  2746. MessageBox.Show("请先停止生产,再进行产品修改!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2747. return;
  2748. }
  2749. FrmProductList frm = new FrmProductList();
  2750. frm.ShowDialog();
  2751. loadProductCodeList();
  2752. }
  2753. private void tsbtnProductRevise_Click(object sender, EventArgs e)
  2754. {
  2755. if (!devContainer.state)
  2756. {
  2757. MessageBox.Show("请先启动设备!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  2758. return;
  2759. }
  2760. if (currentPT != CurrentPTEnum.InitPT || currentState != CurrentStateEnum.等待启动)
  2761. {
  2762. MessageBox.Show("请先复位设备!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  2763. return;
  2764. }
  2765. FrmProductList frm = new FrmProductList(true);
  2766. if (frm.ShowDialog() == DialogResult.Yes && frm.Product != null)//执行校正
  2767. {
  2768. AddTextEvent("校正", "开始执行产品base厚度校正...");
  2769. isProductRevise = true;
  2770. currProductModel = frm.Product;
  2771. currProductModel.HeightBaseDec = "";
  2772. this.txtProductCode.Text = currProductModel.Code;
  2773. this.txtProductName.Text = currProductModel.Name;
  2774. this.txtProductSN.Text = "";
  2775. this.dgvProcess.DataSource = new BindingSource(currProductModel.ReviseStepInfo.ProcessList, null);
  2776. devContainer.libFor.clear();
  2777. devContainer.libIF.clear();
  2778. //
  2779. this.setButtonEnabled(this.tsbtnStart, false);
  2780. this.setButtonEnabled(this.tsbtnPause, true);
  2781. this.setButtonEnabled(this.tsbtnStopNow, true);
  2782. threadProcess = new System.Threading.Thread(() =>
  2783. {
  2784. int nextStepId = 0;
  2785. do
  2786. {
  2787. currentState = CurrentStateEnum.运行中;
  2788. nextStepId = nextProcess(currProductModel, nextStepId);
  2789. } while (nextStepId >= 0 && !isBreakProcessRun());
  2790. });
  2791. threadProcess.IsBackground = true;
  2792. threadProcess.Start();
  2793. }
  2794. }
  2795. private void 设备调试ToolStripMenuItem_Click(object sender, EventArgs e)
  2796. {
  2797. if (devContainer.state)
  2798. {
  2799. MessageBox.Show("请先停止生产,再进行设备调试!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2800. return;
  2801. }
  2802. FrmDebug3 frm = new FrmDebug3();
  2803. frm.ShowDialog();
  2804. }
  2805. private void 角色管理ToolStripMenuItem_Click(object sender, EventArgs e)
  2806. {
  2807. FrmRoleRight frm = new FrmRoleRight();
  2808. frm.ShowDialog(this);
  2809. }
  2810. private void 用户管理ToolStripMenuItem_Click(object sender, EventArgs e)
  2811. {
  2812. FrmUserList frm = new FrmUserList();
  2813. frm.ShowDialog(this);
  2814. }
  2815. private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
  2816. {
  2817. Application.Exit();
  2818. System.GC.Collect();
  2819. System.Environment.Exit(0);
  2820. }
  2821. private void 注销ToolStripMenuItem_Click(object sender, EventArgs e)
  2822. {
  2823. if (devContainer.state)
  2824. {
  2825. MessageBox.Show("请先停止生产再退出!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2826. return;
  2827. }
  2828. if (MessageBox.Show($"确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
  2829. {
  2830. this.bExitApp = true;
  2831. Process.Start(Application.StartupPath + "\\ProductionControl.exe");
  2832. this.Close();
  2833. }
  2834. }
  2835. private void splitContainer1_Panel1_Resize(object sender, EventArgs e)
  2836. {
  2837. int allWidth = this.splitContainer1.Panel1.Width;
  2838. this.gpbProductInfo.Width = this.flpnlResultData.Width = this.gpbProcessList.Width = this.gpbLog.Width = allWidth;
  2839. //
  2840. this.txtProductName.Width = this.txtProductCode.Width = this.gpbProductInfo.Width - this.txtProductName.Left - 8;
  2841. this.txtProductSN.Width = this.txtBatchId.Width = (this.txtProductName.Width- lblBatchId.Width)/2;
  2842. this.lblBatchId.Left = this.txtProductSN.Right ;
  2843. this.txtBatchId.Left = this.lblBatchId.Right;
  2844. //
  2845. int spliceWidth = 5;
  2846. kanban1.Width = kanban2.Width = kanban3.Width = kanban4.Width = kanban5.Width = kanban6.Width = (flpnlResultData.Width-20) / 6;
  2847. //2023-10-17 更新log和步骤列表显示
  2848. this.gpbProcessList.Height = this.splitContainer1.Panel1.Height - this.gpbProcessList.Top - this.gpbLog.Height;
  2849. this.gpbLog.Top = this.splitContainer1.Panel1.Height - this.gpbLog.Height;
  2850. }
  2851. private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
  2852. {
  2853. AboutBox1 aboutBox1 = new AboutBox1();
  2854. aboutBox1.Show();
  2855. }
  2856. private void 系统设置ToolStripMenuItem_Click(object sender, EventArgs e)
  2857. {
  2858. FrmSysSetting frmSetting = new FrmSysSetting();
  2859. frmSetting.ShowDialog();
  2860. }
  2861. private void dgvProcess_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
  2862. {
  2863. //string processCode;
  2864. //for (int i = 0; i < this.dgvProcess.Rows.Count; i++)
  2865. //{
  2866. //processCode = dgvProcess.Rows[i].Cells[0].Value.ToString();
  2867. //dgvProcess.Rows[i].Cells[1].Value = Config.dicDevType[processCode];
  2868. //}
  2869. }
  2870. private void tsbtnWarning_Click(object sender, EventArgs e)
  2871. {
  2872. //if (warningLevel == WarningEnum.Normal)
  2873. //{
  2874. // tsbtnWarning.Enabled = false;
  2875. // return;
  2876. //}
  2877. //重置AXIS状态
  2878. devContainer.devAxis.resetAxisState();
  2879. if (!devContainer.devAxis.isReady())
  2880. {
  2881. AddTextEvent("解除报警", "轴状态未恢复,解除报警失败!", warningLevel);
  2882. return;
  2883. }
  2884. if (devContainer.devAxis.isError())
  2885. {
  2886. AddTextEvent("解除报警", "轴IO状态异常,解除报警失败!", warningLevel);
  2887. return;
  2888. }
  2889. if (!this.disableDoorSensor && compareIOInput(CMDName.门磁告警输入))
  2890. {
  2891. AddTextEvent("解除报警", "门磁告警未清除 ,解除报警失败!", warningLevel);
  2892. return;
  2893. }
  2894. if (!this.disableDoorSensor && compareIOInput(CMDName.喷墨告警输入))
  2895. {
  2896. AddTextEvent("解除报警", "喷墨告警输入未清除 ,解除报警失败!", warningLevel);
  2897. return;
  2898. }
  2899. //关闭蜂鸣器
  2900. devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0);
  2901. devContainer.io_output(CMDName.红灯输出, false, true, 0);
  2902. devContainer.io_output(CMDName.复位按钮, false, true, 0);
  2903. if (warningLevel == WarningEnum.High)
  2904. {
  2905. AddTextEvent("解除报警", "急停告警已解除,但必需进行复位操作!", warningLevel);
  2906. currentState = CurrentStateEnum.等待复位;
  2907. this.tsbtnReset.Enabled = true;
  2908. tsbtnWarning.Enabled = this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled
  2909. = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = this.btnMakeTags.Enabled= false;
  2910. }
  2911. else
  2912. {
  2913. devContainer.io_output(CMDName.黄灯输出);
  2914. AddTextEvent("解除报警", "告警已解除,请继续选择下一步操作!", warningLevel);
  2915. if (currentPT == CurrentPTEnum.MakeTag)
  2916. currentState = CurrentStateEnum.打标中;
  2917. else
  2918. currentState = CurrentStateEnum.等待启动;
  2919. tsbtnWarning.Enabled = false;
  2920. this.tsbtnStart.Enabled = this.tsbtnGoDownPT.Enabled = true;
  2921. this.tsbtnReset.Enabled = this.tsbtnPause.Enabled = this.tsbtnStopNow.Enabled = true;
  2922. }
  2923. warningLevel = WarningEnum.Normal;
  2924. }
  2925. private void tsbtnGoDownPT_Click(object sender, EventArgs e)
  2926. {
  2927. if (!devContainer.state || warningLevel!= WarningEnum.Normal)
  2928. return;
  2929. if (!devContainer.devAxis.isReady())
  2930. {
  2931. AddTextEvent("下料失败", "轴状态异常!", WarningEnum.Low);
  2932. return;
  2933. }
  2934. gotoDownPT();
  2935. }
  2936. //急停
  2937. private void tsbtnStopNow_Click(object sender, EventArgs e)
  2938. {
  2939. this.warning(WarningEnum.High);
  2940. }
  2941. private Thread threadProcess;
  2942. private void tsbtnStart_Click(object sender, EventArgs e)
  2943. {
  2944. this.startCommand();
  2945. }
  2946. private void tsbtnPause_Click(object sender, EventArgs e)
  2947. {
  2948. warning(WarningEnum.Low,false);
  2949. }
  2950. //复位
  2951. private void tsbtnReset_Click(object sender, EventArgs e)
  2952. {
  2953. this.resetCommand();
  2954. }
  2955. private void tsbtnGButSetting_Click(object sender, EventArgs e)
  2956. {
  2957. if (devContainer.state)
  2958. {
  2959. MessageBox.Show("请先停止生产,再进行设置!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2960. return;
  2961. }
  2962. FrmCMDProcess from = new FrmCMDProcess();
  2963. from.ShowDialog();
  2964. }
  2965. private void tsbtnPTSetting_Click(object sender, EventArgs e)
  2966. {
  2967. if (devContainer.state)
  2968. {
  2969. MessageBox.Show("请先停止生产,再进行设置!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  2970. return;
  2971. }
  2972. FrmPTSetting from = new FrmPTSetting();
  2973. from.ShowDialog();
  2974. }
  2975. private void tsMenuModifyPW_Click(object sender, EventArgs e)
  2976. {
  2977. FrmModifyPW frm = new FrmModifyPW();
  2978. frm.ShowDialog();
  2979. }
  2980. //分拆面板平均分配
  2981. private void splitContainer1_ClientSizeChanged(object sender, EventArgs e)
  2982. {
  2983. if (this.WindowState == FormWindowState.Minimized)
  2984. return;
  2985. SplitContainer sc = (SplitContainer)sender;
  2986. sc.SplitterDistance = sc.Width / 7*3;
  2987. }
  2988. private void splitContainer3_ClientSizeChanged(object sender, EventArgs e)
  2989. {
  2990. if (this.WindowState == FormWindowState.Minimized)
  2991. return;
  2992. SplitContainer sc = (SplitContainer)sender;
  2993. sc.SplitterDistance = sc.Height / 2;
  2994. }
  2995. private void Menu查询统计_Click(object sender, EventArgs e)
  2996. {
  2997. FrmWeb frm = new FrmWeb("查询统计", $"reportRecordSN?CustomerVer={Config.CustomerVer}");
  2998. frm.Show();
  2999. }
  3000. private void tsMenuOrder_Click(object sender, EventArgs e)
  3001. {
  3002. //FrmOrderList frm = new FrmOrderList();
  3003. string subject = (sender as ToolStripMenuItem).Text;
  3004. FrmWeb frm = new FrmWeb(subject, $"reportRecordSN?CustomerVer={Config.CustomerVer}");
  3005. frm.Show();
  3006. }
  3007. private void tsMenuOrderProduct_Click(object sender, EventArgs e)
  3008. {
  3009. string subject = (sender as ToolStripMenuItem).Text;
  3010. FrmWeb frm = new FrmWeb(subject, $"reportRecordProduct?CustomerVer={Config.CustomerVer}");
  3011. frm.Show();
  3012. }
  3013. private void tsMenuStatistics_Click(object sender, EventArgs e)
  3014. {
  3015. string subject = (sender as ToolStripMenuItem).Text;
  3016. FrmWeb frm = new FrmWeb(subject, $"bigscreen/index.html", "http://127.0.0.1:18082/static/");
  3017. frm.Show();
  3018. }
  3019. private void toolStripButton1_Click(object sender, EventArgs e)
  3020. {
  3021. //Bitmap[] bmps = new Bitmap[2];
  3022. //bmps[0] = new Bitmap(@"f:\1.bmp");
  3023. //bmps[1] = new Bitmap(@"f:\111.bmp");
  3024. //List<Dictionary<int, List<string>[]>> list = new List<Dictionary<int, List<string>[]>>();
  3025. //Dictionary<int, List<string>[]> dir = new Dictionary<int, List<string>[]>();
  3026. //List<string>[] vs = new List<string>[1];
  3027. //vs[0] = new List<string>();
  3028. //dir.Add(0, vs);
  3029. //list.Add(dir);
  3030. //showDefectSmallBmps(bmps, list);
  3031. var bmp = Bitmap.FromFile("f:\\1.jpg");
  3032. int pnlWidth = this.pnlBmpList.ClientSize.Width;
  3033. for (int i = 0; i < 5; i++)
  3034. {
  3035. int x = i;
  3036. this.Invoke(new System.Action(() =>
  3037. {
  3038. int imgWidth = 224;
  3039. int imgHeight = 200;
  3040. int splitWidth = 10;
  3041. int index = Convert.ToInt32(this.gboxDefectList.Tag);
  3042. PictureBox picbox = new PictureBox();
  3043. picbox.Width = imgWidth;
  3044. picbox.Height = imgHeight;
  3045. CheckBox checkBox = new CheckBox();
  3046. picbox.Image = bmp;
  3047. picbox.Name = "imgDefect_" + index;
  3048. picbox.Tag ="1,2,3";
  3049. checkBox.Name = "chkDefect_" + index;
  3050. checkBox.Text = $"第{index + 1}张";
  3051. checkBox.CheckedChanged += new System.EventHandler(this.CheckBox_CheckedChanged);
  3052. picbox.Click += new EventHandler(defectBmpBox_Click);
  3053. picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
  3054. picbox.BorderStyle = BorderStyle.FixedSingle;
  3055. picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth, 0, 0);
  3056. checkBox.Margin = new Padding((pnlWidth - checkBox.Width) / 2+ splitWidth, 0, 0, 0);
  3057. //
  3058. //if (this.pnlBmpList.Controls.Count > 0)
  3059. // {
  3060. // if ((this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + imgWidth + splitWidth) > this.pnlBmpList.Width)
  3061. // picbox.Location = new System.Drawing.Point(splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Bottom + splitWidth);
  3062. // else
  3063. // picbox.Location = new System.Drawing.Point(this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Right + splitWidth, this.pnlBmpList.Controls[this.pnlBmpList.Controls.Count - 1].Location.Y);
  3064. // }
  3065. // else
  3066. // {
  3067. // picbox.Location = new System.Drawing.Point(splitWidth, 0);
  3068. // }
  3069. // checkBox.Location = new System.Drawing.Point(picbox.Location.X + 5, picbox.Location.Y + 5);
  3070. // checkBox.ForeColor = Color.Black;
  3071. //}
  3072. this.pnlBmpList.Controls.Add(picbox);
  3073. this.pnlBmpList.Controls.Add(checkBox);
  3074. //
  3075. index++;
  3076. this.gboxDefectList.Tag = index;
  3077. this.gboxDefectList.Text = $"缺陷图像:{index} 张";
  3078. pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum;
  3079. }));
  3080. }
  3081. }
  3082. private void chkBuzzer_CheckedChanged(object sender, EventArgs e)
  3083. {
  3084. this.disableBuzzer = chkBuzzer.Checked;
  3085. if (devContainer.state && this.disableBuzzer)
  3086. devContainer.io_output(CMDName.蜂鸣器输出, false, true, 0);
  3087. }
  3088. private void chkDoorSensor_CheckedChanged(object sender, EventArgs e)
  3089. {
  3090. this.disableDoorSensor = chkDoorSensor.Checked;
  3091. }
  3092. private void tsbtnLight_Click(object sender, EventArgs e)
  3093. {
  3094. if (devContainer.state)
  3095. {
  3096. if(tsbtnLight.Text.Trim()== "开灯")
  3097. {
  3098. if(devContainer.io_output(CMDName.日光灯输出))
  3099. tsbtnLight.Text = " 关灯 ";
  3100. }
  3101. else
  3102. {
  3103. if (devContainer.io_output(CMDName.日光灯输出, false, true, 0))
  3104. tsbtnLight.Text = " 开灯 ";
  3105. }
  3106. }
  3107. }
  3108. private void btnMakeTag_Click(object sender, EventArgs e)
  3109. {
  3110. if(currentPT != CurrentPTEnum.MakeTag)
  3111. {
  3112. AddTextEvent("打标失败", "非可打标状态!");
  3113. return;
  3114. }
  3115. btnMakeTags.Enabled = false;
  3116. autoMakeTagRuning = true;
  3117. Thread threadtest = new System.Threading.Thread(() =>
  3118. {
  3119. try
  3120. {
  3121. if (!devContainer.state)
  3122. {
  3123. AddTextEvent("打标", "设备已停机!");
  3124. return;
  3125. }
  3126. if ((int)this.lblDefectAddTag.Tag < 1)
  3127. {
  3128. AddTextEvent("打标", "打标队列为空!");
  3129. return;
  3130. }
  3131. int tagIndex;
  3132. double Xmm, Ymm;
  3133. Bitmap currBmp;
  3134. string[] tags;
  3135. for (int i = 0; i < this.pnlBmpList.Controls.Count; i += 2)
  3136. {
  3137. CheckBox cb = this.pnlBmpList.Controls[i + 1] as CheckBox;
  3138. if (cb.Checked)
  3139. {
  3140. PictureBox picBox = this.pnlBmpList.Controls[i] as PictureBox;
  3141. tags = picBox.Tag.ToString().Split(',');
  3142. tagIndex = Convert.ToInt32(tags[0]);
  3143. Xmm = Convert.ToDouble(tags[1]);
  3144. Ymm = Convert.ToDouble(tags[2]);
  3145. currBmp = (Bitmap)picBox.Image;
  3146. //打标
  3147. AddTextEvent("打标", $"第{i / 2 + 1}/{this.pnlBmpList.Controls.Count / 2}张 [索引:{tagIndex}, X:{Xmm}mm, Y:{Ymm}mm]");
  3148. var list = devContainer.libDefect.makeTag(tagIndex, Xmm, Ymm, currBmp.Width, currBmp.Height);
  3149. devContainer.devAxis.move_ptp(1, list[0], AxMoveMode.绝对位置);
  3150. devContainer.devAxis.move_ptp(2, list[1], AxMoveMode.绝对位置);
  3151. while (!devContainer.devAxis.isReady(1) || !devContainer.devAxis.isReady(2))
  3152. {
  3153. Application.DoEvents();
  3154. Thread.Sleep(100);
  3155. if (!devContainer.state)
  3156. throw new Exception("设备停止,打标中止!");
  3157. }
  3158. //
  3159. if (!devContainer.io_output(CMDName.喷墨输出, false, true, 500))
  3160. throw new Exception("请确认[喷墨输出]指令设置是否正确!");
  3161. this.Invoke(new System.Action(() =>
  3162. {
  3163. cb.Checked = false;
  3164. }));
  3165. }
  3166. }
  3167. //自动下料
  3168. AddTextEvent("打标完成", $"批量打标完成,进行下料...");
  3169. currentState = CurrentStateEnum.自动流程结束;
  3170. gotoDownPT();
  3171. }
  3172. catch (Exception ex)
  3173. {
  3174. AddTextEvent("打标失败", ex.Message, WarningEnum.High);
  3175. warning(WarningEnum.Low, true);
  3176. }
  3177. finally { autoMakeTagRuning=false; }
  3178. });
  3179. threadtest.IsBackground = true;
  3180. threadtest.Start();
  3181. }
  3182. private void btnInputCode_Click(object sender, EventArgs e)
  3183. {
  3184. txtProductCode_DoubleClick(null, null);
  3185. }
  3186. private void txtProductName_DoubleClick(object sender, EventArgs e)
  3187. {
  3188. txtProductCode_DoubleClick(null, null);
  3189. }
  3190. private void txtProductCode_DoubleClick(object sender, EventArgs e)
  3191. {
  3192. //不需要等待扫码才能选择
  3193. //if (currentState != CurrentStateEnum.等待扫码) return;
  3194. FrmInput frm = new FrmInput(productCodeList, "请选择产品料号:");
  3195. if (frm.ShowDialog() != DialogResult.OK && string.IsNullOrWhiteSpace(frm.inputData))
  3196. return;
  3197. //显示料号
  3198. //this.txtProductCode.Text = frm.inputData;
  3199. var model = svcProduct.GetModelNav(frm.inputData);
  3200. if (model != null && model.StepInfo.ProcessList.Count > 0)
  3201. {
  3202. this.txtProductCode.Text = model.Code;
  3203. this.txtProductName.Text = model.Name;
  3204. }
  3205. /*//屏蔽扫码枪事件
  3206. Task.Factory.StartNew(() =>
  3207. {
  3208. devContainer.devCodeScanner.ScanerEvent?.Invoke(frm.inputData);
  3209. });
  3210. */
  3211. //string code = Interaction.InputBox("请输入产品编码", "输入框", "", -1, -1).Trim();
  3212. //if(code != "")
  3213. //{
  3214. // Task.Factory.StartNew(() =>
  3215. // {
  3216. // devContainer.devCodeScanner.ScanerEvent?.Invoke(frm.inputData);
  3217. // });
  3218. //}
  3219. }
  3220. private void txtProductSN_DoubleClick(object sender, EventArgs e)
  3221. {
  3222. //if (currentState != CurrentStateEnum.等待扫码 || this.txtProductCode.Text.Trim()=="") return;
  3223. //string sn = Interaction.InputBox("请输入产品SN码", "输入框", "", -1, -1).Trim();
  3224. //if (sn != "")
  3225. //{
  3226. // this.txtProductSN.Text = sn;
  3227. // string code = this.txtProductCode.Text.Trim();
  3228. // Task.Factory.StartNew(() =>
  3229. // {
  3230. // devContainer.devCodeScanner.ScanerEvent?.Invoke(code);
  3231. // });
  3232. //}
  3233. }
  3234. private void 测试ToolStripMenuItem_Click(object sender, EventArgs e)
  3235. {
  3236. tsbtnDefectImage.Enabled = tsbtnSizeImage.Enabled=true;
  3237. return;
  3238. Form1 frm = new Form1();
  3239. frm.Show();
  3240. //tsbtnDefectImage_Click(null, null);
  3241. return;
  3242. try
  3243. {
  3244. //string ls = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,182.257722637742,182.257727282667,0,0";
  3245. //List<string> list = new List<string>(ls.Split(','));
  3246. //lstPT = list.Select<string, double>(q => Convert.ToDouble(q)).ToList();
  3247. //updatePTValue(1,2);
  3248. //lstPT.Add(10);
  3249. //lstPT.Add(0);
  3250. //updatePTValue(1, 2);
  3251. //{
  3252. // lstLineWidth.Add(res.Shanxian > 0 ? res.Shanxian : 0);
  3253. // updateLineWidthValue(model.LineWidthBaseValue + model.LineWidthUpFloatValue, model.LineWidthBaseValue - model.LineWidthDownFloatValue);
  3254. //}
  3255. //return;
  3256. //loadProductCodeList();
  3257. //FrmInput frm = new FrmInput(null, "请选择产品编码:");
  3258. //if (frm.ShowDialog() != DialogResult.OK)
  3259. // return;
  3260. //var model = svcProduct.GetModelNav(frm.inputData);
  3261. //if (model == null)
  3262. // throw new Exception("没有此产品!");
  3263. //order.ProductId = model.Id;
  3264. //order.BatchId = model.BatchId;
  3265. //order.StepId = model.StepId==null? 0:(int)model.StepId;
  3266. //frm = new FrmInput(null, "请输入SN:");
  3267. //if (frm.ShowDialog() != DialogResult.OK)
  3268. // return;
  3269. //order.SN = frm.inputData;
  3270. //frm = new FrmInput(null, "请输入主机台Mark点数据:", "[0,0,0,0,0,0,0,0]");
  3271. //if (frm.ShowDialog() != DialogResult.OK)
  3272. // return;
  3273. //order.MarkData= frm.inputData;
  3274. //order.Tension1 = order.Tension2 = order.Tension3 = order.Tension4 = order.Tension5 = order.Tension5 + 3;
  3275. //order.PT1 = order.PT4 = order.PT5 = order.PT6 = order.PT6 + 1.33;
  3276. //order.LineWidth2 = order.LineWidth3 = order.LineWidth5 = order.LineWidth6 = +order.LineWidth6 + 1.22;
  3277. //order.HeightValue = order.Height1 = order.Height3 = order.Height4 = 55;
  3278. //order.DefectCount = order.DefectCount + 22;
  3279. //order.YXCount = order.PPCount = 33;
  3280. //order.TimeLen = 1000;
  3281. //order.Succeed = true;
  3282. //order.ModifyUserCode = order.CreateUserCode = Config.loginUser.Code;
  3283. //if (!svcOrder.Insert(order))
  3284. // AddTextEvent("保存失败", $"保存生产记录失败!");
  3285. //MessageBox.Show("成功!");
  3286. //---------------
  3287. this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\1.bmp"));
  3288. this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\2.bmp"));
  3289. this.lstCompareFailZoomImage.Add((Bitmap)Bitmap.FromFile(@"f:\3.bmp"));
  3290. }
  3291. catch(Exception ex)
  3292. {
  3293. MessageBox.Show(ex.Message);
  3294. }
  3295. }
  3296. private void toolStripSeparator4_Click(object sender, EventArgs e)
  3297. {
  3298. }
  3299. private void chkHttpLog_CheckedChanged(object sender, EventArgs e)
  3300. {
  3301. if (this.chkHttpLog.Checked)
  3302. {
  3303. webService.LogEvent = (warning, msg) =>
  3304. {
  3305. AddTextEvent("HTTP服务", msg, warning);
  3306. };
  3307. }
  3308. else
  3309. webService.LogEvent = null;
  3310. }
  3311. //打开比对失败的图片
  3312. private void lblCompareResult_Click(object sender, EventArgs e)
  3313. {
  3314. if (lstCompareFailZoomImage.Count < 1) return;
  3315. FrmPhotoShow frm = new FrmPhotoShow(lstCompareFailZoomImage);
  3316. frm.ShowDialog();
  3317. }
  3318. //过程变量查看
  3319. private void tsbtnSizeTag_Click(object sender, EventArgs e)
  3320. {
  3321. if (order == null || order.SizeTagDataList == null || order.SizeTagDataList.Count<1)
  3322. return;
  3323. FrmShowSizeTag frm = new FrmShowSizeTag(order);
  3324. frm.Show();
  3325. }
  3326. //缺陷+比对与图纸查看
  3327. private void tsbtnDefectImage_Click(object sender, EventArgs e)
  3328. {
  3329. //currProductModel = svcProduct.GetModelNav(53);
  3330. //order = svcOrder.GetModelNav("20230814002");
  3331. AddTextEvent("打开窗口", "1");
  3332. if (currProductModel ==null || order == null || order.DefectInfoList == null || order.DefectInfoList.Count < 1)
  3333. return;
  3334. AddTextEvent("打开窗口", "2");
  3335. //图纸
  3336. try
  3337. {
  3338. string gbxBmpPath = "";
  3339. var attachmentFile = currProductModel.AttachmentList.FirstOrDefault(x => x.Type == 0);
  3340. if (attachmentFile != null)
  3341. {
  3342. gbxBmpPath = Application.StartupPath + $"\\Attachment\\product\\{attachmentFile.NameTimestamp}";
  3343. if (!File.Exists(gbxBmpPath + ".bmp")) gbxBmpPath = "";
  3344. }
  3345. AddTextEvent("打开窗口", "3");
  3346. if (string.IsNullOrEmpty(gbxBmpPath))
  3347. {
  3348. MessageBox.Show("图纸文件不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  3349. return;
  3350. }
  3351. AddTextEvent("打开窗口", "4");
  3352. if (!File.Exists(gbxBmpPath + ".jpg"))//转背景后的图纸文件
  3353. {
  3354. AddTextEvent("打开窗口", "5");
  3355. //换背景JPG
  3356. Mat mat = Cv2.ImRead(gbxBmpPath + ".bmp");
  3357. Cv2.CvtColor(mat, mat, ColorConversionCodes.RGB2GRAY);//转灰度图
  3358. for (int i = 0; i < mat.Height; i++)
  3359. {
  3360. for (int j = 0; j < mat.Width; j++)
  3361. {
  3362. if (mat.At<byte>(i, j) == 255)//白色
  3363. mat.Set<byte>(i, j, 0);
  3364. else
  3365. mat.Set<byte>(i, j, 255);
  3366. }
  3367. }
  3368. AddTextEvent("打开窗口", "6");
  3369. //灰转彩
  3370. //Cv2.CvtColor(mat, mat, ColorConversionCodes.GRAY2RGB);
  3371. //for (int i = 0; i < mat.Height; i++)
  3372. //{
  3373. // for (int j = 0; j < mat.Width; j++)
  3374. // {
  3375. // if (mat.At<byte>(i, j) == 255)//白色
  3376. // mat.Set<byte>(i, j, 0); //黄色
  3377. // }
  3378. //}
  3379. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat).Save(gbxBmpPath + ".jpg", ImageFormat.Jpeg);
  3380. }
  3381. AddTextEvent("打开窗口", "7");
  3382. //
  3383. ToolStripButton btn = sender as ToolStripButton;
  3384. AddTextEvent("打开窗口", btn.Tag.ToString());
  3385. FrmShowDefectImage frm = new FrmShowDefectImage(gbxBmpPath + ".jpg", order, string.IsNullOrEmpty(btn.Tag.ToString()) ? 0 : Convert.ToInt32(btn.Tag.ToString()));
  3386. frm.Show();
  3387. AddTextEvent("打开窗口", "9");
  3388. }
  3389. catch (Exception ex)
  3390. {
  3391. MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
  3392. }
  3393. }
  3394. private void tsbtnLog_Click(object sender, EventArgs e)
  3395. {
  3396. if (string.IsNullOrWhiteSpace(Config.LogPath)) return;
  3397. string lsPath = (Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\").Replace("\\\\", "\\");
  3398. if(!Directory.Exists(lsPath))
  3399. Directory.CreateDirectory(lsPath);
  3400. System.Diagnostics.Process.Start("explorer.exe", lsPath);
  3401. }
  3402. }
  3403. }