Make_ParseLog.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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("C:\\Users\\MI\\Desktop");
  48. fileList.Add("C:\\Users\\MI\\Desktop");
  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_"))
  262. {
  263. continue;
  264. }
  265. if (!Directory.Exists(file))
  266. {
  267. LogMessage(0, $"文件夹不存在: {file}");
  268. }
  269. outFileMsg = CheckFolderPermissions(file);
  270. if (outFileMsg != "OK")
  271. {
  272. if(!outFileMsg.Contains("文件被占用"))
  273. {
  274. LogMessage(0, outFileMsg);
  275. }
  276. continue;
  277. }
  278. }
  279. else
  280. {
  281. if (!File.Exists(file))
  282. {
  283. LogMessage(0, $"文件不存在: {file}");
  284. }
  285. //outFileMsg = CheckFileAccess(file);
  286. //if (outFileMsg != "OK")
  287. //{
  288. // //LogMessage(0, outFileMsg);
  289. // continue;
  290. //}
  291. if (File.ReadAllText(file).Length == 0)
  292. {
  293. continue;
  294. }
  295. }
  296. if (equiType == "AOI")
  297. {
  298. using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  299. using (StreamReader SR = new StreamReader(fileStream, Encoding.GetEncoding("GBK")))
  300. {
  301. string Content = SR.ReadToEnd();
  302. SR.Close();
  303. SR.Dispose();
  304. List<Log> logArr = new List<Log>() { };
  305. string[] lines = Content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  306. int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
  307. Log itemLog = new Log() { };
  308. foreach (var item in lines)
  309. {
  310. if (string.IsNullOrEmpty(item)) continue;
  311. if (Array.IndexOf(lines, item) == 1) itemLog.SN = item.Split(':')[1].ToString().Trim().Replace(";", ";");
  312. if (Array.IndexOf(lines, item) == 2) itemLog.TestTime = item.Split(':')[1].Split('.')[0].ToString().Trim();
  313. if (Array.IndexOf(lines, item) == 3) itemLog.Result = item.Split(':')[1].ToString().Trim();
  314. if (Array.IndexOf(lines, item) == 4) itemLog.Side = item.Split(':')[1].ToString().Trim();
  315. if (item.IndexOf("元件位置") > -1)
  316. {
  317. LogItem list = new LogItem();
  318. int ind = Array.IndexOf(lines, item);
  319. list.Location = lines[ind].Split(':')[1].ToString().Trim();
  320. list.ReelNo = lines[ind + 1].Split(':')[1].ToString().Trim();
  321. list.FirstType = lines[ind + 2].Split(':')[1].ToString().Trim();
  322. list.SceondType = lines[ind + 3].Split(':')[1].ToString().Trim();
  323. list.Name = lines[ind + 4].Split(':')[1].ToString().Trim();
  324. itemLog.LogItemList.Add(list);
  325. }
  326. }
  327. logArr.Add(itemLog);
  328. if (logArr.Count == 0)
  329. {
  330. break;
  331. }
  332. if (InsertDb(logArr, file, fileNum))
  333. {
  334. if (ConsoleLog(Content, file, logArr[0].SN))
  335. {
  336. File.WriteAllText(file, string.Empty);
  337. outFileMsg = CheckFileAccess(file);
  338. if (outFileMsg == "OK")
  339. {
  340. File.Delete(file);
  341. }
  342. }
  343. }
  344. }
  345. }
  346. else if (equiType == "Xray")
  347. {
  348. string[] floderFile = Directory.GetFiles(file, $"*.{currFileType}");
  349. foreach(string floderFileItem in floderFile)
  350. {
  351. SN = Path.GetFileName(floderFileItem).Split('_')[1];
  352. if (UploadImageToFtp(floderFileItem, SN))
  353. {
  354. if (!LogicHandler.CheckStepSNAndMacode("", User.UserSourceCode, SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  355. {
  356. LogMessage(0, $"核对NG:{oErrorMessage}");
  357. }
  358. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  359. VALUES ( steptestmain_seq.NEXTVAL,'{SN}','{omakeCode}','{User.UserSourceCode}', sysdate,'Xray', 'http://192.168.1.5:8099/ftp/xray/{DateTime.Now.ToString("yyyyMMdd")}/{Path.GetFileName(floderFileItem)}' )", "insert");
  360. if (Array.IndexOf(floderFile, floderFileItem) == floderFile.Length - 1)
  361. {
  362. string newFloderName = Path.GetDirectoryName(file);
  363. Directory.Move(file, Path.Combine(newFloderName, "Log_" + Path.GetFileName(file)));
  364. }
  365. }
  366. }
  367. }
  368. else if(equiType == "CCD")
  369. {
  370. if (txtFiles.Length != 2) break;
  371. foreach (var fileItem in txtFiles)
  372. {
  373. string imageName = Path.GetFileName(fileItem);
  374. SN = imageName.Split('_')[0].ToString();
  375. if (imageName.ToUpper().Contains("NG"))
  376. {
  377. if (UploadImageToFtp(fileItem, SN))
  378. {
  379. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  380. VALUES ( steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text}','{User.UserSourceCode}', sysdate,'CCD', 'http://192.168.1.5:8088/ftp/ccd/{SN}/{Path.GetFileName(fileItem)}' )", "insert");
  381. }
  382. }
  383. string parentPath = Path.GetDirectoryName(file);
  384. string changeName = Path.Combine(parentPath, SN);
  385. if (!Directory.Exists(changeName))
  386. {
  387. Directory.CreateDirectory(changeName);
  388. }
  389. File.Move(file, changeName);
  390. }
  391. }
  392. }
  393. }
  394. catch (Exception ex)
  395. {
  396. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  397. }
  398. }
  399. private bool InsertDb(List<Log> logs, string PathName, int fileNum)
  400. {
  401. try
  402. {
  403. StringBuilder sql = new StringBuilder();
  404. StringBuilder details = new StringBuilder();
  405. List<string> param = new List<string>() { };
  406. foreach (var item in logs)
  407. {
  408. dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{item.SN}' AND mp_sourcecode = 'AOI'", "select");
  409. if (dt.Rows.Count > 0)
  410. {
  411. LogMessage(1, $"序列号:{item.SN}已经过站并记录测试信息");
  412. continue;
  413. }
  414. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  415. {
  416. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", item.Result.ToUpper() == "PASS" ? "OK" :"NG", User.UserCode, out oErrorMessage))
  417. {
  418. string outMsg = "";
  419. param.Add(omakeCode);
  420. param.Add(item.SN);
  421. param.Add(User.UserSourceCode);
  422. param.Add(User.UserName);
  423. param.Add(User.CurrentStepCode);
  424. param.Add(item.Result.ToUpper());
  425. param.Add(item.TestTime);
  426. param.Add(item.Side);
  427. param.Add(equiType);
  428. details.Clear();
  429. foreach (LogItem LI in item.LogItemList)
  430. {
  431. details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
  432. }
  433. param.Add(details.ToString());
  434. param.Add(outMsg);
  435. string[] paramList = param.ToArray();
  436. dh.CallProcedure("CS_INSERT_TESTDETAILS", ref paramList);
  437. if (paramList[10].Substring(0, 2) == "OK")
  438. {
  439. LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
  440. }
  441. else
  442. {
  443. LogMessage(1, paramList[8]);
  444. }
  445. param.Clear();
  446. if (logs.IndexOf(item) == logs.Count - 1)
  447. {
  448. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
  449. return true;
  450. }
  451. }
  452. else
  453. {
  454. LogMessage(0, $"处理过站NG:{oErrorMessage}");
  455. break;
  456. }
  457. }
  458. else
  459. {
  460. LogMessage(0, $"过站核对NG:{oErrorMessage}");
  461. break;
  462. }
  463. }
  464. return false;
  465. }
  466. catch (Exception ex)
  467. {
  468. LogMessage(0, $"Error,处理解析写入: {ex.Message}");
  469. return false;
  470. }
  471. }
  472. private void ChangeWoFunc(object sender, EventArgs e)
  473. {
  474. try
  475. {
  476. sql.Clear();
  477. sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
  478. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  479. if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
  480. {
  481. ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
  482. return;
  483. }
  484. LogMessage(0, $"NG,自动识别更新工单");
  485. }
  486. catch (Exception ex)
  487. {
  488. LogMessage(0, $"Error,自动切换工单: {ex.Message}");
  489. }
  490. }
  491. private bool ConsoleLog(string Content, string PathName,string SN)
  492. {
  493. try
  494. {
  495. string sourcePaht = Path.GetDirectoryName(PathName);
  496. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  497. string newFolderName = "Logs";
  498. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  499. if (!Directory.Exists(newFolderPath))
  500. {
  501. Directory.CreateDirectory(newFolderPath);
  502. }
  503. string newFileName = "Log_" + Path.GetFileName(changeName);
  504. string newFilePath = Path.Combine(newFolderPath, newFileName);
  505. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  506. return true;
  507. }
  508. catch (Exception ex)
  509. {
  510. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  511. return false;
  512. }
  513. }
  514. private void LogMessage(int type, string message)
  515. {
  516. if (type == 0)
  517. {
  518. if (lstFiles.InvokeRequired)
  519. {
  520. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  521. return;
  522. }
  523. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  524. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  525. }
  526. else
  527. {
  528. if (lstOk.InvokeRequired)
  529. {
  530. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  531. return;
  532. }
  533. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  534. lstOk.TopIndex = lstOk.Items.Count - 1;
  535. }
  536. }
  537. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  538. {
  539. if (e.Index < 0) return;
  540. e.DrawBackground();
  541. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  542. Brush color = Brushes.Black;
  543. if (txt.Contains("NG"))
  544. {
  545. color = Brushes.Red;
  546. }
  547. else if (txt.Contains("ERROR"))
  548. {
  549. color = Brushes.Red;
  550. }
  551. else
  552. {
  553. color = Brushes.Green;
  554. }
  555. e.DrawFocusRectangle();
  556. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  557. }
  558. public bool UploadImageToFtp(string localFilePath, string Sn)
  559. {
  560. string ftpServer;
  561. ftpServer = equiType == "Xray" ? "ftp://10.8.0.215:21/xray/" : "ftp://10.8.0.215:21/ccd/";
  562. ftpServer = equiType == "Xray" ? "ftp://192.168.1.5:21/xray/" : "ftp://192.168.1.5:21/ccd/";
  563. string username = "vsftpd";
  564. string password = "vsftpd3ef41637hy";
  565. string currentDate = DateTime.Now.ToString("yyyyMMdd");
  566. string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{currentDate}";
  567. /*string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{Sn}";*/
  568. string outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
  569. if (outResult.Substring(0, 2) == "NG")
  570. {
  571. LogMessage(0, outResult);
  572. return false;
  573. }
  574. string remoteFileName = Path.GetFileName(localFilePath);
  575. string uri = $"{ftpFullPath}/{remoteFileName}";
  576. try
  577. {
  578. var request = (FtpWebRequest)WebRequest.Create(uri);
  579. request.Method = WebRequestMethods.Ftp.UploadFile;
  580. request.Credentials = new NetworkCredential(username, password);
  581. request.UsePassive = true;
  582. request.UseBinary = true;
  583. request.KeepAlive = false;
  584. using (var fileStream = File.OpenRead(localFilePath))
  585. using (var requestStream = request.GetRequestStream())
  586. {
  587. byte[] buffer = new byte[4096];
  588. int bytesRead;
  589. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  590. {
  591. requestStream.Write(buffer, 0, bytesRead);
  592. }
  593. }
  594. using (var response = (FtpWebResponse)request.GetResponse())
  595. {
  596. LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
  597. return true;
  598. }
  599. }
  600. catch (WebException ex)
  601. {
  602. if (ex.Response is FtpWebResponse response)
  603. {
  604. LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  605. }
  606. else
  607. {
  608. LogMessage(0, $"NG,Web异常: {ex.Message}");
  609. }
  610. return false;
  611. }
  612. catch (Exception ex)
  613. {
  614. LogMessage(0, $"NG,上传失败: {ex.Message}");
  615. return false;
  616. }
  617. }
  618. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  619. {
  620. try
  621. {
  622. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  623. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  624. request.Credentials = new NetworkCredential(username, password);
  625. request.UsePassive = true;
  626. request.UseBinary = true;
  627. request.KeepAlive = false;
  628. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  629. {
  630. response.Close();
  631. return "OK,目录创建成功: " + response.StatusDescription;
  632. }
  633. }
  634. catch (WebException ex)
  635. {
  636. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  637. {
  638. return "OK,目录已存在: " + response.StatusDescription;
  639. }
  640. else
  641. {
  642. return "NG,创建目录时发生错误: " + ex.Message;
  643. }
  644. }
  645. }
  646. private void Delete_Click(object sender, EventArgs e)
  647. {
  648. if (!Directory.Exists(txtPath.Text))
  649. {
  650. LogMessage(0, $"删除路径不存在: {txtPath.Text}");
  651. return;
  652. }
  653. List<string> DeleteList = new List<string>() { };
  654. DeleteList.Add("1-1_" + SN1.Text);
  655. DeleteList.Add("1-2_" + SN2.Text);
  656. DeleteList.Add("1-3_" + SN3.Text);
  657. DeleteList.Add("2-1_" + SN4.Text);
  658. DeleteList.Add("2-2_" + SN5.Text);
  659. DeleteList.Add("2-3_" + SN6.Text);
  660. string DeletePath;
  661. int DeleteCount = 0;
  662. foreach (var item in DeleteList)
  663. {
  664. DeletePath = Path.Combine(txtPath.Text, item);
  665. if (DeletePath == txtPath.Text)
  666. {
  667. LogMessage(0, $"NG,路径{DeletePath}中,没有 {item} 文件夹");
  668. continue;
  669. }
  670. if (Directory.Exists(DeletePath))
  671. {
  672. try
  673. {
  674. Directory.Delete(DeletePath);
  675. }
  676. catch (IOException ex)
  677. {
  678. LogMessage(0, $"NG,文件夹{item}存有文件,{ex.Message}");
  679. continue;
  680. }
  681. catch (Exception ex)
  682. {
  683. LogMessage(0, $"NG,删除异常,{ex.Message}");
  684. continue;
  685. }
  686. DeleteCount++;
  687. if (SN1.Text == item) SN1.Text = "";
  688. if (SN2.Text == item) SN2.Text = "";
  689. if (SN3.Text == item) SN3.Text = "";
  690. if (SN4.Text == item) SN4.Text = "";
  691. if (SN5.Text == item) SN5.Text = "";
  692. if (SN6.Text == item) SN6.Text = "";
  693. }
  694. }
  695. if(DeleteCount != 0)
  696. {
  697. LogMessage(0, $"一键删除文件夹成功,共 {DeleteCount}个");
  698. return;
  699. }
  700. else
  701. {
  702. LogMessage(0, $"NG,请扫描SN序列号删除文件夹");
  703. }
  704. }
  705. private void Clear_Click(object sender, EventArgs e)
  706. {
  707. SN1.Text = "";
  708. SN2.Text = "";
  709. SN3.Text = "";
  710. SN4.Text = "";
  711. SN5.Text = "";
  712. SN6.Text = "";
  713. SN1.Focus();
  714. SN1.SelectAll();
  715. }
  716. private void Generate_Click(object sender, EventArgs e)
  717. {
  718. if (!Directory.Exists(txtPath.Text))
  719. {
  720. LogMessage(0, $"NG,生成路径不存在: {txtPath.Text}");
  721. return;
  722. }
  723. List<string> GenerateList = new List<string>() { };
  724. GenerateList.Add("1-1_" + SN1.Text);
  725. GenerateList.Add("1-2_" + SN2.Text);
  726. GenerateList.Add("1-3_" + SN3.Text);
  727. GenerateList.Add("2-1_" + SN4.Text);
  728. GenerateList.Add("2-2_" + SN5.Text);
  729. GenerateList.Add("2-3_" + SN6.Text);
  730. string GeneratePath;
  731. int GenerateCount = 0;
  732. foreach (var item in GenerateList)
  733. {
  734. GeneratePath = Path.Combine(txtPath.Text, item);
  735. if (GeneratePath == txtPath.Text)
  736. {
  737. LogMessage(0, $"NG,请扫描SN序列号创建文件夹");
  738. continue;
  739. }
  740. if (Directory.Exists(GeneratePath))
  741. {
  742. LogMessage(0, $"NG,路径{txtPath.Text}已有{item}文件夹");
  743. continue;
  744. }
  745. Directory.CreateDirectory(GeneratePath);
  746. GenerateCount++;
  747. }
  748. if(GenerateCount != 0) LogMessage(0, $"一键生成文件夹成功,共 {GenerateCount}个");
  749. }
  750. private void SN1_KeyDown(object sender, KeyEventArgs e)
  751. {
  752. if (e.KeyCode != Keys.Enter) return;
  753. if (string.IsNullOrEmpty(SN1.Text)) return;
  754. SN2.Focus();
  755. SN2.SelectAll();
  756. }
  757. private void SN2_KeyDown(object sender, KeyEventArgs e)
  758. {
  759. if (e.KeyCode != Keys.Enter) return;
  760. if (string.IsNullOrEmpty(SN2.Text)) return;
  761. SN3.Focus();
  762. SN3.SelectAll();
  763. }
  764. private void SN3_KeyDown(object sender, KeyEventArgs e)
  765. {
  766. if (e.KeyCode != Keys.Enter) return;
  767. if (string.IsNullOrEmpty(SN3.Text)) return;
  768. SN4.Focus();
  769. SN4.SelectAll();
  770. }
  771. private void SN4_KeyDown(object sender, KeyEventArgs e)
  772. {
  773. if (e.KeyCode != Keys.Enter) return;
  774. if (string.IsNullOrEmpty(SN4.Text)) return;
  775. SN5.Focus();
  776. SN5.SelectAll();
  777. }
  778. private void SN5_KeyDown(object sender, KeyEventArgs e)
  779. {
  780. if (e.KeyCode != Keys.Enter) return;
  781. if (string.IsNullOrEmpty(SN5.Text)) return;
  782. SN6.Focus();
  783. SN6.SelectAll();
  784. }
  785. private void SN6_KeyDown(object sender, KeyEventArgs e)
  786. {
  787. if (e.KeyCode != Keys.Enter) return;
  788. if (string.IsNullOrEmpty(SN6.Text)) return;
  789. Generate.Focus();
  790. }
  791. public string CheckFileAccess(string filePath)
  792. {
  793. try
  794. {
  795. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  796. {
  797. return "OK";
  798. }
  799. }
  800. catch (IOException ex)
  801. {
  802. return "NG,文件被占用: " + ex.Message;
  803. }
  804. catch (UnauthorizedAccessException ex)
  805. {
  806. return "NG,权限不足,无法访问文件: " + ex.Message;
  807. }
  808. catch (Exception ex)
  809. {
  810. return "NG," + ex.Message;
  811. }
  812. }
  813. public string CheckFolderPermissions(string path)
  814. {
  815. try
  816. {
  817. DirectorySecurity security = Directory.GetAccessControl(path);
  818. AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
  819. WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
  820. foreach (FileSystemAccessRule rule in rules)
  821. {
  822. if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
  823. {
  824. Console.WriteLine($" {rule.IdentityReference.Value}");
  825. Console.WriteLine($"权限类型: {rule.AccessControlType}");
  826. Console.WriteLine($"具体权限: {rule.FileSystemRights}");
  827. Console.WriteLine($"是否继承: {rule.IsInherited}");
  828. }
  829. }
  830. return "OK";
  831. }
  832. catch (UnauthorizedAccessException ex)
  833. {
  834. return $"NG,无权限访问文件夹: {ex.Message}";
  835. }
  836. catch (DirectoryNotFoundException)
  837. {
  838. return "NG,文件夹不存在";
  839. }
  840. catch (Exception ex)
  841. {
  842. return "NG," + ex.Message;
  843. }
  844. }
  845. public class Log
  846. {
  847. public string SN { set; get; }
  848. public string Result { set; get; }
  849. public string TestTime { set; get; }
  850. public string Side { set; get; }
  851. public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
  852. }
  853. public class LogItem
  854. {
  855. public string Location { set; get; }
  856. public string ReelNo { set; get; }
  857. public string FirstType { set; get; }
  858. public string SceondType { set; get; }
  859. public string Name { set; get; }
  860. }
  861. }
  862. }