Make_ParseLog.cs 42 KB

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