using BarTender; using DevExpress.Utils.OAuth.Provider; using DevExpress.Xpo.Logger; using DevExpress.XtraEditors.Controls; using DevExpress.XtraExport; using DevExpress.XtraPrinting; using NPOI.SS.Formula.Functions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Security; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using System.Web.Services.Description; using System.Web.UI.WebControls; using System.Windows.Forms; using System.Xml; using UAS_MES_NEW.CustomControl.ButtonUtil; using UAS_MES_NEW.CustomControl.TextBoxWithIcon; using UAS_MES_NEW.DataOperate; using UAS_MES_NEW.Entity; using UAS_MES_NEW.PublicMethod; using static DevExpress.Xpo.DB.DataStoreLongrunnersWatch; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; namespace UAS_MES_NEW.Make { public partial class Make_ParseLog : Form { public Make_ParseLog() { InitializeComponent(); } FileSystemWatcher watcher; LogStringBuilder sql = new LogStringBuilder(); DataTable Dbfind; DataTable dt; DataHelper dh; string currFileType = "",equiType = ""; string SN, omakeCode, oMsid, oErrorMessage = ""; List fileList = new List(); Timer formsTimer; string outXmlFilePath; private void Make_ParseLog_Load(object sender, EventArgs e) { dh = SystemInf.dh; fileList.Add("C:\\Users\\MI\\Desktop"); formsTimer = new Timer(); formsTimer.Interval = 10000; formsTimer.Tick += timer1_Tick; //outXmlFilePath = "D:\\JANETSSR"; watcher = new FileSystemWatcher(); watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; watcher.Created += OnFileCreated; /*watcher.Changed += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileChanged;*/ //设置锁定工单 LockMakeCode.GetMakeCodeCtl(ma_code); ma_code.SetLockCheckBox(LockMakeCode); //工单号放大镜配置 ma_code.TableName = "make left join product on ma_prodcode=pr_code"; ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称"; ma_code.FormName = Name; ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" }; ma_code.Condition = "ma_statuscode='STARTED'"; ma_code.DbChange += Ma_code_DbChange; } private void Ma_code_DbChange(object sender, EventArgs e) { Dbfind = ma_code.ReturnData; BaseUtil.SetFormValue(this.Controls, Dbfind); //获取工单的其他信息 sql.Clear(); sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,"); sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on "); 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 + "'"); dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select"); if (dt.Rows.Count > 0) { BaseUtil.SetFormValue(this.Controls, dt); } } private void Device_SelectedIndexChanged(object sender, EventArgs e) { if (Device.SelectedIndex == -1) return; switch (Device.SelectedIndex) { case 0: currFileType = "Log"; equiType = "设备"; break; } if (string.IsNullOrEmpty(ma_code.Text)) { Device.SelectedIndex = -1; txtPath.Text = ""; MessageBox.Show(this.ParentForm, "请选择工单", "提示"); return; } txtPath.Text = fileList[Device.SelectedIndex]; txtPath.Focus(); txtPath.SelectAll(); ma_code.Enabled = true; txtPath.Enabled = false; } private void Choose_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); switch (Device.SelectedIndex) { case 0: dialog.Description = "请选择读取劲拓SPI设备文件夹"; currFileType = "Log"; equiType = "设备"; break; } if (dialog.ShowDialog() == DialogResult.OK) { txtPath.Text = dialog.SelectedPath; txtPath.Enabled = false; Device.Enabled = false; watcher.EnableRaisingEvents = false; } } private void claerBtn_Click(object sender, EventArgs e) { lstFiles.Items.Clear(); } private void allParse_Click(object sender, EventArgs e) { if (Device.SelectedIndex == 0) { if (string.IsNullOrEmpty(ma_code.Text)) { MessageBox.Show(this.ParentForm, "请选择工单", "提示"); return; } } if (Device.SelectedIndex == -1) { Device.Focus(); Device.SelectAll(); MessageBox.Show(this.ParentForm, "请选择设备", "提示"); return; } if (String.IsNullOrEmpty(txtPath.Text)) { txtPath.Focus(); txtPath.SelectAll(); return; } string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}"); if (txtFiles.Length == 0) { LogMessage($"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件"); return; } RefreshFileList(); } private void onWatch_Click(object sender, EventArgs e) { if (Device.SelectedIndex == 0) { if (string.IsNullOrEmpty(ma_code.Text)) { MessageBox.Show(this.ParentForm, "请选择工单", "提示"); return; } } if (Device.SelectedIndex == -1) { Device.Focus(); Device.SelectAll(); MessageBox.Show(this.ParentForm, "请选择设备", "提示"); return; } if (String.IsNullOrEmpty(txtPath.Text)) { txtPath.Focus(); txtPath.SelectAll(); return; } try { watcher.Path = txtPath.Text; watcher.Filter = $"*.{currFileType}"; //formsTimer.Start(); //formsTimer.Stop(); if (onWatch.Text == "开启解析") { watcher.EnableRaisingEvents = true; onWatch.Text = "关闭解析"; } else { watcher.EnableRaisingEvents = false; onWatch.Text = "开启解析"; } } catch (Exception ex) { MessageBox.Show(this.ParentForm, ex.Message, "警告"); } } private void timer1_Tick(object sender, EventArgs e) { try { sql.Clear(); sql.Append($@"SELECT dd_date,dd_name,dd_status,dd_id FROM devicedata WHERE dd_status = 0"); dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select"); if (dt.Rows.Count > 0) { string currentDate = DateTime.Now.ToString("yyyyMMddHHmmss"); string currentDate1 = DateTime.Now.ToString("yyyy-MM-dd"); XmlWriterSettings settings = new XmlWriterSettings { Indent = true //,Encoding = System.Text.Encoding.UTF8 }; foreach (DataRow dr in dt.Rows) { #region /*var hasFileAry = Directory.GetFiles(outXmlFilePath, $"*.{currFileType}"); string xmlName; if (hasFileAry.Length > 0) { var lastFile = Directory.GetFiles(outXmlFilePath).Select(f => new FileInfo(f)) .Where(f => f.CreationTime.Date == DateTime.Today) .OrderByDescending(f => f.CreationTime).FirstOrDefault().Name; string seqNumStr = lastFile.Substring(lastFile.Length - 7, 3); string fileSeqNum = (int.Parse(seqNumStr) + 1).ToString().PadLeft(seqNumStr.Length, '0'); ; xmlName = $"1.08_{currentDate}_{currentDate}{fileSeqNum}__RequestTotalProduction.xml"; } else { xmlName = $"1.08_{currentDate}_{currentDate}001__RequestTotalProduction.xml"; }*/ #endregion string xmlName = $"1.08__{currentDate1}T101505_{currentDate}001__RequestTotalProduction.xml"; string fullPath = Path.Combine(outXmlFilePath, xmlName); using (XmlWriter writer = XmlWriter.Create(fullPath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("RequestTotalProductionInfo"); writer.WriteAttributeString("MachineName", dr["dd_name"].ToString()); writer.WriteEndElement(); writer.WriteEndDocument(); } sql.Clear(); sql.Append($"UPDATE devicedata SET dd_status = -1 WHERE dd_name = '{dr["dd_name"].ToString()}' and dd_status = 0"); dh.ExecuteSql(sql.GetString(), "update"); } } } catch (Exception ex) { LogMessage($"写入指令文件异常: {ex.Message}"); } } private void OnFileCreated(object sender, FileSystemEventArgs e) { RefreshFileList(); } private void OnFileChanged(object sender, FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Changed) { RefreshFileList(); } } private void RefreshFileList() { if (lstFiles.InvokeRequired) { lstFiles.Invoke(new Action(RefreshFileList)); lstFiles.BeginInvoke(new Action(RefreshFileList)); return; } try { if (!Directory.Exists(txtPath.Text)) { LogMessage($"目录不存在: {txtPath.Text}"); return; } string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}"); if (txtFiles.Length == 0) { return; } else { foreach (string file in txtFiles) { if (!File.Exists(file)) { LogMessage($"文件不存在: {file}"); } string outFileMsg = CheckFileAccess(file); if (outFileMsg != "OK") { LogMessage(outFileMsg); continue; } if (Device.SelectedIndex == 0) // 测试设备 { ParseLogInsert(file); } } } } catch (Exception ex) { LogMessage($"Error: 解析文件列表失败: {ex.Message}"); } } private void ParseLogInsert(string PathName) { try { StreamReader SR = File.OpenText(PathName); string restOfStream = SR.ReadToEnd(); SR.Close(); SR.Dispose(); List logArr = new List() { }; string[] lines = restOfStream.Split(new string[] { "\r\n" }, StringSplitOptions.None); int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length; foreach (var item in lines) { if (string.IsNullOrEmpty(item)) continue; string[] currItem = item.Split(','); if(equiType == "设备") { string[] resultArr = currItem[0].Split('='); Log itemLog = new Log() { SN = currItem[1], Result = resultArr[1], }; logArr.Add(itemLog); } } if (InsertDb(logArr, PathName, fileNum)) { if (ConsoleLog(restOfStream, PathName)) { File.WriteAllText(PathName, string.Empty); File.Delete(PathName); } } } catch (Exception ex) { LogMessage($"Error: 文件 {PathName}, {ex.Message}"); } } private bool InsertDb(List logs, string PathName,int fileNum) { try { StringBuilder sql = new StringBuilder(); List param = new List() { }; foreach (var item in logs) { if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage)) { if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", "OK", User.UserCode, out oErrorMessage)) { string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'"; dt = (DataTable)dh.ExecuteSql(sqlStr, "select"); BaseUtil.SetFormValue(Controls, dt); //记录操作日志 LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, ""); param.Add(item.SN); string res = ""; param.Add(res); string[] paramList = param.ToArray(); dh.CallProcedure("cs_insert_testrejects", ref paramList); param.Clear(); LogMessage($"文件: {PathName},共{fileNum}条记录已过站解析"); if (logs.IndexOf(item) == logs.Count - 1) { return true; } } else { LogMessage($"处理过站NG:{oErrorMessage}"); break; } } else { LogMessage($"过站核对NG:{oErrorMessage}"); } } return false; } catch (Exception ex) { LogMessage($"处理解析写入error:{ex.Message}"); return false; } } private bool ConsoleLog(string Content, string PathName) { try { string sourceDir = Path.GetDirectoryName(PathName); string newFolderName = "Logs"; string newFolderPath = Path.Combine(sourceDir, newFolderName); if (!Directory.Exists(newFolderPath)) { Directory.CreateDirectory(newFolderPath); } string newFileName = "Log_" + Path.GetFileName(PathName); string newFilePath = Path.Combine(newFolderPath, newFileName); File.AppendAllText(newFilePath, Content + Environment.NewLine); return true; } catch (Exception ex) { MessageBox.Show(this.ParentForm, ex.Message, "警告"); return false; } } private void LogMessage(string message) { if (lstFiles.InvokeRequired) { lstFiles.Invoke(new Action(LogMessage), message); return; } lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}"); lstFiles.TopIndex = lstFiles.Items.Count - 1; } public string CheckFileAccess(string filePath) { try { using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) { return "OK"; } } catch (IOException ex) { return "文件被占用: " + ex.Message; } catch (UnauthorizedAccessException ex) { return "权限不足,无法访问文件: " + ex.Message; } catch (Exception ex) { return ex.Message; } } private class Log { public string SN { set; get; } public string Result { set; get; } } } }