Make_ParseLog.cs 38 KB

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