diff --git a/CsvHelper.dll b/CsvHelper.dll new file mode 100644 index 0000000..ee33cf9 Binary files /dev/null and b/CsvHelper.dll differ diff --git a/Microsoft.Bcl.AsyncInterfaces.dll b/Microsoft.Bcl.AsyncInterfaces.dll new file mode 100644 index 0000000..6031ba1 Binary files /dev/null and b/Microsoft.Bcl.AsyncInterfaces.dll differ diff --git a/WindowsFormsApp1/MES_PLC_Control.csproj b/WindowsFormsApp1/MES_PLC_Control.csproj index 6c15e57..4bc796a 100644 --- a/WindowsFormsApp1/MES_PLC_Control.csproj +++ b/WindowsFormsApp1/MES_PLC_Control.csproj @@ -35,11 +35,15 @@ 4 + + ..\..\CsvHelper.dll + ..\packages\HslCommunication.7.0.1\lib\net451\HslCommunication.dll - - ..\packages\Microsoft.Bcl.AsyncInterfaces.6.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + + False + ..\..\Microsoft.Bcl.AsyncInterfaces.dll ..\packages\Microsoft.Bcl.TimeProvider.8.0.0\lib\net462\Microsoft.Bcl.TimeProvider.dll @@ -147,6 +151,9 @@ FLow_Insert.cs + + Form + Form @@ -237,6 +244,7 @@ MaterialScanForm.cs + @@ -266,6 +274,7 @@ + @@ -303,6 +312,9 @@ Flow_Manage.cs + + ImageDisplayForm.cs + Line_Manage.cs diff --git a/WindowsFormsApp1/MainForm.Designer.cs b/WindowsFormsApp1/MainForm.Designer.cs index 53d2471..1f1c04e 100644 --- a/WindowsFormsApp1/MainForm.Designer.cs +++ b/WindowsFormsApp1/MainForm.Designer.cs @@ -52,6 +52,7 @@ namespace WindowsFormsApp1 this.压力曲线设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.系统参数配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.材料扫码ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.图片展示ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox4 = new System.Windows.Forms.GroupBox(); @@ -137,7 +138,8 @@ namespace WindowsFormsApp1 this.mES接口配置ToolStripMenuItem, this.扫码枪配置ToolStripMenuItem, this.系统参数配置ToolStripMenuItem, - this.材料扫码ToolStripMenuItem}); + this.材料扫码ToolStripMenuItem, + this.图片展示ToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Padding = new System.Windows.Forms.Padding(8, 2, 0, 2); @@ -293,6 +295,15 @@ namespace WindowsFormsApp1 this.材料扫码ToolStripMenuItem.Size = new System.Drawing.Size(166, 45); this.材料扫码ToolStripMenuItem.Text = "材料扫码"; this.材料扫码ToolStripMenuItem.Click += new System.EventHandler(this.材料扫码ToolStripMenuItem_Click); + + // + // 图片展示ToolStripMenuItem + // + this.图片展示ToolStripMenuItem.Name = "图片展示ToolStripMenuItem"; + this.图片展示ToolStripMenuItem.Size = new System.Drawing.Size(166, 45); + this.图片展示ToolStripMenuItem.Text = "图片展示"; + this.图片展示ToolStripMenuItem.Click += new System.EventHandler(this.图片展示ToolStripMenuItem_Click); + // // tableLayoutPanel1 // @@ -1167,6 +1178,7 @@ namespace WindowsFormsApp1 private System.Windows.Forms.Label linename; private System.Windows.Forms.Label 剩余寿命; private System.Windows.Forms.Button 胶水上下线; + private System.Windows.Forms.ToolStripMenuItem 图片展示ToolStripMenuItem; } } diff --git a/WindowsFormsApp1/MainForm.cs b/WindowsFormsApp1/MainForm.cs index c1d463a..ebb839f 100644 --- a/WindowsFormsApp1/MainForm.cs +++ b/WindowsFormsApp1/MainForm.cs @@ -118,6 +118,10 @@ namespace WindowsFormsApp1 continue; } + + LOT号.Text = PlcData.Read_MaterialCode0; + Tray盘二维码.Text = PlcData.Read_MaterialCode1; + DateTime Plc_Time = DateTime.Now; //PLC链接状态.Text = "PLC链接状态:OK"; @@ -128,7 +132,7 @@ namespace WindowsFormsApp1 ApiClient apiClient = new ApiClient(); otherdata otherdata = new otherdata(); - + Init.SN = PlcData.Read_MaterialCode0; #region 机台状态及报警 //机台状态 //机台状态.Text = "机台状态:" + Enum.GetName(typeof(plcstatus), Init.Plcstatus); @@ -361,13 +365,13 @@ namespace WindowsFormsApp1 #endregion #region 判断物料调用次数 固化站 - if (Init.t_Line.lineremark1 == "Curing") + if (Init.t_Line.lineremark2 == "Curing") { SQLiteHelper materialCallHelper = new SQLiteHelper(); - string materialId = PlcData.Read_MaterialCode1; + string materialId = PlcData.Read_MaterialCode0; bool shouldCallApi = false; - var materialCall = materialCallHelper.Query(m => m.materialid == materialId).Data.FirstOrDefault(); + var materialCall = materialCallHelper.QuerySingle(m => m.materialid == materialId).Data; if (materialCall == null) { // 首次进站,需要调用接口 @@ -384,7 +388,10 @@ namespace WindowsFormsApp1 materialCall.checkin1 = DateTime.Now; shouldCallApi = true; } - else if (!materialCall.checkout3.HasValue && nowinterface.code.Contains("Checkout")) + else if (!materialCall.checkout3.HasValue + && materialCall.checkout2.HasValue + && materialCall.checkout1.HasValue + && nowinterface.code.Contains("Checkout")) { // 第三次出站,需要调用接口 materialCall.checkout3 = DateTime.Now; @@ -715,6 +722,12 @@ namespace WindowsFormsApp1 materialScanForm.Show(); } + private void 图片展示ToolStripMenuItem_Click(object sender, EventArgs e) + { + ImageDisplayForm displayForm = new ImageDisplayForm(); + displayForm.Show(); + } + private void pLC通讯设置ToolStripMenuItem_Click(object sender, EventArgs e) { Plc_Manage pLC_Manage = new Plc_Manage(); diff --git a/WindowsFormsApp1/Program.cs b/WindowsFormsApp1/Program.cs index bf5ae90..6b8791d 100644 --- a/WindowsFormsApp1/Program.cs +++ b/WindowsFormsApp1/Program.cs @@ -68,5 +68,7 @@ namespace WindowsFormsApp1 //其他线程获取的气密参数 public static Airtight airtight = new Airtight(); + + public static string SN { get; set; } } } diff --git a/WindowsFormsApp1/form/ImageDisplayForm.cs b/WindowsFormsApp1/form/ImageDisplayForm.cs new file mode 100644 index 0000000..3e6d81f --- /dev/null +++ b/WindowsFormsApp1/form/ImageDisplayForm.cs @@ -0,0 +1,517 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using System.ComponentModel; +using System.IO; +using WindowsFormsApp1.mod; +using WindowsFormsApp1.db; + +namespace WindowsFormsApp1 +{ + public partial class ImageDisplayForm : Form + { + protected PictureBox pictureBox; + protected Button btnLoadImage; + protected TextBox txtX; + protected TextBox txtY; + protected TextBox txtName; + protected TextBox txtPosition; + protected Button btnSave; + protected Panel panel; + protected Label lblX; + protected Label lblY; + protected Label lblName; + protected Label lblPosition; + + private Bitmap originalImage; + private Bitmap markedImage; + private Timer blinkTimer; + private bool isBlinking = false; + private IContainer components = null; + private string currentName = ""; + private string currentPosition = ""; + private Timer autoUpdateTimer; + + public ImageDisplayForm() + { + InitializeComponent(); + SetCurrentName("123"); + + // 初始化自动更新定时器 + autoUpdateTimer = new Timer(); + autoUpdateTimer.Interval = 10000; + autoUpdateTimer.Tick += new EventHandler(AutoUpdateTimer_Tick); + autoUpdateTimer.Start(); + } + + // 设置当前名称的方法,可以从外部调用 + public void SetCurrentName(string name) + { + currentName = name; + LoadImageByName(name); + } + + // 根据名称加载图片 + private void LoadImageByName(string name) + { + if (string.IsNullOrEmpty(name)) + return; + + string imagesFolder = Path.Combine(Application.StartupPath, "images"); + + // 检查目录是否存在 + if (!Directory.Exists(imagesFolder)) + { + MessageBox.Show($"图片目录不存在: {imagesFolder}"); + return; + } + + // 获取目录中所有文件 + string[] files = Directory.GetFiles(imagesFolder); + + // 查找文件名以指定名称开头的文件 + string imagePath = null; + foreach (string file in files) + { + string fileName = Path.GetFileNameWithoutExtension(file); + if (fileName.Equals(name, StringComparison.OrdinalIgnoreCase)) + { + imagePath = file; + break; + } + } + + if (!string.IsNullOrEmpty(imagePath)) + { + try + { + // 停止闪烁定时器并重置状态 + blinkTimer?.Stop(); + isBlinking = false; + + // 加载新图片 + originalImage = new Bitmap(imagePath); + markedImage = new Bitmap(originalImage); + pictureBox.Image = markedImage; + txtName.Text = name; + } + catch (Exception ex) + { + MessageBox.Show($"加载图片失败:{ex.Message}"); + } + } + else + { + MessageBox.Show($"未找到名称为 {name} 的图片"); + } + } + + // 自动更新定时器事件 + private void AutoUpdateTimer_Tick(object sender, EventArgs e) + { + // 这里应该从某处获取当前位置变量 + string newPosition = GetCurrentPosition(); + + if (newPosition != currentPosition || (string.IsNullOrEmpty(currentPosition) && !string.IsNullOrEmpty(newPosition))) + { + currentPosition = newPosition; + txtPosition.Text = currentPosition; + + // 如果名称和位置都有值,则查询坐标并标注 + if (!string.IsNullOrEmpty(currentName) && !string.IsNullOrEmpty(currentPosition)) + { + QueryAndMarkPosition(currentName, currentPosition); + } + } + } + + // 获取当前位置的方法(需要根据实际情况实现) + private string GetCurrentPosition() + { + // 生成1-10的随机数 + Random random = new Random(); + int position = random.Next(1, 11); // 1到10之间的随机数 + return position.ToString(); + } + + // 根据名称和位置查询坐标并标注 + private void QueryAndMarkPosition(string name, string position) + { + try + { + SQLiteHelper sQLiteHelper_position = new db.SQLiteHelper(); + var positions = sQLiteHelper_position.Query(x => x.name == name + && x.position == position).Data; + + if (positions != null && positions.Count > 0) + { + var pos = positions[0]; + // 更新坐标文本框 + txtX.Text = pos.x.ToString(); + txtY.Text = pos.y.ToString(); + + // 标记位置 + if (originalImage != null) + { + DrawMark(pos.x, pos.y); + isBlinking = true; + blinkTimer.Start(); + } + } + } + catch (Exception ex) + { + // 记录错误但不显示消息框,避免频繁弹窗 + Console.WriteLine($"查询坐标失败:{ex.Message}"); + } + } + + private void DrawMark(int x, int y) + { + markedImage = new Bitmap(originalImage); + using (Graphics g = Graphics.FromImage(markedImage)) + { + if (isBlinking) + { + // 绘制放大加粗的红色感叹号 + using (Brush brush = new SolidBrush(Color.Red)) + using (Pen pen = new Pen(Color.Red, 4)) // 加粗线条 + { + // 放大的感叹号圆点 + g.FillEllipse(brush, x - 6, y + 8, 12, 12); + // 放大的感叹号竖线 + g.DrawLine(pen, x, y - 20, x, y); + } + } + } + pictureBox.Image = markedImage; + } + + private void BlinkTimer_Tick(object sender, EventArgs e) + { + isBlinking = !isBlinking; + if (!int.TryParse(txtX.Text, out int x) || !int.TryParse(txtY.Text, out int y)) + return; + DrawMark(x, y); + } + + private void PictureBox_Click(object sender, EventArgs e) + { + if (originalImage == null || !(e is MouseEventArgs me)) + return; + + // 获取图片在 PictureBox 中的实际显示尺寸和位置 + float ratioX = (float)originalImage.Width / pictureBox.ClientSize.Width; + float ratioY = (float)originalImage.Height / pictureBox.ClientSize.Height; + float ratio = Math.Max(ratioX, ratioY); + + float imageWidth = originalImage.Width / ratio; + float imageHeight = originalImage.Height / ratio; + + // 计算图片在 PictureBox 中的显示位置 + float imageX = (pictureBox.ClientSize.Width - imageWidth) / 2; + float imageY = (pictureBox.ClientSize.Height - imageHeight) / 2; + + // 将点击坐标转换为图片实际坐标 + int x = (int)((me.X - imageX) * ratio); + int y = (int)((me.Y - imageY) * ratio); + + // 确保坐标在图片范围内 + if (x >= 0 && x < originalImage.Width && y >= 0 && y < originalImage.Height) + { + txtX.Text = x.ToString(); + txtY.Text = y.ToString(); + BtnMark_Click(sender, e); // 自动标记位置 + } + } + + private void BtnLoadImage_Click(object sender, EventArgs e) + { + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp|所有文件|*.*"; + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + // 停止闪烁定时器并重置状态 + blinkTimer?.Stop(); + isBlinking = false; + + originalImage = new Bitmap(openFileDialog.FileName); + markedImage = new Bitmap(originalImage); + pictureBox.Image = markedImage; + } + } + } + + private void BtnMark_Click(object sender, EventArgs e) + { + if (markedImage == null || !int.TryParse(txtX.Text, out int x) || !int.TryParse(txtY.Text, out int y)) + { + MessageBox.Show("请先加载图片并输入有效的坐标值"); + return; + } + + DrawMark(x, y); + isBlinking = true; + blinkTimer.Start(); + } + + private void BtnSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrWhiteSpace(txtName.Text) || + string.IsNullOrWhiteSpace(txtPosition.Text) || + string.IsNullOrWhiteSpace(txtX.Text) || + string.IsNullOrWhiteSpace(txtY.Text)) + { + MessageBox.Show("请填写完整信息"); + return; + } + + // 添加坐标值验证 + if (!int.TryParse(txtX.Text, out int x) || !int.TryParse(txtY.Text, out int y)) + { + MessageBox.Show("坐标值必须是有效的数字"); + return; + } + + // 检查图片是否已加载 + if (originalImage == null) + { + MessageBox.Show("请先加载图片"); + return; + } + + // 检查坐标是否在图片范围内 + if (x <= 0 || y <= 0 || x >= originalImage.Width || y >= originalImage.Height) + { + MessageBox.Show($"坐标值超出范围!\n有效范围:X(1-{originalImage.Width}) Y(1-{originalImage.Height})"); + return; + } + + try + { + SQLiteHelper sQLiteHelper_position = new db.SQLiteHelper(); + t_imageposition position = new t_imageposition + { + name = txtName.Text, + position = txtPosition.Text, + x = int.Parse(txtX.Text), + y = int.Parse(txtY.Text), + createtime = DateTime.Now + }; + + var result = sQLiteHelper_position.Insert(position); + if (result.Success) + { + MessageBox.Show("保存成功!"); + // 清空输入框 + //txtName.Text = ""; + txtPosition.Text = ""; + } + else + { + MessageBox.Show($"保存失败"); + } + } + catch (Exception ex) + { + MessageBox.Show($"保存失败:{ex.Message}"); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + blinkTimer?.Stop(); + blinkTimer?.Dispose(); + autoUpdateTimer?.Stop(); + autoUpdateTimer?.Dispose(); + originalImage?.Dispose(); + markedImage?.Dispose(); + components?.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.panel = new System.Windows.Forms.Panel(); + this.btnLoadImage = new System.Windows.Forms.Button(); + this.txtX = new System.Windows.Forms.TextBox(); + this.txtY = new System.Windows.Forms.TextBox(); + this.txtName = new System.Windows.Forms.TextBox(); + this.txtPosition = new System.Windows.Forms.TextBox(); + this.btnSave = new System.Windows.Forms.Button(); + this.lblX = new System.Windows.Forms.Label(); + this.lblY = new System.Windows.Forms.Label(); + this.lblName = new System.Windows.Forms.Label(); + this.lblPosition = new System.Windows.Forms.Label(); + this.pictureBox = new System.Windows.Forms.PictureBox(); + this.blinkTimer = new System.Windows.Forms.Timer(this.components); + this.panel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.SuspendLayout(); + // + // panel + // + this.panel.Controls.Add(this.btnLoadImage); + this.panel.Controls.Add(this.txtX); + this.panel.Controls.Add(this.txtY); + this.panel.Controls.Add(this.txtName); + this.panel.Controls.Add(this.txtPosition); + this.panel.Controls.Add(this.btnSave); + this.panel.Controls.Add(this.lblX); + this.panel.Controls.Add(this.lblY); + this.panel.Controls.Add(this.lblName); + this.panel.Controls.Add(this.lblPosition); + this.panel.Dock = System.Windows.Forms.DockStyle.Top; + this.panel.Location = new System.Drawing.Point(0, 0); + this.panel.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.panel.Name = "panel"; + this.panel.Size = new System.Drawing.Size(1600, 125); + this.panel.TabIndex = 0; + // + // btnLoadImage + // + this.btnLoadImage.Location = new System.Drawing.Point(20, 21); + this.btnLoadImage.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.btnLoadImage.Name = "btnLoadImage"; + this.btnLoadImage.Size = new System.Drawing.Size(200, 62); + this.btnLoadImage.TabIndex = 0; + this.btnLoadImage.Text = "加载图片"; + this.btnLoadImage.UseVisualStyleBackColor = true; + this.btnLoadImage.Click += new System.EventHandler(this.BtnLoadImage_Click); + // + // txtX + // + this.txtX.Location = new System.Drawing.Point(240, 21); + this.txtX.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.txtX.Name = "txtX"; + this.txtX.Size = new System.Drawing.Size(116, 31); + this.txtX.TabIndex = 1; + this.txtX.Text = "0"; + // + // txtY + // + this.txtY.Location = new System.Drawing.Point(380, 21); + this.txtY.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.txtY.Name = "txtY"; + this.txtY.Size = new System.Drawing.Size(116, 31); + this.txtY.TabIndex = 2; + this.txtY.Text = "0"; + // + // txtName + // + this.txtName.Location = new System.Drawing.Point(740, 21); + this.txtName.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.txtName.Name = "txtName"; + this.txtName.Size = new System.Drawing.Size(196, 31); + this.txtName.TabIndex = 4; + // + // txtPosition + // + this.txtPosition.Location = new System.Drawing.Point(960, 21); + this.txtPosition.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.txtPosition.Name = "txtPosition"; + this.txtPosition.Size = new System.Drawing.Size(196, 31); + this.txtPosition.TabIndex = 5; + // + // btnSave + // + this.btnSave.Location = new System.Drawing.Point(1180, 21); + this.btnSave.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.btnSave.Name = "btnSave"; + this.btnSave.Size = new System.Drawing.Size(200, 62); + this.btnSave.TabIndex = 6; + this.btnSave.Text = "保存"; + this.btnSave.UseVisualStyleBackColor = true; + this.btnSave.Click += new System.EventHandler(this.BtnSave_Click); + // + // lblX + // + this.lblX.AutoSize = true; + this.lblX.ForeColor = System.Drawing.Color.Gray; + this.lblX.Location = new System.Drawing.Point(240, 83); + this.lblX.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); + this.lblX.Name = "lblX"; + this.lblX.Size = new System.Drawing.Size(68, 25); + this.lblX.TabIndex = 7; + this.lblX.Text = "X坐标"; + // + // lblY + // + this.lblY.AutoSize = true; + this.lblY.ForeColor = System.Drawing.Color.Gray; + this.lblY.Location = new System.Drawing.Point(380, 83); + this.lblY.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); + this.lblY.Name = "lblY"; + this.lblY.Size = new System.Drawing.Size(69, 25); + this.lblY.TabIndex = 8; + this.lblY.Text = "Y坐标"; + // + // lblName + // + this.lblName.AutoSize = true; + this.lblName.ForeColor = System.Drawing.Color.Gray; + this.lblName.Location = new System.Drawing.Point(740, 83); + this.lblName.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); + this.lblName.Name = "lblName"; + this.lblName.Size = new System.Drawing.Size(117, 25); + this.lblName.TabIndex = 9; + this.lblName.Text = "请输入名称"; + // + // lblPosition + // + this.lblPosition.AutoSize = true; + this.lblPosition.ForeColor = System.Drawing.Color.Gray; + this.lblPosition.Location = new System.Drawing.Point(960, 83); + this.lblPosition.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); + this.lblPosition.Name = "lblPosition"; + this.lblPosition.Size = new System.Drawing.Size(117, 25); + this.lblPosition.TabIndex = 10; + this.lblPosition.Text = "请输入位置"; + // + // pictureBox + // + this.pictureBox.BackColor = System.Drawing.Color.LightGray; + this.pictureBox.Cursor = System.Windows.Forms.Cursors.Cross; + this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.pictureBox.Location = new System.Drawing.Point(0, 125); + this.pictureBox.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.pictureBox.Name = "pictureBox"; + this.pictureBox.Size = new System.Drawing.Size(1600, 1125); + this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + this.pictureBox.TabIndex = 1; + this.pictureBox.TabStop = false; + this.pictureBox.Click += new System.EventHandler(this.PictureBox_Click); + // + // blinkTimer + // + this.blinkTimer.Interval = 500; + this.blinkTimer.Tick += new System.EventHandler(this.BlinkTimer_Tick); + // + // ImageDisplayForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1600, 1250); + this.Controls.Add(this.pictureBox); + this.Controls.Add(this.panel); + this.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); + this.Name = "ImageDisplayForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "图片展示"; + this.panel.ResumeLayout(false); + this.panel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/form/ImageDisplayForm.resx b/WindowsFormsApp1/form/ImageDisplayForm.resx new file mode 100644 index 0000000..522c832 --- /dev/null +++ b/WindowsFormsApp1/form/ImageDisplayForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/WindowsFormsApp1/form/ScanForm_DZ.cs b/WindowsFormsApp1/form/ScanForm_DZ.cs index 1a34bcd..0f17c7b 100644 --- a/WindowsFormsApp1/form/ScanForm_DZ.cs +++ b/WindowsFormsApp1/form/ScanForm_DZ.cs @@ -14,6 +14,7 @@ using WindowsFormsApp1.mod; using WindowsFormsApp1.mod.database; using WindowsFormsApp1.mod.server; using WindowsFormsApp1.server; +using static SQLite.SQLite3; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace WindowsFormsApp1 @@ -97,7 +98,7 @@ namespace WindowsFormsApp1 端子1.Text = barcode; })); var result = ApiClient.CallFunctionByName("SN_FeedingCheck", PlcData, new otherdata() { JS_SN = barcode }); - if (result.Success) + if (result.Success && result.Mesresult == mesresult.PASS) { this.Invoke(new Action(() => { @@ -105,7 +106,7 @@ namespace WindowsFormsApp1 })); //继续调用接口 var result2 = ApiClient.CallFunctionByName("Link_Comp", PlcData, new otherdata() { JS_SN = barcode }); - if (result2.Success) + if (result2.Success && result2.Mesresult == mesresult.PASS) { this.Invoke(new Action(() => { @@ -143,7 +144,7 @@ namespace WindowsFormsApp1 端子2.Text = barcode; })); var result = ApiClient.CallFunctionByName("SN_FeedingCheck", PlcData, new otherdata() { JS_SN = barcode }); - if (result.Success) + if (result.Success && result.Mesresult == mesresult.PASS) { this.Invoke(new Action(() => { @@ -152,7 +153,7 @@ namespace WindowsFormsApp1 //继续调用接口 var result2 = ApiClient.CallFunctionByName("Link_Comp", PlcData, new otherdata() { JS_SN = barcode }); - if (result2.Success) + if (result2.Success && result2.Mesresult == mesresult.PASS) { this.Invoke(new Action(() => { @@ -191,7 +192,7 @@ namespace WindowsFormsApp1 端子3.Text = barcode; })); var result = ApiClient.CallFunctionByName("SN_FeedingCheck", PlcData, new otherdata() { JS_SN = barcode }); - if (result.Success) + if (result.Success && result.Mesresult == mesresult.PASS) { this.Invoke(new Action(() => { @@ -199,7 +200,7 @@ namespace WindowsFormsApp1 })); var result2 = ApiClient.CallFunctionByName("Link_Comp", PlcData, new otherdata() { JS_SN = barcode }); - if (result2.Success) + if (result2.Success && result2.Mesresult == mesresult.PASS) { this.Invoke(new Action(() => { diff --git a/WindowsFormsApp1/mod/database/t_imageposition.cs b/WindowsFormsApp1/mod/database/t_imageposition.cs new file mode 100644 index 0000000..8c120be --- /dev/null +++ b/WindowsFormsApp1/mod/database/t_imageposition.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SQLite; + +namespace WindowsFormsApp1.mod +{ + public class t_imageposition + { + [PrimaryKey, AutoIncrement] + public int id { get; set; } + public string name { get; set; } + public string position { get; set; } + public int x { get; set; } + public int y { get; set; } + public DateTime createtime { get; set; } + } +} \ No newline at end of file diff --git a/WindowsFormsApp1/mod/server/otherdata.cs b/WindowsFormsApp1/mod/server/otherdata.cs index 0dc5649..70401c9 100644 --- a/WindowsFormsApp1/mod/server/otherdata.cs +++ b/WindowsFormsApp1/mod/server/otherdata.cs @@ -28,6 +28,11 @@ namespace WindowsFormsApp1.mod.server /// public string JS_SN { get; set; } + /// + /// 前端返回的扫码 + /// + public string SN { get; set; } + /// /// 螺丝枪扭力 /// diff --git a/WindowsFormsApp1/server/ApiClient.cs b/WindowsFormsApp1/server/ApiClient.cs index c0f4af1..12f5dad 100644 --- a/WindowsFormsApp1/server/ApiClient.cs +++ b/WindowsFormsApp1/server/ApiClient.cs @@ -19,6 +19,7 @@ using HslCommunication.BasicFramework; using System.IO; using static WindowsFormsApp1.server.ApiClient; using System.Security.Policy; +using System.Diagnostics; namespace WindowsFormsApp1.server { @@ -54,7 +55,12 @@ namespace WindowsFormsApp1.server _opID = Init.t_User.username; + // 初始化 CsvLogger + CsvLogger.Initialize("D:/Logs/logs.csv"); + // 设置自定义表头 + //var customHeaders = new List { "SN", "值1", "消息", "异常" }; + //CsvLogger.SetHeaders(customHeaders); //线别.Text = "线别:" + Init.t_Line.linename; //段别.Text = "段别:" + Init.t_Line.linemode; //机台编号.Text = "机台编号:" + Init.t_Line.linecode; @@ -74,34 +80,34 @@ namespace WindowsFormsApp1.server try { // 测试 - LogExecute.logNet.WriteDebug($"{eventName} 接口请求模拟测试成功\n请求:{jsonPayload}"); + //LogExecute.logNet.WriteDebug($"{eventName} 接口请求模拟测试成功\n请求:{jsonPayload}"); // 回写对应PLC - if (statusCode > 0) - PlcData.Write_Status = (short)statusCode; - if (eventName == "SN_Release") - PlcData.Write_stSN = "testsn"; - if(eventName == "Glue_CheckOut") - { - var station = Init.t_Line.lineremark2.ToLower(); - switch (station) - { - case "potting"://灌胶 - case "thermalpaste"://点胶&CCD检测 - case "uvcoating"://三防漆涂覆 - case "sealant"://点密封胶&CCD - var power = Init.t_Keyvalues.First(x => x.key == "Power"); - power.value = DateTime.Now.Millisecond.ToString(); - SQLiteHelper kvHelper = new db.SQLiteHelper(); - kvHelper.Update(power); + //if (statusCode > 0) + // PlcData.Write_Status = (short)statusCode; + //if (eventName == "SN_Release") + // PlcData.Write_stSN = "testsn"; + //if(eventName == "Glue_CheckOut") + //{ + // var station = Init.t_Line.lineremark2.ToLower(); + // switch (station) + // { + // case "potting"://灌胶 + // case "thermalpaste"://点胶&CCD检测 + // case "uvcoating"://三防漆涂覆 + // case "sealant"://点密封胶&CCD + // var power = Init.t_Keyvalues.First(x => x.key == "Power"); + // power.value = DateTime.Now.Millisecond.ToString(); + // SQLiteHelper kvHelper = new db.SQLiteHelper(); + // kvHelper.Update(power); - break; - } - } - return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now); + // break; + // } + //} + //return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now); - #region 测试不用 - /* + #region MES交互 + var response = _httpClient.PostAsync(url, httpContent).Result; // 检查响应状态码 if (response.IsSuccessStatusCode) @@ -129,6 +135,23 @@ namespace WindowsFormsApp1.server PlcData.Write_Status = (short)statusCode; if (eventName == "SN_Release") PlcData.Write_stSN = res.SN.Value; + if (eventName == "SN_FeedingCheck") + { + var station = Init.t_Line.lineremark2.ToLower(); + switch (station) + { + case "potting"://灌胶 + case "thermalpaste"://点胶&CCD检测 + case "uvcoating"://三防漆涂覆 + case "sealant"://点密封胶&CCD + var power = Init.t_Keyvalues.First(x => x.key == "Power"); + power.value = res.SN.Value.ToString(); + SQLiteHelper kvHelper = new db.SQLiteHelper(); + kvHelper.Update(power); + + break; + } + } } else { @@ -139,8 +162,8 @@ namespace WindowsFormsApp1.server } } return result - ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) - : ApiFormResult.Sucess(mesresult.FAIL, true, res.MSG.Value, PlcData, DateTime.Now); + ? ApiFormResult.Sucess(mesresult.PASS, false, res.Msg.Value, PlcData, DateTime.Now) + : ApiFormResult.Sucess(mesresult.FAIL, true, res.Msg.Value, PlcData, DateTime.Now); } else if (res.IsSuccess != null) // 打印 mes不返回result { @@ -148,8 +171,8 @@ namespace WindowsFormsApp1.server if (statusCode > 0) PlcData.Write_Status = (short)statusCode; return res.IsSuccess.Value == true - ? ApiFormResult.Sucess(mesresult.PASS, true, res.MSG?.Value ?? "", PlcData, DateTime.Now) - : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG?.Value ?? "", PlcData, DateTime.Now); + ? ApiFormResult.Sucess(mesresult.PASS, true, res.Msg?.Value ?? "", PlcData, DateTime.Now) + : ApiFormResult.Sucess(mesresult.FAIL, false, res.Msg?.Value ?? "", PlcData, DateTime.Now); } } } @@ -157,7 +180,7 @@ namespace WindowsFormsApp1.server { throw new Exception($"请求失败,状态码:{response.StatusCode}"); } - */ + #endregion 测试不用 } catch (Exception ex) @@ -223,6 +246,23 @@ namespace WindowsFormsApp1.server /// public ApiFormResult SN_FeedingCheck(string url, plcdata PlcData, otherdata OtherData) { + //判断是否为胶水站,是查询materialscan中上线的胶水码 + var station = Init.t_Line.lineremark2.ToLower(); + switch (station) + { + case "potting"://灌胶 + case "thermalpaste"://点胶&CCD检测 + case "uvcoating"://三防漆涂覆 + case "sealant"://点密封胶&CCD + SQLiteHelper glueHelper = new db.SQLiteHelper(); + var glue = glueHelper.QuerySingle(x => x.isonline); + if (glue.Success) + { + OtherData.JS_SN = glue.Data.scancode; + OtherData.locationindex = int.Parse(glue.Data.position); + } + break; + } // 组装 request json var request = new { @@ -233,7 +273,7 @@ namespace WindowsFormsApp1.server OPID = _opID, Token = _token, FixSN = _fixsn, - SN = OtherData.JS_SN,//扫码 + SN = OtherData.JS_SN??"test",//扫码 SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") }; @@ -241,12 +281,13 @@ namespace WindowsFormsApp1.server if (result.Success && result.Mesresult != mesresult.PASS) { // 判断是否是胶水站,FAIL 直接下线 todo - return CallFunctionByName("Glue_CheckOut", PlcData, OtherData); - } - else - { - return result; + if ("Potting,ThermalPaste,Sel_Soldering,UVCoating,Sealant".Contains(station)) + { + OtherData.opindex = 2; + return CallFunctionByName("Glue_CheckOut", PlcData, OtherData); + } } + return result; } /// @@ -275,7 +316,7 @@ namespace WindowsFormsApp1.server Qty = "1" } }, - SN = OtherData.JS_SN, + SN = Init.SN, SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") }; @@ -301,8 +342,8 @@ namespace WindowsFormsApp1.server OPID = _opID, Token = _token, FixSN = _fixsn, - SN = OtherData.JS_SN, - CarrierID = "", + SN = Init.ScanString, + CarrierID = PlcData.Read_MaterialCode1, SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") }; // 特殊处理:需要设置Write_stSN @@ -331,7 +372,7 @@ namespace WindowsFormsApp1.server case "sealant"://点密封胶&CCD break; default: - fixsn_1 = "CompPN"; + fixsn_1 = "CompSN"; locationindex = OtherData.locationindex; break; } @@ -369,9 +410,31 @@ namespace WindowsFormsApp1.server StationID = _stationID, MachineID = _machineID, OPID = _opID, - SN = OtherData.JS_SN, + SN = OtherData.JS_SN ?? PlcData.Read_MaterialCode0 ?? "test", + CarrierID = PlcData.Read_MaterialCode1, + DC_INFO = new List(), + CompList = new List(), SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") }; + request.CompList.Add(new CompListItem + { + CompID = "", + Qty = "1" + }); + var station = Init.t_Line.lineremark2.ToLower(); + if (station == "vacuum") + { + // 抽真空 + foreach(var val in OtherData.FinalPressureCurve.Where(x => x > 0)) + { + request.DC_INFO.Add(new DCInfoItem + { + Item = "Chamber_Pressure", + Value = val.ToString() + }); + } + } + // 扭力 读马头服务器 todo return CallApi(url, request, "Data_Collection", PlcData, PLC_Status.Data_Collection); } @@ -427,12 +490,117 @@ namespace WindowsFormsApp1.server var time = DateTime.Now.ToString("HHmmss"); var result = PlcData.Read_Result == 1 ? "OK" : "NG"; - var sourceDirectory = @""; - var targetDirectory = $"{OtherData.FileUploadAddress}\\{_line.Substring(0, 2)}\\{month}\\{day}\\line{_line.Substring(_line.Length - 2)}\\{_stationID}\\{_machineID}\\{result}"; - var fileName = $"{month}{day}_{_stationID}_{result}_{PlcData.Write_stSN}_{monthDay}_{time}_{_machineID}_Original01.png"; + OtherData.FileUploadAddress = @"W:\\"; + var sourceDirectory = @"D:\\"; + var targetDirectory = $"{OtherData.FileUploadAddress}{_line.Substring(0, 2)}\\{month}\\{day}\\Line{_line.Substring(_line.Length - 2)}\\{_stationID}\\{_machineID}\\{result}"; + var fileName = ""; + + try + { + string[] sourceFolders = OtherData.FileUploadAddress.Split(';'); // 使用分号分隔多个源文件夹 + string targetFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadFiles"); + List fileList = new List(); + string snNumber = PlcData.Read_MaterialCode0; + + if (string.IsNullOrEmpty(snNumber)) + { + LogExecute.logNet.WriteError("SN号为空,无法处理文件"); + return ApiFormResult.Error(mesresult.FAIL, false, "SN号为空", PlcData, DateTime.Now); + } + + if (!Directory.Exists(targetFolder)) + { + Directory.CreateDirectory(targetFolder); + } + + foreach (string sourceFolder in sourceFolders) + { + if (Directory.Exists(sourceFolder.Trim())) + { + string[] files = Directory.GetFiles(sourceFolder.Trim()); + foreach (string file in files) + { + string fileName1 = Path.GetFileName(file); + if (!fileName1.Contains(snNumber)) + { + continue; + } + + string targetPath = Path.Combine(targetFolder, fileName); + File.Copy(file, targetPath, true); + fileList.Add(fileName); + LogExecute.logNet.WriteDebug($"文件 {fileName} 已从 {sourceFolder.Trim()} 复制到 {targetPath}"); + } + } + else + { + LogExecute.logNet.WriteDebug($"源文件夹 {sourceFolder.Trim()} 不存在"); + } + } + + if (fileList.Count == 0) + { + LogExecute.logNet.WriteDebug($"在所有源文件夹中未找到包含SN号 {snNumber} 的文件"); + } + + // 组装 request json + var request = new + { + Line = _line, + StationID = _stationID, + MachineID = _machineID, + OPID = _opID, + SNList = new List() + { + new + { + SN = OtherData.JS_SN, + FileInfo = fileList.Select(x => new + { + FileName = fileName, + FilePath = targetFolder + }).ToList() + } + }, + SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + }; + + return CallApi(url, request, "SN_FileUpload", PlcData, PLC_Status.SN_FileUpload); + } + catch (Exception ex) + { + LogExecute.logNet.WriteError($"文件上传处理失败: {ex.Message}"); + return ApiFormResult.Error(mesresult.FAIL, false, ex.Message, PlcData, DateTime.Now); + } + + + /* // 查找源文件 可能会有多张照片或视频 - string sourceFile = Path.Combine(sourceDirectory, "source.png"); - //string targetDir = Path.Combine(targetDirectory, "target"); + var filelist = Directory.GetFiles(sourceDirectory); + var copyedFileList = new List(); + string sourceFile = ""; + var num = 1; + foreach (var file in filelist) + { + // 分别处理每张图片 + var sourceName = Path.GetFileNameWithoutExtension(file); + if (sourceName.Contains(PlcData.Read_MaterialCode0)) + { + sourceFile = Path.Combine(sourceDirectory, sourceName); + var extensionstr = Path.GetExtension(file); + fileName = $"{month}{day}_{_stationID}_{result}_{PlcData.Read_MaterialCode0}_{monthDay}_{time}_{_machineID}_01_Original{num}.{extensionstr}"; + + //执行复制 + var copyResult = CopyFileToDirectory(sourceFile, targetDirectory, fileName); + if (copyResult) + { + copyedFileList.Add(fileName); + num++; + } + } + + } + // 执行复制 try { @@ -470,21 +638,10 @@ namespace WindowsFormsApp1.server // 多个视频或图片 // 动态添加 FileInfo - /* - var newFileInfo = new - { - FileName = "NewFileName.txt", - FilePath = "C:\\path\\to\\newfile.txt" - }; - // 获取 SNList 的第一个元素(假设只有一个 SN 元素) - dynamic snElement = request.SNList[0]; - - // 将 newFileInfo 添加到 FileInfo 列表中 - snElement.FileInfo.Add(newFileInfo); - */ return CallApi(url, request, "SN_FileUpload", PlcData, PLC_Status.SN_FileUpload); + */ } /// @@ -500,7 +657,7 @@ namespace WindowsFormsApp1.server var request = new { Line = _line, // 特殊值,不使用_line - StationID = _stationID, + Station = _stationID, MachineID = _machineID, SN = PlcData.Read_MaterialCode0 }; @@ -512,7 +669,7 @@ namespace WindowsFormsApp1.server { // 根据不同的lineCode构建不同的请求 var lineCode = Init.t_Line.linecode; - var stationid = Init.t_Line.lineremark2.ToLower(); + var stationid = Init.t_Line.lineremark2; var result = PlcData.Read_Result == 1 ? "PASS" : "FAIL"; var logresult = PlcData.Read_Result == 1 ? "OK" : "NG"; @@ -550,26 +707,29 @@ namespace WindowsFormsApp1.server //气密 if ("WAT,Leakage".Contains(stationid)) { - + var customHeaders = new List { "SN", { OutItem.充气压力 }, { OutItem.泄漏量 }, "时间" }; + CsvLogger.SetHeaders(customHeaders); + sninfo.DC_INFO.Add(new DCInfoItem { Item = OutItem.充气压力, - Value = Init.airtight.Airtight_Value, + Value = Init.airtight.Airtight_Value ?? "0", Result = result }); sninfo.DC_INFO.Add(new DCInfoItem { Item = OutItem.泄漏量, - Value = Init.airtight.Leak_Value, + Value = Init.airtight.Leak_Value ?? "0", Result = result }); - - LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value}"); + CsvLogger.Log($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value},{DateTime.Now}"); } //扭力,角度 if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM".Contains(stationid)) { var AngleCount = 1; + OtherData.FinalAngleValue[0] = (float)12.8888; + OtherData.FinalAngleValue[1] = (float)11.9999; foreach (var item in OtherData.FinalAngleValue.Where(x => x > 0)) { //角度 @@ -579,9 +739,13 @@ namespace WindowsFormsApp1.server dcInfo.Result = result; sninfo.DC_INFO.Add(dcInfo); + LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}"); + AngleCount++; } var TorqueCount = 1; + OtherData.FinalTorqueValue[0] = (float)120; + OtherData.FinalTorqueValue[1] = (float)110; foreach (var item in OtherData.FinalTorqueValue.Where(x => x > 0)) { //扭力 @@ -591,6 +755,8 @@ namespace WindowsFormsApp1.server dcInfo.Result = result; sninfo.DC_INFO.Add(dcInfo); + LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}"); + TorqueCount++; } } @@ -598,6 +764,7 @@ namespace WindowsFormsApp1.server //CCD if ("Assy2,Assy3,AOI,Assy5,Sealant,CCD,PrintLabel".Contains(stationid)) { + dcInfo = new DCInfoItem(); dcInfo.Item = stationid == "CCD"? "CCD" : $"{Init.t_Line.lineremark2}_CCD"; dcInfo.Value = PlcData.Read_UploadData0.ToString(); dcInfo.Result = result; @@ -608,7 +775,21 @@ namespace WindowsFormsApp1.server //抽真空 压力 if ("Vacuum".Contains(stationid)) { - + var Chamber_Pressure = OtherData.FinalPressureCurve.First(); + dcInfo = new DCInfoItem(); + dcInfo.Item = $"Chamber_Pressure"; + dcInfo.Value = Chamber_Pressure.ToString(); + dcInfo.Result = result; + LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}"); + + sninfo.DC_INFO.Add(dcInfo); + + dcInfo = new DCInfoItem(); + dcInfo.Item = $"Hold_Time"; + dcInfo.Value = PlcData.Read_Other0.ToString(); + dcInfo.Result = result; + LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}"); + } //固化 时间 if ("Curing".Contains(stationid)) @@ -618,7 +799,7 @@ namespace WindowsFormsApp1.server if (material.Success) { // 计算加热时间 - var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout2)).TotalMinutes; + var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout1)).TotalMilliseconds; var jrTime = Convert.ToInt32(time).ToString(); sninfo.DC_INFO.Add(new DCInfoItem { @@ -647,6 +828,8 @@ namespace WindowsFormsApp1.server dcInfo.Item = $"{stationid}_Weight"; dcInfo.Value = PlcData.Read_UploadData0.ToString(); dcInfo.Result = result; + LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}"); + sninfo.DC_INFO.Add(dcInfo); } //胶宽 @@ -655,17 +838,23 @@ namespace WindowsFormsApp1.server dcInfo.Item = $"{stationid}_Width"; dcInfo.Value = PlcData.Read_UploadData1.ToString(); dcInfo.Result = result; + LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}"); + sninfo.DC_INFO.Add(dcInfo); } //胶水 材料码 if ("Potting,ThermalPaste,Sel_Soldering,UVCoating,Sealant".Contains(stationid)) { - compListItem.CompID = OtherData.JS_SN; - compListItem.Qty = "1"; + SQLiteHelper materialHelper = new db.SQLiteHelper(); + var glue = materialHelper.QuerySingle(x => x.isonline); + if (glue.Success) + { + compListItem.CompID = glue.Data.scancode; + compListItem.Qty = "1"; - sninfo.CompList.Add(compListItem); - - LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},胶水码:{OtherData.JS_SN},胶重:{PlcData.Read_UploadData0}"); + sninfo.CompList.Add(compListItem); + } + //LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},胶水码:{OtherData.JS_SN},胶重:{PlcData.Read_UploadData0}"); } else //其他不传 { diff --git a/WindowsFormsApp1/server/CsvHelper.cs b/WindowsFormsApp1/server/CsvHelper.cs new file mode 100644 index 0000000..bfe6627 --- /dev/null +++ b/WindowsFormsApp1/server/CsvHelper.cs @@ -0,0 +1,85 @@ +using CsvHelper; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace WindowsFormsApp1 +{ + // 定义日志条目类 + public class LogEntry + { + public DateTime Timestamp { get; set; } + public string Level { get; set; } + public string Message { get; set; } + public string Exception { get; set; } + } + + // 封装 CsvHelper 的日志记录类,设为静态类 + public static class CsvLogger + { + private static string _baseFilePath; + private static List _customHeaders = new List(); + + public static void Initialize(string baseFilePath) + { + _baseFilePath = baseFilePath; + } + + // 设置自定义表头 + public static void SetHeaders(List headers) + { + _customHeaders = headers; + } + + private static string GetCurrentLogFilePath() + { + var date = DateTime.Now.ToString("yyyy-MM-dd"); + var fileExtension = Path.GetExtension(_baseFilePath); + var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_baseFilePath); + if (!Directory.Exists(Path.GetDirectoryName(_baseFilePath))) + { + Directory.CreateDirectory(Path.GetDirectoryName(_baseFilePath)); + } + return $"{Path.GetDirectoryName(_baseFilePath)}/{fileNameWithoutExtension}_{date}{fileExtension}"; + } + + public static void Log(string csvFormattedString) + { + var filePath = GetCurrentLogFilePath(); + // 检查文件是否存在,如果不存在则创建并写入表头 + if (!File.Exists(filePath)) + { + using (var writer = new StreamWriter(filePath)) + using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) + { + if (_customHeaders.Count > 0) + { + foreach (var header in _customHeaders) + { + csv.WriteField(header); + } + csv.NextRecord(); + } + else + { + csv.WriteHeader(); + csv.NextRecord(); + } + } + } + + // 追加日志条目到文件 + using (var writer = new StreamWriter(filePath, true)) + using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) + { + var fields = csvFormattedString.Split(','); + foreach (var field in fields) + { + csv.WriteField(field); + } + csv.NextRecord(); + } + } + } +}