Make_ParseLog.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. using BarTender;
  2. using DevExpress.Utils.OAuth.Provider;
  3. using DevExpress.Xpo.Logger;
  4. using DevExpress.XtraEditors.Controls;
  5. using DevExpress.XtraExport;
  6. using DevExpress.XtraPrinting;
  7. using NPOI.SS.Formula.Functions;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.Drawing;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Security;
  17. using System.Security.AccessControl;
  18. using System.Security.Principal;
  19. using System.Text;
  20. using System.Threading.Tasks;
  21. using System.Web.Services.Description;
  22. using System.Web.UI.WebControls;
  23. using System.Windows.Forms;
  24. using System.Xml;
  25. using UAS_MES_NEW.CustomControl.ButtonUtil;
  26. using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
  27. using UAS_MES_NEW.DataOperate;
  28. using UAS_MES_NEW.Entity;
  29. using UAS_MES_NEW.PublicMethod;
  30. using static DevExpress.Xpo.DB.DataStoreLongrunnersWatch;
  31. using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
  32. namespace UAS_MES_NEW.Make
  33. {
  34. public partial class Make_ParseLog : Form
  35. {
  36. public Make_ParseLog()
  37. {
  38. InitializeComponent();
  39. }
  40. FileSystemWatcher watcher;
  41. LogStringBuilder sql = new LogStringBuilder();
  42. DataTable Dbfind;
  43. DataTable dt;
  44. DataHelper dh;
  45. string currFileType = "",equiType = "";
  46. string SN, omakeCode, oMsid, oErrorMessage = "";
  47. List<string> fileList = new List<string>();
  48. Timer formsTimer;
  49. string outXmlFilePath;
  50. private void Make_ParseLog_Load(object sender, EventArgs e)
  51. {
  52. dh = SystemInf.dh;
  53. fileList.Add("C:\\Users\\MI\\Desktop");
  54. formsTimer = new Timer();
  55. formsTimer.Interval = 10000;
  56. formsTimer.Tick += timer1_Tick;
  57. //outXmlFilePath = "D:\\JANETSSR";
  58. watcher = new FileSystemWatcher();
  59. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  60. watcher.Created += OnFileCreated;
  61. /*watcher.Changed += OnFileChanged;
  62. watcher.Deleted += OnFileChanged;
  63. watcher.Renamed += OnFileChanged;*/
  64. //设置锁定工单
  65. LockMakeCode.GetMakeCodeCtl(ma_code);
  66. ma_code.SetLockCheckBox(LockMakeCode);
  67. //工单号放大镜配置
  68. ma_code.TableName = "make left join product on ma_prodcode=pr_code";
  69. ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称";
  70. ma_code.FormName = Name;
  71. ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" };
  72. ma_code.Condition = "ma_statuscode='STARTED'";
  73. ma_code.DbChange += Ma_code_DbChange;
  74. }
  75. private void Ma_code_DbChange(object sender, EventArgs e)
  76. {
  77. Dbfind = ma_code.ReturnData;
  78. BaseUtil.SetFormValue(this.Controls, Dbfind);
  79. //获取工单的其他信息
  80. sql.Clear();
  81. sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,");
  82. sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on ");
  83. 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 + "'");
  84. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  85. if (dt.Rows.Count > 0)
  86. {
  87. BaseUtil.SetFormValue(this.Controls, dt);
  88. }
  89. }
  90. private void Device_SelectedIndexChanged(object sender, EventArgs e)
  91. {
  92. if (Device.SelectedIndex == -1) return;
  93. switch (Device.SelectedIndex)
  94. {
  95. case 0:
  96. currFileType = "Log";
  97. equiType = "设备";
  98. break;
  99. }
  100. if (string.IsNullOrEmpty(ma_code.Text))
  101. {
  102. Device.SelectedIndex = -1;
  103. txtPath.Text = "";
  104. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  105. return;
  106. }
  107. txtPath.Text = fileList[Device.SelectedIndex];
  108. txtPath.Focus();
  109. txtPath.SelectAll();
  110. ma_code.Enabled = true;
  111. txtPath.Enabled = false;
  112. }
  113. private void Choose_Click(object sender, EventArgs e)
  114. {
  115. FolderBrowserDialog dialog = new FolderBrowserDialog();
  116. switch (Device.SelectedIndex)
  117. {
  118. case 0:
  119. dialog.Description = "请选择读取劲拓SPI设备文件夹";
  120. currFileType = "Log";
  121. equiType = "设备";
  122. break;
  123. }
  124. if (dialog.ShowDialog() == DialogResult.OK)
  125. {
  126. txtPath.Text = dialog.SelectedPath;
  127. txtPath.Enabled = false;
  128. Device.Enabled = false;
  129. watcher.EnableRaisingEvents = false;
  130. }
  131. }
  132. private void claerBtn_Click(object sender, EventArgs e)
  133. {
  134. lstFiles.Items.Clear();
  135. }
  136. private void allParse_Click(object sender, EventArgs e)
  137. {
  138. if (Device.SelectedIndex == 0)
  139. {
  140. if (string.IsNullOrEmpty(ma_code.Text))
  141. {
  142. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  143. return;
  144. }
  145. }
  146. if (Device.SelectedIndex == -1)
  147. {
  148. Device.Focus();
  149. Device.SelectAll();
  150. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  151. return;
  152. }
  153. if (String.IsNullOrEmpty(txtPath.Text))
  154. {
  155. txtPath.Focus();
  156. txtPath.SelectAll();
  157. return;
  158. }
  159. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  160. if (txtFiles.Length == 0)
  161. {
  162. LogMessage($"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  163. return;
  164. }
  165. RefreshFileList();
  166. }
  167. private void onWatch_Click(object sender, EventArgs e)
  168. {
  169. if (Device.SelectedIndex == 0)
  170. {
  171. if (string.IsNullOrEmpty(ma_code.Text))
  172. {
  173. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  174. return;
  175. }
  176. }
  177. if (Device.SelectedIndex == -1)
  178. {
  179. Device.Focus();
  180. Device.SelectAll();
  181. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  182. return;
  183. }
  184. if (String.IsNullOrEmpty(txtPath.Text))
  185. {
  186. txtPath.Focus();
  187. txtPath.SelectAll();
  188. return;
  189. }
  190. try
  191. {
  192. watcher.Path = txtPath.Text;
  193. watcher.Filter = $"*.{currFileType}";
  194. //formsTimer.Start();
  195. //formsTimer.Stop();
  196. if (onWatch.Text == "开启解析")
  197. {
  198. watcher.EnableRaisingEvents = true;
  199. onWatch.Text = "关闭解析";
  200. }
  201. else
  202. {
  203. watcher.EnableRaisingEvents = false;
  204. onWatch.Text = "开启解析";
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  210. }
  211. }
  212. private void timer1_Tick(object sender, EventArgs e)
  213. {
  214. try
  215. {
  216. sql.Clear();
  217. sql.Append($@"SELECT dd_date,dd_name,dd_status,dd_id FROM devicedata WHERE dd_status = 0");
  218. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  219. if (dt.Rows.Count > 0)
  220. {
  221. string currentDate = DateTime.Now.ToString("yyyyMMddHHmmss");
  222. string currentDate1 = DateTime.Now.ToString("yyyy-MM-dd");
  223. XmlWriterSettings settings = new XmlWriterSettings
  224. {
  225. Indent = true
  226. //,Encoding = System.Text.Encoding.UTF8
  227. };
  228. foreach (DataRow dr in dt.Rows)
  229. {
  230. #region
  231. /*var hasFileAry = Directory.GetFiles(outXmlFilePath, $"*.{currFileType}");
  232. string xmlName;
  233. if (hasFileAry.Length > 0)
  234. {
  235. var lastFile = Directory.GetFiles(outXmlFilePath).Select(f => new FileInfo(f))
  236. .Where(f => f.CreationTime.Date == DateTime.Today)
  237. .OrderByDescending(f => f.CreationTime).FirstOrDefault().Name;
  238. string seqNumStr = lastFile.Substring(lastFile.Length - 7, 3);
  239. string fileSeqNum = (int.Parse(seqNumStr) + 1).ToString().PadLeft(seqNumStr.Length, '0'); ;
  240. xmlName = $"1.08_{currentDate}_{currentDate}{fileSeqNum}__RequestTotalProduction.xml";
  241. }
  242. else
  243. {
  244. xmlName = $"1.08_{currentDate}_{currentDate}001__RequestTotalProduction.xml";
  245. }*/
  246. #endregion
  247. string xmlName = $"1.08__{currentDate1}T101505_{currentDate}001__RequestTotalProduction.xml";
  248. string fullPath = Path.Combine(outXmlFilePath, xmlName);
  249. using (XmlWriter writer = XmlWriter.Create(fullPath, settings))
  250. {
  251. writer.WriteStartDocument();
  252. writer.WriteStartElement("RequestTotalProductionInfo");
  253. writer.WriteAttributeString("MachineName", dr["dd_name"].ToString());
  254. writer.WriteEndElement();
  255. writer.WriteEndDocument();
  256. }
  257. sql.Clear();
  258. sql.Append($"UPDATE devicedata SET dd_status = -1 WHERE dd_name = '{dr["dd_name"].ToString()}' and dd_status = 0");
  259. dh.ExecuteSql(sql.GetString(), "update");
  260. }
  261. }
  262. }
  263. catch (Exception ex)
  264. {
  265. LogMessage($"写入指令文件异常: {ex.Message}");
  266. }
  267. }
  268. private void OnFileCreated(object sender, FileSystemEventArgs e)
  269. {
  270. RefreshFileList();
  271. }
  272. private void OnFileChanged(object sender, FileSystemEventArgs e)
  273. {
  274. if (e.ChangeType == WatcherChangeTypes.Changed)
  275. {
  276. RefreshFileList();
  277. }
  278. }
  279. private void RefreshFileList()
  280. {
  281. if (lstFiles.InvokeRequired)
  282. {
  283. lstFiles.Invoke(new Action(RefreshFileList));
  284. lstFiles.BeginInvoke(new Action(RefreshFileList));
  285. return;
  286. }
  287. try
  288. {
  289. if (!Directory.Exists(txtPath.Text))
  290. {
  291. LogMessage($"目录不存在: {txtPath.Text}");
  292. return;
  293. }
  294. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  295. if (txtFiles.Length == 0)
  296. {
  297. return;
  298. }
  299. else
  300. {
  301. foreach (string file in txtFiles)
  302. {
  303. if (!File.Exists(file))
  304. {
  305. LogMessage($"文件不存在: {file}");
  306. }
  307. string outFileMsg = CheckFileAccess(file);
  308. if (outFileMsg != "OK")
  309. {
  310. LogMessage(outFileMsg);
  311. continue;
  312. }
  313. if (Device.SelectedIndex == 0) // 测试设备
  314. {
  315. ParseLogInsert(file);
  316. }
  317. }
  318. }
  319. }
  320. catch (Exception ex)
  321. {
  322. LogMessage($"Error: 解析文件列表失败: {ex.Message}");
  323. }
  324. }
  325. private void ParseLogInsert(string PathName)
  326. {
  327. try
  328. {
  329. StreamReader SR = File.OpenText(PathName);
  330. string restOfStream = SR.ReadToEnd();
  331. SR.Close();
  332. SR.Dispose();
  333. List<Log> logArr = new List<Log>() { };
  334. string[] lines = restOfStream.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  335. int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
  336. foreach (var item in lines)
  337. {
  338. if (string.IsNullOrEmpty(item)) continue;
  339. string[] currItem = item.Split(',');
  340. if(equiType == "设备")
  341. {
  342. string[] resultArr = currItem[0].Split('=');
  343. Log itemLog = new Log()
  344. {
  345. SN = currItem[1],
  346. Result = resultArr[1],
  347. };
  348. logArr.Add(itemLog);
  349. }
  350. }
  351. if (InsertDb(logArr, PathName, fileNum))
  352. {
  353. if (ConsoleLog(restOfStream, PathName))
  354. {
  355. File.WriteAllText(PathName, string.Empty);
  356. File.Delete(PathName);
  357. }
  358. }
  359. }
  360. catch (Exception ex)
  361. {
  362. LogMessage($"Error: 文件 {PathName}, {ex.Message}");
  363. }
  364. }
  365. private bool InsertDb(List<Log> logs, string PathName,int fileNum)
  366. {
  367. try
  368. {
  369. StringBuilder sql = new StringBuilder();
  370. List<string> param = new List<string>() { };
  371. foreach (var item in logs)
  372. {
  373. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  374. {
  375. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", "OK", User.UserCode, out oErrorMessage))
  376. {
  377. string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  378. from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  379. where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'";
  380. dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  381. BaseUtil.SetFormValue(Controls, dt);
  382. //记录操作日志
  383. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, "");
  384. param.Add(item.SN);
  385. string res = "";
  386. param.Add(res);
  387. string[] paramList = param.ToArray();
  388. dh.CallProcedure("cs_insert_testrejects", ref paramList);
  389. param.Clear();
  390. LogMessage($"文件: {PathName},共{fileNum}条记录已过站解析");
  391. if (logs.IndexOf(item) == logs.Count - 1)
  392. {
  393. return true;
  394. }
  395. }
  396. else
  397. {
  398. LogMessage($"处理过站NG:{oErrorMessage}");
  399. break;
  400. }
  401. }
  402. else
  403. {
  404. LogMessage($"过站核对NG:{oErrorMessage}");
  405. }
  406. }
  407. return false;
  408. }
  409. catch (Exception ex)
  410. {
  411. LogMessage($"处理解析写入error:{ex.Message}");
  412. return false;
  413. }
  414. }
  415. private bool ConsoleLog(string Content, string PathName)
  416. {
  417. try
  418. {
  419. string sourceDir = Path.GetDirectoryName(PathName);
  420. string newFolderName = "Logs";
  421. string newFolderPath = Path.Combine(sourceDir, newFolderName);
  422. if (!Directory.Exists(newFolderPath))
  423. {
  424. Directory.CreateDirectory(newFolderPath);
  425. }
  426. string newFileName = "Log_" + Path.GetFileName(PathName);
  427. string newFilePath = Path.Combine(newFolderPath, newFileName);
  428. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  429. return true;
  430. }
  431. catch (Exception ex)
  432. {
  433. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  434. return false;
  435. }
  436. }
  437. private void LogMessage(string message)
  438. {
  439. if (lstFiles.InvokeRequired)
  440. {
  441. lstFiles.Invoke(new Action<string>(LogMessage), message);
  442. return;
  443. }
  444. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  445. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  446. }
  447. public string CheckFileAccess(string filePath)
  448. {
  449. try
  450. {
  451. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  452. {
  453. return "OK";
  454. }
  455. }
  456. catch (IOException ex)
  457. {
  458. return "文件被占用: " + ex.Message;
  459. }
  460. catch (UnauthorizedAccessException ex)
  461. {
  462. return "权限不足,无法访问文件: " + ex.Message;
  463. }
  464. catch (Exception ex)
  465. {
  466. return ex.Message;
  467. }
  468. }
  469. private class Log
  470. {
  471. public string SN { set; get; }
  472. public string Result { set; get; }
  473. }
  474. }
  475. }