From dc18021539bdf4ee176ec9d9b88eb7d9ad581600 Mon Sep 17 00:00:00 2001
From: C3204 <zhengyabo@lanpucloud.cn>
Date: 星期五, 17 四月 2026 17:00:35 +0800
Subject: [PATCH] 新增心跳等常规信号配置&&修改相机轴读取配置等

---
 LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorS7Form.cs |  328 ++++++++++++++++++++++++++++++++++++------------------
 1 files changed, 218 insertions(+), 110 deletions(-)

diff --git a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorS7Form.cs b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorS7Form.cs
index a39b1e2..e32afed 100644
--- a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorS7Form.cs
+++ b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorS7Form.cs
@@ -1,11 +1,17 @@
-锘縰sing LB_VisionProcesses.Communicators;
+锘縰sing LB_SmartVisionCommon;
+using LB_VisionProcesses.Communicators;
 using LB_VisionProcesses.Communicators.SiemensS7;
 using LB_VisionProcesses.Communicators.Tcom;
+using Microsoft.VisualBasic;
+using OpenVinoSharp.Extensions.model;
 using ReaLTaiizor.Forms;
 using RJCP.IO.Ports;
 using S7.Net;
+using System.Data;
 using System.Diagnostics;
 using System.Linq;
+using System.Windows.Forms;
+using YamlDotNet.Core.Tokens;
 
 namespace LB_SmartVision.Forms.Pages.CommunicatorPage
 {
@@ -15,6 +21,11 @@
         BaseCommunicator communicator { get; set; }
 
         public event CommunicatorS7Change CommunicatorChanged;
+
+        private PlcConfig config;
+        private DataTable signalTable;
+        private BindingSource bindingSource;
+        private string Name;
 
         private void communicatorChanged(BaseCommunicator communicator)
         {
@@ -44,60 +55,14 @@
             cmbIP.Enabled = false;
             txtIP.Enabled = false;
             txtPort.Enabled = false;
-            cmbDataType.Enabled = false;
 
 
             lblType.Visible = false;
-            lblAddress.Visible = false;
             cmbType.Visible = false;
-            txtAddress.Visible = false;
-            lblDataType.Visible = false;
-            cmbDataType.Visible = false;
 
-
+            Name = name;
             this.Text = name;
-            if (communicator is UARTPort)
-            {
-                //缁熻鍙敤绔彛
-                SerialPortStream temp = new SerialPortStream();
-                string[] ArryPort = temp.GetPortNames();
-                for (int i = 0; i < ArryPort.Length; i++)
-                {
-                    cmbIP.Items.Add(ArryPort[i]);
-                }
-                cmbIP.Text = communicator.CommunicatorConnections["鍦板潃"]?.ToString();
-                txtPort.Text = communicator.CommunicatorConnections["绔彛"]?.ToString();
-                txtIP.Visible = false;
-                cmbIP.Visible = true;
-                this.btnRuleSend.Visible = true;
-                lblType.Visible = false;
-                lblAddress.Visible = false;
-                cmbType.Visible = false;
-                txtAddress.Visible = false;
-                lblDataType.Visible = false;
-                cmbDataType.Visible = false;
-
-                lblIP.Text = "COM鍙�";
-                lblPort.Text = "娉㈢壒鐜�";
-            }
-            else if (communicator is TCPClient || communicator is TCPServer)
-            {
-                txtIP.Text = communicator.CommunicatorConnections["鍦板潃"]?.ToString();
-                txtPort.Text = communicator.CommunicatorConnections["绔彛"]?.ToString();
-                txtIP.Visible = true;
-                cmbIP.Visible = false;
-                this.btnRuleSend.Visible = false;
-                lblType.Visible = false;
-                lblAddress.Visible = false;
-                cmbType.Visible = false;
-                txtAddress.Visible = false;
-                lblDataType.Visible = false;
-                cmbDataType.Visible = false;
-
-                lblIP.Text = "鍦板潃";
-                lblPort.Text = "绔彛";
-            }
-            else if (communicator is SiemensLBS7)
+            if (communicator is SiemensLBS7)
             {
                 txtIP.Text = communicator.CommunicatorConnections["鍦板潃"]?.ToString();
                 txtPort.Text = communicator.CommunicatorConnections["绔彛"]?.ToString();
@@ -107,33 +72,10 @@
                     cmbType.Items.Add(communicator.CommunicatorConnections["鍨嬪彿"]?.ToString());
                     cmbType.Text = communicator.CommunicatorConnections["鍨嬪彿"]?.ToString();
                 }
-                if (!string.IsNullOrEmpty(communicator.CommunicatorConnections["鍙橀噺鍦板潃"]?.ToString()))
-                {
-                    txtAddress.Text = communicator.CommunicatorConnections["鍙橀噺鍦板潃"]?.ToString();
-                }
-
-                // 鍒濆鍖栨暟鎹被鍨�
-                cmbDataType.Items.Clear();
-                cmbDataType.Items.AddRange(new string[] { "String", "Bool", "Byte", "Int", "DInt", "Real", "Double", "Word", "DWord" });
-                if (communicator.CommunicatorConnections.Contains("鏁版嵁绫诲瀷"))
-                {
-                    cmbDataType.Text = communicator.CommunicatorConnections["鏁版嵁绫诲瀷"].ToString();
-                }
-                else
-                {
-                    cmbDataType.Text = "String";
-                }
-
                 txtIP.Visible = true;
                 cmbIP.Visible = false;
-                this.btnRuleSend.Visible = false;
                 lblType.Visible = true;
-                lblAddress.Visible = true;
                 cmbType.Visible = true;
-                txtAddress.Visible = true;
-                lblDataType.Visible = true;
-                cmbDataType.Visible = true;
-                cmbDataType.Enabled = true; // 鍚敤鏁版嵁绫诲瀷閫夋嫨
 
                 lblIP.Text = "IP";
                 lblPort.Text = "妲�";
@@ -142,15 +84,7 @@
             this.communicator = communicator;
             //鍔犺浇鍥炶皟鍑芥暟
             Subscribe();
-        }
-
-        private void cmbDataType_SelectedIndexChanged(object sender, EventArgs e)
-        {
-            if (communicator != null)
-            {
-                communicator.CommunicatorConnections.Add("鏁版嵁绫诲瀷", cmbDataType.Text);
-                communicatorChanged(communicator);
-            }
+            LoadConfigAndSetupGrid();
         }
 
         private void CommunicatorForm_FormClosing(object sender, FormClosingEventArgs e) => Unsubscribe();
@@ -274,59 +208,233 @@
             }
         }
 
