Make_ParseLog.cs 40 KB

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