Make_ParseLog.cs 39 KB

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