-        private void btnSend_Click(object sender, EventArgs e)
+        // 鎵归噺璇诲彇鎵�鏈変俊鍙�
+        private void btnReadAll_Click(object sender, EventArgs e)
         {
-            if (communicator == null)
+            if (communicator == null || !communicator.bConnected)
             {
+                MessageBox.Show("璇峰厛杩炴帴 PLC", "鎻愮ず", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 return;
             }
 
-            if (communicator.SendMessage(txtSendMsg.Text))
+            try
             {
-                ShowSendMsg(txtSendMsg.Text);
+                for (int i = 0; i < config.Signals.Count; i++)
+                {
+                    var signal = config.Signals[i];
+                    object value = ((SiemensLBS7)communicator).ReadSignal(signal);
+                    config.Signals[i].Value= value?.ToString() ?? "";
+                    signalTable.Rows[i]["Value"] = config.Signals[i].Value;
+                    ShowLogMsg(signalTable.Rows[i]["Value"] + "锛�" + value?.ToString() ?? "");
+                }
             }
-            else
+            catch (Exception ex)
             {
-                ShowLogMsg(communicator.Msg);
+                MessageBox.Show($"鎵归噺璇诲彇澶辫触: {ex.Message}", "閿欒", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
 
-        private void btnRuleSend_Click(object sender, EventArgs e)
+        // 鎵归噺鍐欏叆锛氬皢琛ㄦ牸涓慨鏀硅繃鐨勫�煎啓鍏� PLC
+        private void btnWriteAll_Click(object sender, EventArgs e)
         {
-            if (communicator == null)
+            if (communicator == null || !communicator.bConnected)
             {
+                MessageBox.Show("璇峰厛杩炴帴 PLC", "鎻愮ず", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 return;
             }
 
-            string SendMsg = txtSendMsg.Text;
-
-            //byte[] HexByte = BaseCommunicator.strToHexByte(SendMsg);
-
-            byte[] HexByte = SendMsg.Split(' ', StringSplitOptions.RemoveEmptyEntries)
-                                        .Select(hex => Convert.ToByte(hex, 16))
-                                        .ToArray();
-            ushort crcHexByte = BaseCommunicator.CRC16Calculate(HexByte, HexByte.Length);
-
-            string crcString = crcHexByte.ToString("X4");
-            crcString = crcString.Insert(2, " ");
-            HexByte = BaseCommunicator.strToHexByte(SendMsg + " " + crcString);
-
-            if (communicator.SendMessage(HexByte))
+            try
             {
-                ShowSendMsg(SendMsg + " " + crcString);
+                int successCount = 0;
+                for (int i = 0; i < config.Signals.Count; i++)
+                {
+                    var signal = config.Signals[i];
+                    string newValueStr = signalTable.Rows[i]["Value"]?.ToString();
+                    if (!string.IsNullOrEmpty(newValueStr))
+                    {
+                        object convertedValue = ConvertValue(signal.DataType, newValueStr);
+                        ((SiemensLBS7)communicator).WriteSignal(signal, convertedValue);
+                        successCount++;
+                    }
+                    ShowSendMsg(signalTable.Rows[i]["Value"] + "锛�" + newValueStr?.ToString() ?? "");
+                }
+                MessageBox.Show($"鎵归噺鍐欏叆瀹屾垚锛屾垚鍔熷啓鍏� {successCount} 涓俊鍙枫��", "鍐欏叆缁撴灉", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
-            else
+            catch (Exception ex)
             {
-                ShowLogMsg(communicator.Msg);
+                MessageBox.Show($"鎵归噺鍐欏叆澶辫触: {ex.Message}", "閿欒", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
 
-        private void txtAddress_TextChanged(object sender, EventArgs e)
+        private void btnConfig_Click(object sender, EventArgs e)
         {
-            if (communicator != null)
+            using (var configForm = new ConfigForm(config, GlobalVar.allPlcSettingPath + "\\" + this.Name + ".json"))
             {
-                communicator.CommunicatorConnections.Add("鍙橀噺鍦板潃", txtAddress.Text);
-                communicatorChanged(communicator);
+                if (configForm.ShowDialog() == DialogResult.OK)
+                {
+                    config = S7ConfigService.LoadConfig(GlobalVar.allPlcSettingPath);
+                    LoadConfigAndSetupGrid();
+                    UpdateConnectionStatus();
+                }
+            }
+        }
+
+
+
+        // 鏁版嵁绫诲瀷杞崲杈呭姪鏂规硶
+        private object ConvertValue(string dataType, string valueStr)
+        {
+            switch (dataType)
+            {
+                case "Bool":
+                    {
+                        if (bool.TryParse(valueStr, out bool b)) return b;
+                        if (valueStr == "1") return true;
+                        if (valueStr == "0") return false;
+                        throw new Exception("鏃犳晥鐨勫竷灏斿��");
+                    }
+                case "Byte":
+                    {
+                        return byte.Parse(valueStr);
+                    }
+                case "Int":
+                    {
+                        return short.Parse(valueStr);
+                    }
+                case "DInt":
+                    {
+                        return int.Parse(valueStr);
+                    }
+                case "Real":
+                    {
+                        return float.Parse(valueStr);
+                    }
+                case "String":
+                    {
+                        return valueStr;
+                    }
+                default:
+                    {
+                        throw new NotSupportedException($"涓嶆敮鎸佺殑绫诲瀷: {dataType}");
+                    }
+            }
+        }
+        private void LoadConfigAndSetupGrid()
+        {
+            config = S7ConfigService.LoadConfig(GlobalVar.allPlcSettingPath + "\\" + this.Name + ".json");
+
+            if (GlobalVar.allPlcSettings.Keys.Contains(Name))
+            {
+                GlobalVar.allPlcSettings[Name] = config;
+            }
+            else
+            {
+                GlobalVar.allPlcSettings.TryAdd(Name, config);
+            }
+            ConfigManager<Dictionary<string, PlcConfig>>.SaveConfig<Dictionary<string, PlcConfig>>(GlobalVar.allPlcSettings, GlobalVar.allPlcSettingsPath);
+            // 鏋勫缓 DataTable 鐢ㄤ簬灞曠ず淇″彿锛堟敮鎸佺紪杈戝�煎垪锛�
+            signalTable = new DataTable();
+            signalTable.Columns.Add("SignalName", typeof(string));
+            signalTable.Columns.Add("Address", typeof(string));
+            signalTable.Columns.Add("Value", typeof(string));
+
+            foreach (var signal in config.Signals)
+            {
+                string address = $"{signal.Area}";
+                if (signal.Area == "DB")
+                    address += $"{signal.DbNumber}.DB";
+                address += $"{signal.ByteOffset}.{signal.BitOffset}";
+
+                signalTable.Rows.Add(signal.SignalName, address, "");
+            }
+
+            bindingSource = new BindingSource();
+            bindingSource.DataSource = signalTable;
+            dgvSignals.DataSource = bindingSource;
+
+            dgvSignals.Columns["SignalName"].HeaderText = "淇″彿鍚嶇О";
+            dgvSignals.Columns["SignalName"].ReadOnly = true;
+            dgvSignals.Columns["Address"].HeaderText = "PLC 鍦板潃";
+            dgvSignals.Columns["Address"].ReadOnly = true;
+            dgvSignals.Columns["Value"].HeaderText = "褰撳墠鍊�";
+            dgvSignals.Columns["Value"].ReadOnly = false;  // 鍏佽鐢ㄦ埛缂栬緫
+
+            UpdateConnectionStatus();
+            dgvSignals.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
+        }
+
+        private void UpdateConnectionStatus()
+        {
+            if (communicator != null && communicator.bConnected)
+            {
+                lblStatus.Text = $"宸茶繛鎺�: {config.PlcIpAddress}";
+                lblStatus.ForeColor = Color.Green;
+            }
+            else
+            {
+                lblStatus.Text = "鏈繛鎺�";
+                lblStatus.ForeColor = Color.Red;
+            }
+        }
+
+        // ========== 鍙抽敭鑿滃崟锛氬崟淇″彿鎿嶄綔 ==========
+        private SignalConfig GetSelectedSignal()
+        {
+            if (dgvSignals.CurrentRow == null) return null;
+            int index = dgvSignals.CurrentRow.Index;
+            if (index >= 0 && index < config.Signals.Count)
+                return config.Signals[index];
+            return null;
+        }
+
+        private void menuReadSignal_Click(object sender, EventArgs e)
+        {
+            var signal = GetSelectedSignal();
+            if (signal == null) return;
+
+            if (communicator != null && !communicator.bConnected)
+            {
+                MessageBox.Show("璇峰厛杩炴帴 PLC");
+                return;
+            }
+
+            try
+            {
+                object value = ((SiemensLBS7)communicator).ReadSignal(signal);
+                MessageBox.Show($"淇″彿 [{signal.SignalName}] 褰撳墠鍊�: {value}", "璇诲彇缁撴灉");
+                signalTable.Rows[dgvSignals.CurrentRow.Index]["Value"] = value?.ToString();
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"璇诲彇澶辫触: {ex.Message}");
+            }
+        }
+
+        private void menuWriteSignal_Click(object sender, EventArgs e)
+        {
+            var signal = GetSelectedSignal();
+            if (signal == null) return;
+
+            if (communicator != null && !communicator.bConnected)
+            {
+                MessageBox.Show("璇峰厛杩炴帴 PLC");
+                return;
+            }
+
+            string input = Interaction.InputBox(
+                $"璇疯緭鍏ヨ鍐欏叆 {signal.SignalName} 鐨勫�� ({signal.DataType})",
+                "鍐欏叆淇″彿", "");
+            if (string.IsNullOrEmpty(input)) return;
+
+            try
+            {
+                object value = ConvertValue(signal.DataType, input);
+                ((SiemensLBS7)communicator).WriteSignal(signal, value);
+                MessageBox.Show("鍐欏叆鎴愬姛");
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"鍐欏叆澶辫触: {ex.Message}");
             }
         }
     }

--
Gitblit v1.9.3