Make_ParseLog.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. using DevExpress.Utils.CodedUISupport;
  2. using DevExpress.Xpo.Logger;
  3. using HslCommunication;
  4. using NPOI.POIFS.NIO;
  5. using NPOI.SS.Formula.Functions;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Data;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Security.AccessControl;
  15. using System.Security.Principal;
  16. using System.Text;
  17. using System.Web.Services.Description;
  18. using System.Web.UI.WebControls;
  19. using System.Windows.Forms;
  20. using UAS_MES_NEW.CustomControl.ButtonUtil;
  21. using UAS_MES_NEW.DataOperate;
  22. using UAS_MES_NEW.Entity;
  23. using UAS_MES_NEW.PublicMethod;
  24. namespace UAS_MES_NEW.Make
  25. {
  26. public partial class Make_ParseLog : Form
  27. {
  28. public Make_ParseLog()
  29. {
  30. InitializeComponent();
  31. }
  32. FileSystemWatcher watcher;
  33. LogStringBuilder sql = new LogStringBuilder();
  34. DataTable Dbfind;
  35. DataTable dt;
  36. DataHelper dh;
  37. string currFileType = "", equiType = "";
  38. string ccdTestRes = "OK"; //两面都OK为OK,否则为NG
  39. List<string> ccdNgFile = new List<string>();
  40. string SN, omakeCode, oMsid, oErrorMessage = "";
  41. List<string> fileList = new List<string>();
  42. Timer ChangeWoTimer;
  43. string outFileMsg;
  44. private void Make_ParseLog_Load(object sender, EventArgs e)
  45. {
  46. dh = SystemInf.dh;
  47. Choose.Enabled = false;
  48. fileList.Add("E:\\AOIMes\\Mes");
  49. fileList.Add("E:\\UAS");
  50. fileList.Add("");
  51. ChangeWoTimer = new Timer();
  52. ChangeWoTimer.Interval = 30000;
  53. ChangeWoTimer.Tick += ChangeWoFunc;
  54. watcher = new FileSystemWatcher();
  55. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  56. watcher.Created += OnFileCreated;
  57. watcher.Changed += OnFileChanged;
  58. /*watcher.Deleted += OnFileChanged;
  59. watcher.Renamed += OnFileChanged;*/
  60. //设置锁定工单
  61. LockMakeCode.GetMakeCodeCtl(ma_code);
  62. ma_code.SetLockCheckBox(LockMakeCode);
  63. //工单号放大镜配置
  64. ma_code.TableName = "make left join product on ma_prodcode=pr_code";
  65. ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称";
  66. ma_code.FormName = Name;
  67. ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" };
  68. ma_code.Condition = "ma_statuscode='STARTED'";
  69. ma_code.DbChange += Ma_code_DbChange;
  70. }
  71. private void Ma_code_DbChange(object sender, EventArgs e)
  72. {
  73. Dbfind = ma_code.ReturnData;
  74. BaseUtil.SetFormValue(this.Controls, Dbfind);
  75. //获取工单的其他信息
  76. sql.Clear();
  77. sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,");
  78. sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on ");
  79. sql.Append("mcd_maid=ma_id left join product on pr_code=ma_prodcode where ma_code='" + ma_code.Text + "' and mcd_stepcode='" + User.CurrentStepCode + "'");
  80. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  81. if (dt.Rows.Count > 0)
  82. {
  83. BaseUtil.SetFormValue(this.Controls, dt);
  84. }
  85. }
  86. private void Device_SelectedIndexChanged(object sender, EventArgs e)
  87. {
  88. if (Device.SelectedIndex == -1) return;
  89. if(ChangeWoTimer.Enabled) ChangeWoTimer.Stop();
  90. onWatch.Enabled = true;
  91. FileBox.Visible = false;
  92. switch (Device.SelectedIndex)
  93. {
  94. case 0:
  95. currFileType = "Txt";
  96. equiType = "AOI";
  97. /*ChangeWoTimer.Start();
  98. ChangeWoFunc(null, null);*/
  99. break;
  100. case 1:
  101. currFileType = "bmp";
  102. equiType = "Xray";
  103. onWatch.Enabled = false;
  104. FileBox.Visible = true;
  105. break;
  106. case 2:
  107. currFileType = "jpg";
  108. equiType = "CCD";
  109. break;
  110. }
  111. txtPath.Text = fileList[Device.SelectedIndex];
  112. txtPath.Focus();
  113. txtPath.SelectAll();
  114. ma_code.Enabled = true;
  115. Choose.Enabled = true;
  116. txtPath.Enabled = false;
  117. }
  118. private void Choose_Click(object sender, EventArgs e)
  119. {
  120. using (var dialog = new FolderBrowserDialog())
  121. {
  122. if (dialog.ShowDialog() == DialogResult.OK)
  123. {
  124. txtPath.Text = dialog.SelectedPath;
  125. txtPath.Enabled = false;
  126. Device.Enabled = false;
  127. watcher.EnableRaisingEvents = false;
  128. }
  129. }
  130. }
  131. private void claerBtn_Click(object sender, EventArgs e)
  132. {
  133. lstFiles.Items.Clear();
  134. }
  135. private void allParse_Click(object sender, EventArgs e)
  136. {
  137. if (String.IsNullOrEmpty(ma_code.Text))
  138. {
  139. ma_code.Focus();
  140. MessageBox.Show(this.ParentForm, "请选择归属工单", "提示");
  141. return;
  142. }
  143. if (Device.SelectedIndex == -1)
  144. {
  145. Device.Focus();
  146. Device.SelectAll();
  147. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  148. return;
  149. }
  150. if (String.IsNullOrEmpty(txtPath.Text))
  151. {
  152. txtPath.Focus();
  153. txtPath.SelectAll();
  154. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  155. return;
  156. }
  157. string[] txtFiles;
  158. if (equiType == "Xray")
  159. {
  160. txtFiles = Directory.GetDirectories(txtPath.Text);
  161. if (txtFiles.Length == 0)
  162. {
  163. LogMessage(0, $"当前路径{txtPath.Text},没有{equiType}设备输出的文件夹");
  164. return;
  165. }
  166. }
  167. else
  168. {
  169. txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  170. if (txtFiles.Length == 0)
  171. {
  172. LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  173. return;
  174. }
  175. }
  176. RefreshFileList();
  177. }
  178. private void onWatch_Click(object sender, EventArgs e)
  179. {
  180. if (String.IsNullOrEmpty(ma_code.Text))
  181. {
  182. ma_code.Focus();
  183. MessageBox.Show(this.ParentForm, "请选择归属工单", "提示");
  184. return;
  185. }
  186. if (Device.SelectedIndex == -1)
  187. {
  188. Device.Focus();
  189. Device.SelectAll();
  190. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  191. return;
  192. }
  193. if (String.IsNullOrEmpty(txtPath.Text))
  194. {
  195. txtPath.Focus();
  196. txtPath.SelectAll();
  197. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  198. return;
  199. }
  200. try
  201. {
  202. watcher.Path = txtPath.Text;
  203. watcher.Filter = $"*.{currFileType}";
  204. if (onWatch.Text == "开启解析")
  205. {
  206. watcher.EnableRaisingEvents = true;
  207. onWatch.Text = "关闭解析";
  208. }
  209. else
  210. {
  211. watcher.EnableRaisingEvents = false;
  212. onWatch.Text = "开启解析";
  213. }
  214. }
  215. catch (Exception ex)
  216. {
  217. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  218. }
  219. }
  220. private void OnFileCreated(object sender, FileSystemEventArgs e)
  221. {
  222. RefreshFileList();
  223. }
  224. private void OnFileChanged(object sender, FileSystemEventArgs e)
  225. {
  226. if (e.ChangeType == WatcherChangeTypes.Changed)
  227. {
  228. RefreshFileList();
  229. }
  230. }
  231. private void RefreshFileList()
  232. {
  233. if (lstFiles.InvokeRequired)
  234. {
  235. lstFiles.Invoke(new Action(RefreshFileList));
  236. lstFiles.BeginInvoke(new Action(RefreshFileList));
  237. return;
  238. }
  239. try
  240. {
  241. if (!Directory.Exists(txtPath.Text))
  242. {
  243. LogMessage(0, $"目录不存在: {txtPath.Text}");
  244. return;
  245. }
  246. string[] txtFiles;
  247. if (equiType == "Xray")
  248. {
  249. txtFiles = Directory.GetDirectories(txtPath.Text);
  250. }
  251. else
  252. {
  253. txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  254. }
  255. if (txtFiles.Length == 0)
  256. {
  257. return;
  258. }
  259. foreach (string file in txtFiles)
  260. {
  261. if (equiType == "Xray")
  262. {
  263. if (Path.GetFileName(file).Contains("Log_")) continue;
  264. if (!Directory.Exists(file))
  265. {
  266. LogMessage(0, $"文件夹不存在: {file}");
  267. }
  268. outFileMsg = CheckFolderPermissions(file);
  269. if (outFileMsg != "OK")
  270. {
  271. if(!outFileMsg.Contains("文件被占用"))
  272. {
  273. LogMessage(0, outFileMsg);
  274. }
  275. continue;
  276. }
  277. }else if (equiType == "CCD")
  278. {
  279. outFileMsg = CheckFileAccess(file);
  280. if (outFileMsg != "OK")
  281. {
  282. //LogMessage(0, outFileMsg);
  283. //continue;
  284. }
  285. }
  286. else
  287. {
  288. if (!File.Exists(file))
  289. {
  290. LogMessage(0, $"文件不存在: {file}");
  291. }
  292. if (File.ReadAllText(file).Length == 0)
  293. {
  294. continue;
  295. }
  296. }
  297. if (equiType == "AOI")
  298. {
  299. using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  300. using (StreamReader SR = new StreamReader(fileStream, Encoding.GetEncoding("GBK")))
  301. {
  302. string Content = SR.ReadToEnd();
  303. SR.Close();
  304. SR.Dispose();
  305. List<Log> logArr = new List<Log>() { };
  306. string[] lines = Content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  307. int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
  308. Log itemLog = new Log() { };
  309. foreach (var item in lines)
  310. {
  311. if (string.IsNullOrEmpty(item)) continue;
  312. if (Array.IndexOf(lines, item) == 1) itemLog.SN = item.Split(':')[1].ToString().Trim().Replace(";", ";");
  313. if (Array.IndexOf(lines, item) == 2) itemLog.TestTime = item.Split(':')[1].Split('.')[0].ToString().Trim();
  314. if (Array.IndexOf(lines, item) == 3) itemLog.Result = item.Split(':')[1].ToString().Trim();
  315. if (Array.IndexOf(lines, item) == 4) itemLog.Side = item.Split(':')[1].ToString().Trim();
  316. if (item.IndexOf("元件位置") > -1)
  317. {
  318. LogItem list = new LogItem();
  319. int ind = Array.IndexOf(lines, item);
  320. list.Location = lines[ind].Split(':')[1].ToString().Trim();
  321. list.ReelNo = lines[ind + 1].Split(':')[1].ToString().Trim();
  322. list.FirstType = lines[ind + 2].Split(':')[1].ToString().Trim();
  323. list.SceondType = lines[ind + 3].Split(':')[1].ToString().Trim();
  324. list.Name = lines[ind + 4].Split(':')[1].ToString().Trim();
  325. itemLog.LogItemList.Add(list);
  326. }
  327. }
  328. logArr.Add(itemLog);
  329. if (logArr.Count == 0)
  330. {
  331. break;
  332. }
  333. if (InsertDb(logArr, file, fileNum))
  334. {
  335. if (ConsoleLog(Content, file, logArr[0].SN))
  336. {
  337. File.WriteAllText(file, string.Empty);
  338. outFileMsg = CheckFileAccess(file);
  339. if (outFileMsg == "OK")
  340. {
  341. File.Delete(file);
  342. }
  343. }
  344. }
  345. }
  346. }
  347. else if (equiType == "Xray")
  348. {
  349. if (Path.GetFileName(file).Contains('_'))
  350. {
  351. SN = Path.GetFileName(file).Split('_')[1].Replace(";", ";");
  352. string[] floderFile = Directory.GetFiles(file, $"*.{currFileType}");
  353. foreach (string floderFileItem in floderFile)
  354. {
  355. if (UploadImageToFtp(floderFileItem, SN))
  356. {
  357. //if (!LogicHandler.CheckStepSNAndMacode("", User.UserSourceCode, SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  358. //{
  359. // LogMessage(0, $"核对NG:{oErrorMessage}");
  360. //}
  361. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  362. VALUES ( steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text.Trim()}','{User.UserSourceCode}', sysdate,'Xray', 'http://192.168.1.5:8099/ftp/xray/{DateTime.Now.ToString("yyyyMMdd")}/{SN}/{Path.GetFileName(floderFileItem)}' )", "insert");
  363. if (Array.IndexOf(floderFile, floderFileItem) == floderFile.Length - 1)
  364. {
  365. string newFloderName = Path.GetDirectoryName(file);
  366. Directory.Move(file, Path.Combine(newFloderName, "Log_" + Path.GetFileName(file)));
  367. }
  368. }
  369. }
  370. }
  371. }
  372. else if(equiType == "CCD")
  373. {
  374. // 有2面CCD图片开始处理
  375. if (txtFiles.Length == 1) break;
  376. foreach (var fileItem in txtFiles)
  377. {
  378. string imageName = Path.GetFileName(fileItem);
  379. string iName = imageName.Split('_')[0];
  380. if (iName[0].ToString() == "A")
  381. {
  382. if (iName.ToUpper().Contains("NG"))
  383. {
  384. SN = iName.Substring(3);
  385. ccdTestRes = ccdTestRes == "NG" ? "NG" : "NG";
  386. ccdNgFile.Add(fileItem);
  387. }
  388. else
  389. {
  390. SN = iName.Substring(1);
  391. ccdTestRes = ccdTestRes == "NG" ? "NG" : "OK";
  392. }
  393. }else if(iName[0].ToString() == "B")
  394. {
  395. if (iName.ToUpper().Contains("NG"))
  396. {
  397. ccdTestRes = ccdTestRes == "NG" ? "NG" : "NG";
  398. ccdNgFile.Add(fileItem);
  399. }
  400. else
  401. {
  402. ccdTestRes = ccdTestRes == "NG" ? "NG" : "OK";
  403. }
  404. }
  405. }
  406. // 创建logs目录
  407. string parentPath = Path.GetDirectoryName(file);
  408. string newFolderPath = Path.Combine(parentPath, "Logs");
  409. if (!Directory.Exists(newFolderPath))
  410. {
  411. Directory.CreateDirectory(newFolderPath);
  412. }
  413. // logs目录下创建sn序列号目录
  414. string changeName = Path.Combine(newFolderPath, SN);
  415. if (!Directory.Exists(changeName))
  416. {
  417. Directory.CreateDirectory(changeName);
  418. }
  419. /*string result = Path.GetFileName(file).Split('_')[0];
  420. if (result.ToUpper().Contains("NG"))
  421. {
  422. if (UploadImageToFtp(file, SN))
  423. {
  424. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  425. VALUES (steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text}','{User.UserSourceCode}', sysdate,'CCD', 'http://192.168.1.5:8088/ftp/ccd/{SN}/{Path.GetFileName(file)}' )", "insert");
  426. }
  427. }*/
  428. if (ccdTestRes == "NG") // 产品是否为NG
  429. {
  430. foreach (var fileItem in ccdNgFile)
  431. {
  432. if (UploadImageToFtp(file, SN)) // 上传NG面全部图片
  433. {
  434. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  435. VALUES (steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text}','{User.UserSourceCode}', sysdate,'CCD', 'http://192.168.1.5:8088/ftp/ccd/{SN}/{Path.GetFileName(file)}' )", "insert");
  436. }
  437. }
  438. }
  439. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  440. {
  441. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, SN, "日志解析", "OK", User.UserCode, out oErrorMessage))
  442. {
  443. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", SN, "");
  444. LogMessage(1, $"序列号: {SN} 已过站解析");
  445. }
  446. else
  447. {
  448. LogMessage(0, $"序列号: {SN},处理过站NG:{oErrorMessage}");
  449. }
  450. }
  451. else
  452. {
  453. LogMessage(0, $"序列号: {SN},过站核对NG:{oErrorMessage}");
  454. }
  455. string targetFile = Path.Combine(changeName, Path.GetFileName(file));
  456. if (File.Exists(targetFile))
  457. {
  458. File.Delete(targetFile);
  459. }
  460. File.Move(file, targetFile);
  461. }
  462. }
  463. if (equiType == "CCD")
  464. {
  465. LogMessage(1, $"序列号: {SN} 图片已处理");
  466. }
  467. }
  468. catch (Exception ex)
  469. {
  470. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  471. }
  472. }
  473. private bool InsertDb(List<Log> logs, string PathName, int fileNum)
  474. {
  475. try
  476. {
  477. StringBuilder sql = new StringBuilder();
  478. StringBuilder details = new StringBuilder();
  479. List<string> param = new List<string>() { };
  480. foreach (var item in logs)
  481. {
  482. dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{item.SN}' AND mp_sourcecode = 'AOI'", "select");
  483. if (dt.Rows.Count > 0)
  484. {
  485. LogMessage(1, $"序列号:{item.SN}已经过站并记录测试信息");
  486. continue;
  487. }
  488. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  489. {
  490. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", item.Result.ToUpper() == "PASS" ? "OK" :"NG", User.UserCode, out oErrorMessage))
  491. {
  492. string outMsg = "";
  493. param.Add(omakeCode);
  494. param.Add(item.SN);
  495. param.Add(User.UserSourceCode);
  496. param.Add(User.UserName);
  497. param.Add(User.CurrentStepCode);
  498. param.Add(item.Result.ToUpper());
  499. param.Add(item.TestTime);
  500. param.Add(item.Side);
  501. param.Add(equiType);
  502. details.Clear();
  503. foreach (LogItem LI in item.LogItemList)
  504. {
  505. details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
  506. }
  507. param.Add(details.ToString());
  508. param.Add(outMsg);
  509. string[] paramList = param.ToArray();
  510. dh.CallProcedure("CS_INSERT_TESTDETAILS", ref paramList);
  511. if (paramList[10].Substring(0, 2) == "OK")
  512. {
  513. LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
  514. }
  515. else
  516. {
  517. LogMessage(1, paramList[8]);
  518. }
  519. param.Clear();
  520. if (logs.IndexOf(item) == logs.Count - 1)
  521. {
  522. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
  523. return true;
  524. }
  525. }
  526. else
  527. {
  528. LogMessage(0, $"处理过站NG:{oErrorMessage}");
  529. break;
  530. }
  531. }
  532. else
  533. {
  534. LogMessage(0, $"过站核对NG:{oErrorMessage}");
  535. break;
  536. }
  537. }
  538. return false;
  539. }
  540. catch (Exception ex)
  541. {
  542. LogMessage(0, $"Error,处理解析写入: {ex.Message}");
  543. return false;
  544. }
  545. }
  546. private void ChangeWoFunc(object sender, EventArgs e)
  547. {
  548. try
  549. {
  550. sql.Clear();
  551. sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
  552. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  553. if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
  554. {
  555. ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
  556. return;
  557. }
  558. LogMessage(0, $"NG,自动识别更新工单");
  559. }
  560. catch (Exception ex)
  561. {
  562. LogMessage(0, $"Error,自动切换工单: {ex.Message}");
  563. }
  564. }
  565. private bool ConsoleLog(string Content, string PathName,string SN)
  566. {
  567. try
  568. {
  569. string sourcePaht = Path.GetDirectoryName(PathName);
  570. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  571. string newFolderName = "Logs";
  572. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  573. if (!Directory.Exists(newFolderPath))
  574. {
  575. Directory.CreateDirectory(newFolderPath);
  576. }
  577. string newFileName = "Log_" + Path.GetFileName(changeName);
  578. string newFilePath = Path.Combine(newFolderPath, newFileName);
  579. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  580. return true;
  581. }
  582. catch (Exception ex)
  583. {
  584. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  585. return false;
  586. }
  587. }
  588. private void LogMessage(int type, string message)
  589. {
  590. if (type == 0)
  591. {
  592. if (lstFiles.InvokeRequired)
  593. {
  594. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  595. return;
  596. }
  597. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  598. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  599. }
  600. else
  601. {
  602. if (lstOk.InvokeRequired)
  603. {
  604. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  605. return;
  606. }
  607. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  608. lstOk.TopIndex = lstOk.Items.Count - 1;
  609. }
  610. }
  611. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  612. {
  613. if (e.Index < 0) return;
  614. e.DrawBackground();
  615. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  616. Brush color = Brushes.Black;
  617. if (txt.Contains("NG"))
  618. {
  619. color = Brushes.Red;
  620. }
  621. else if (txt.Contains("ERROR"))
  622. {
  623. color = Brushes.Red;
  624. }
  625. else
  626. {
  627. color = Brushes.Green;
  628. }
  629. e.DrawFocusRectangle();
  630. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  631. }
  632. public bool UploadImageToFtp(string localFilePath, string Sn)
  633. {
  634. string ftpServer;
  635. ftpServer = equiType == "Xray" ? "ftp://10.8.0.215:21/xray/" : "ftp://10.8.0.215:21/ccd/";
  636. ftpServer = equiType == "Xray" ? "ftp://192.168.1.5:21/xray/" : "ftp://192.168.1.5:21/ccd/";
  637. string username = "vsftpd";
  638. string password = "vsftpd3ef41637hy";
  639. string ftpTimePath = $"{ftpServer.TrimEnd('/')}/{DateTime.Now.ToString("yyyyMMdd")}";
  640. string outResult = CreateFtpDirectoryIfNotExists(ftpTimePath, username, password);
  641. if (outResult.Substring(0, 2) != "OK")
  642. {
  643. LogMessage(0, outResult);
  644. return false;
  645. }
  646. string ftpFullPath = $"{ftpTimePath}/{Sn}";
  647. outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
  648. if (outResult.Substring(0, 2) != "OK")
  649. {
  650. LogMessage(0, outResult);
  651. return false;
  652. }
  653. string remoteFileName = Path.GetFileName(localFilePath);
  654. string uri = $"{ftpFullPath}/{remoteFileName}";
  655. try
  656. {
  657. var request = (FtpWebRequest)WebRequest.Create(uri);
  658. request.Method = WebRequestMethods.Ftp.UploadFile;
  659. request.Credentials = new NetworkCredential(username, password);
  660. request.UsePassive = true;
  661. request.UseBinary = true;
  662. request.KeepAlive = false;
  663. using (var fileStream = File.OpenRead(localFilePath))
  664. using (var requestStream = request.GetRequestStream())
  665. {
  666. byte[] buffer = new byte[4096];
  667. int bytesRead;
  668. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  669. {
  670. requestStream.Write(buffer, 0, bytesRead);
  671. }
  672. }
  673. using (var response = (FtpWebResponse)request.GetResponse())
  674. {
  675. LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
  676. return true;
  677. }
  678. }
  679. catch (WebException ex)
  680. {
  681. if (ex.Response is FtpWebResponse response)
  682. {
  683. LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  684. }
  685. else
  686. {
  687. LogMessage(0, $"NG,Web异常: {ex.Message}");
  688. }
  689. return false;
  690. }
  691. catch (Exception ex)
  692. {
  693. LogMessage(0, $"NG,上传失败: {ex.Message}");
  694. return false;
  695. }
  696. }
  697. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  698. {
  699. try
  700. {
  701. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  702. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  703. request.Credentials = new NetworkCredential(username, password);
  704. request.UsePassive = true;
  705. request.UseBinary = true;
  706. request.KeepAlive = false;
  707. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  708. {
  709. response.Close();
  710. return "OK,目录创建成功: " + response.StatusDescription;
  711. }
  712. }
  713. catch (WebException ex)
  714. {
  715. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  716. {
  717. return "OK,目录已存在: " + response.StatusDescription;
  718. }
  719. else
  720. {
  721. return "NG,创建目录时发生错误: " + ex.Message;
  722. }
  723. }
  724. }
  725. private void Delete_Click(object sender, EventArgs e)
  726. {
  727. if (!Directory.Exists(txtPath.Text))
  728. {
  729. LogMessage(0, $"删除路径不存在: {txtPath.Text}");
  730. return;
  731. }
  732. List<string> DeleteList = new List<string>() { };
  733. if (!string.IsNullOrEmpty(SN1.Text)) DeleteList.Add("1-1_" + SN1.Text);
  734. if (!string.IsNullOrEmpty(SN2.Text)) DeleteList.Add("1-2_" + SN2.Text);
  735. if (!string.IsNullOrEmpty(SN3.Text)) DeleteList.Add("1-3_" + SN3.Text);
  736. if (!string.IsNullOrEmpty(SN4.Text)) DeleteList.Add("2-1_" + SN4.Text);
  737. if (!string.IsNullOrEmpty(SN5.Text)) DeleteList.Add("2-2_" + SN5.Text);
  738. if (!string.IsNullOrEmpty(SN6.Text)) DeleteList.Add("2-3_" + SN6.Text);
  739. string DeletePath;
  740. int DeleteCount = 0;
  741. foreach (var item in DeleteList)
  742. {
  743. DeletePath = Path.Combine(txtPath.Text, item);
  744. if (DeletePath == txtPath.Text)
  745. {
  746. LogMessage(0, $"NG,路径{DeletePath}中,没有 {item} 文件夹");
  747. continue;
  748. }
  749. if (Directory.Exists(DeletePath))
  750. {
  751. try
  752. {
  753. Directory.Delete(DeletePath);
  754. }
  755. catch (IOException ex)
  756. {
  757. LogMessage(0, $"NG,文件夹{item}存有文件,{ex.Message}");
  758. continue;
  759. }
  760. catch (Exception ex)
  761. {
  762. LogMessage(0, $"NG,删除异常,{ex.Message}");
  763. continue;
  764. }
  765. DeleteCount++;
  766. if (SN1.Text == item) SN1.Text = "";
  767. if (SN2.Text == item) SN2.Text = "";
  768. if (SN3.Text == item) SN3.Text = "";
  769. if (SN4.Text == item) SN4.Text = "";
  770. if (SN5.Text == item) SN5.Text = "";
  771. if (SN6.Text == item) SN6.Text = "";
  772. }
  773. }
  774. if(DeleteCount != 0)
  775. {
  776. LogMessage(0, $"一键删除文件夹成功,共 {DeleteCount}个");
  777. return;
  778. }
  779. else
  780. {
  781. LogMessage(0, $"NG,请扫描SN序列号删除文件夹");
  782. }
  783. }
  784. private void Clear_Click(object sender, EventArgs e)
  785. {
  786. SN1.Text = "";
  787. SN2.Text = "";
  788. SN3.Text = "";
  789. SN4.Text = "";
  790. SN5.Text = "";
  791. SN6.Text = "";
  792. SN1.Focus();
  793. SN1.SelectAll();
  794. }
  795. private void Generate_Click(object sender, EventArgs e)
  796. {
  797. if (!Directory.Exists(txtPath.Text))
  798. {
  799. LogMessage(0, $"NG,生成路径不存在: {txtPath.Text}");
  800. return;
  801. }
  802. List<string> GenerateList = new List<string>() { };
  803. if (!string.IsNullOrEmpty(SN1.Text)) GenerateList.Add("1-1_" + SN1.Text);
  804. if (!string.IsNullOrEmpty(SN2.Text)) GenerateList.Add("1-2_" + SN2.Text);
  805. if (!string.IsNullOrEmpty(SN3.Text)) GenerateList.Add("1-3_" + SN3.Text);
  806. if (!string.IsNullOrEmpty(SN4.Text)) GenerateList.Add("2-1_" + SN4.Text);
  807. if (!string.IsNullOrEmpty(SN5.Text)) GenerateList.Add("2-2_" + SN5.Text);
  808. if (!string.IsNullOrEmpty(SN6.Text)) GenerateList.Add("2-3_" + SN6.Text);
  809. string GeneratePath;
  810. int GenerateCount = 0;
  811. foreach (var item in GenerateList)
  812. {
  813. GeneratePath = Path.Combine(txtPath.Text, item);
  814. if (GeneratePath == txtPath.Text)
  815. {
  816. LogMessage(0, $"NG,请扫描SN序列号创建文件夹");
  817. continue;
  818. }
  819. if (Directory.Exists(GeneratePath))
  820. {
  821. LogMessage(0, $"NG,路径{txtPath.Text}已有{item}文件夹");
  822. continue;
  823. }
  824. Directory.CreateDirectory(GeneratePath);
  825. GenerateCount++;
  826. }
  827. if(GenerateCount != 0) LogMessage(0, $"一键生成文件夹成功,共 {GenerateCount}个");
  828. }
  829. private void SN1_KeyDown(object sender, KeyEventArgs e)
  830. {
  831. if (e.KeyCode != Keys.Enter) return;
  832. if (string.IsNullOrEmpty(SN1.Text)) return;
  833. SN2.Focus();
  834. SN2.SelectAll();
  835. }
  836. private void SN2_KeyDown(object sender, KeyEventArgs e)
  837. {
  838. if (e.KeyCode != Keys.Enter) return;
  839. if (string.IsNullOrEmpty(SN2.Text)) return;
  840. SN3.Focus();
  841. SN3.SelectAll();
  842. }
  843. private void SN3_KeyDown(object sender, KeyEventArgs e)
  844. {
  845. if (e.KeyCode != Keys.Enter) return;
  846. if (string.IsNullOrEmpty(SN3.Text)) return;
  847. SN4.Focus();
  848. SN4.SelectAll();
  849. }
  850. private void SN4_KeyDown(object sender, KeyEventArgs e)
  851. {
  852. if (e.KeyCode != Keys.Enter) return;
  853. if (string.IsNullOrEmpty(SN4.Text)) return;
  854. SN5.Focus();
  855. SN5.SelectAll();
  856. }
  857. private void SN5_KeyDown(object sender, KeyEventArgs e)
  858. {
  859. if (e.KeyCode != Keys.Enter) return;
  860. if (string.IsNullOrEmpty(SN5.Text)) return;
  861. SN6.Focus();
  862. SN6.SelectAll();
  863. }
  864. private void SN6_KeyDown(object sender, KeyEventArgs e)
  865. {
  866. if (e.KeyCode != Keys.Enter) return;
  867. if (string.IsNullOrEmpty(SN6.Text)) return;
  868. Generate.Focus();
  869. }
  870. public string CheckFileAccess(string filePath)
  871. {
  872. try
  873. {
  874. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  875. {
  876. return "OK";
  877. }
  878. }
  879. catch (IOException ex)
  880. {
  881. return "NG,文件被占用: " + ex.Message;
  882. }
  883. catch (UnauthorizedAccessException ex)
  884. {
  885. return "NG,权限不足,无法访问文件: " + ex.Message;
  886. }
  887. catch (Exception ex)
  888. {
  889. return "NG," + ex.Message;
  890. }
  891. }
  892. public string CheckFolderPermissions(string path)
  893. {
  894. try
  895. {
  896. DirectorySecurity security = Directory.GetAccessControl(path);
  897. AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
  898. WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
  899. foreach (FileSystemAccessRule rule in rules)
  900. {
  901. if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
  902. {
  903. Console.WriteLine($" {rule.IdentityReference.Value}");
  904. Console.WriteLine($"权限类型: {rule.AccessControlType}");
  905. Console.WriteLine($"具体权限: {rule.FileSystemRights}");
  906. Console.WriteLine($"是否继承: {rule.IsInherited}");
  907. }
  908. }
  909. return "OK";
  910. }
  911. catch (UnauthorizedAccessException ex)
  912. {
  913. return $"NG,无权限访问文件夹: {ex.Message}";
  914. }
  915. catch (DirectoryNotFoundException)
  916. {
  917. return "NG,文件夹不存在";
  918. }
  919. catch (Exception ex)
  920. {
  921. return "NG," + ex.Message;
  922. }
  923. }
  924. public class Log
  925. {
  926. public string SN { set; get; }
  927. public string Result { set; get; }
  928. public string TestTime { set; get; }
  929. public string Side { set; get; }
  930. public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
  931. }
  932. public class LogItem
  933. {
  934. public string Location { set; get; }
  935. public string ReelNo { set; get; }
  936. public string FirstType { set; get; }
  937. public string SceondType { set; get; }
  938. public string Name { set; get; }
  939. }
  940. }
  941. }