c#与基于S7西门子通讯

环境下载

界面展示

项目是在项目上用的稳定无异常 代码附带说明 已经将PLC通讯整个模块复制过来
在这里插入图片描述
VS 上方菜单栏 项目->管理NuGet 搜索安装
在这里插入图片描述
引入S7.NET 的dll库文件

主要的读写类

数据类型的enum声明

		/// <summary>
        /// S7数据类型
        /// </summary>
        public enum S7_Type
        {
            /// <summary>
            /// Short   	西门子1500的Short与Int都是两个字节,写入用Short类型
            /// </summary>
            Short,
            /// <summary>
            /// int
            /// </summary>
            Int,
            /// <summary>
            /// float   	实数类型需要截取长度,否则会占用后面的寄存器 且也只有两个字节 写入用Float类型
            /// </summary>
            Real,	
            /// <summary>
            /// string 		PLC地址那边需要用char字符数组存储 否则会读取异常
            /// </summary>
            String,  
            /// <summary>
            /// 无符号整型	用Uint去读写
            /// </summary>
            DInt     
        }

然后就是类里面的属性

		/// <summary>
        /// 读写要加锁 否则会资源冲突 造成包异常
        /// </summary>
		private static readonly object _lock_read = new object();
		/// <summary>
        /// 
        /// </summary>
        private static readonly object _lock_write = new object();
        /// <summary>
        /// PLC
        /// </summary>
        private S7.Net.Plc _plc;
        /// <summary>
        /// 连接标志位
        /// </summary>
        private bool _connect;
        /// <summary>
        /// ini 配置文件路径
        /// </summary>
        private string params_path = System.Windows.Forms.Application.StartupPath + "\\Config\\PLCConfig\\S1500.ini";
        /// <summary>
        /// PLC参数  创建的是一个读写ini 文件的操作类
        /// </summary>
        public PLCParams PLCParam = new PLCParams();
        /// <summary>
        ///  PLC调试窗体
        /// </summary>
        public PLC PLC_Form;
        public bool Connected
        {
            get { return _connect; }
        }

PLC的读写操作

 		public S7Lib()
        {
            PLCParam.Ini(params_path);
        }

        /// <summary>
        /// 显示PLC弹窗
        /// </summary>
        public void ShowDialogForm()
        {
            PLC_Form = new PLC(this);
            PLC_Form.ShowDialog();

        }

        /// <summary>
        /// 嵌套PLC窗体
        /// </summary>
        /// <returns></returns>
        public PLC ShowForm()
        {
            return PLC_Form = new PLC(this);
        }


        public bool Open()
        {
            lock (_lock_read)
            {
                bool s = false;
                try
                {
                    if (_plc == null)
                    {
                        _plc = new Plc(CpuType.S71200, PLCParam.PLC_IPAddress, PLCParam.PLC_Rack, PLCParam.PLC_Slot);
                    }
                    if (!_plc.IsConnected)
                    {
                        _plc.Open();
                        _connect = _plc.IsConnected;
                    }
                    else
                    {
                        _plc = null;
                        _plc = new Plc(CpuType.S71500, PLCParam.PLC_IPAddress, PLCParam.PLC_Rack, PLCParam.PLC_Slot);
                        _plc.Open();
                        if (_plc.IsConnected)
                            _connect = _plc.IsConnected;
                    }
                }
                catch (Exception ex)
                {
                    s = false;
                }
                return s = _connect;
            }

        }

        public bool Write(int Address, S7_Type dataType, object Value)
        {
            lock (_lock_write)
            {
                bool s = false;
                try
                {
                    short Address1 = (short)Address;
                    if (_plc == null)
                    {
                        _connect = false;
                        throw new Exception("PLC连接异常");
                    }
                    if (!_plc.IsConnected)
                    {
                        _connect = false;
                        throw new Exception("PLC未连接");
                    }
                    switch (dataType)
                    {
                        case S7_Type.Short:
                        case S7_Type.Int:
                            _plc.Write(DataType.DataBlock, PLCParam.DBNum, Address1, Convert.ToInt16(Value));
                            break;
                        case S7_Type.String:
                            _plc.Write(DataType.DataBlock, PLCParam.DBNum, Address1, Convert.ToString(Value));
                            break;
                        case S7_Type.Real:
                            _plc.Write(DataType.DataBlock, PLCParam.DBNum, Address1, Convert.ToSingle(Value));
                            break;
                        case S7_Type.DInt:
                            _plc.Write(DataType.DataBlock, PLCParam.DBNum, Address1, Convert.ToUInt32(Value));
                            break;
                        default:
                            throw new Exception("未知数据类型!");
                    }
                    s = true;
                }
                catch (Exception ex)
                {
                    s = false;
                }
                return s;
            }

        }

        public bool Read<T>(int Address, S7_Type dataType, out T value, int Length = 1)
        {
            lock (_lock_read)
            {
                value = default(T);
                object obj = null;
                bool s = false;
                try
                {
                    if (Length < 1)
                    {
                        throw new Exception("长度参数异常");
                    }
                    if (_plc == null)
                    {
                        _connect = false;
                        throw new Exception("PLC连接异常");
                    }
                    if (!_plc.IsConnected)
                    {
                        _connect = false;
                        throw new Exception("PLC未连接");
                    }
                    switch (dataType)
                    {
                        case S7_Type.Short:
                        case S7_Type.Int:
                            obj = _plc.Read(DataType.DataBlock, PLCParam.DBNum, Address, VarType.Int, 1,0);
                            
                            break;
                        case S7_Type.String:
                            obj = _plc.Read(DataType.DataBlock, PLCParam.DBNum, Address, VarType.String, Length,0);
                            break;
                        case S7_Type.Real:
                            obj = _plc.Read(DataType.DataBlock, PLCParam.DBNum, Address, VarType.Real, Length,0);
                            break;
                        case S7_Type.DInt:
                            obj = _plc.Read(DataType.DataBlock, PLCParam.DBNum, Address, VarType.DInt, Length,0);
                            break;
                        default:
                            throw new Exception("未知数据类型!");
                    }
                    value = (T)obj;
                    s = true;
                }
                catch (Exception ex)
                {
                    value = default(T);
                    s = false;
                }

                return s;
            }
        }
        
        

        public void Close()
        {
            try
            {
                if (_plc == null) {
                    _connect = false;
                }
                if (_plc.IsConnected)
                {
                    _plc.Close();
                    _plc = null;
                    _connect = false;
                }
                _plc = null;
            }
            catch
            {
                _connect = false;
                _plc = null;
                
            }
        }

        public void SaveParams()
        {
            this.PLCParam.Save(params_path);
        }

        public void LoadParams()
        {
            this.PLCParam.Ini(params_path);
        }

配置文件读写类的编写

 		/// <summary>
        /// 配置文件帮助类
        /// </summary>
        public abstract class IniConfig
        {
            #region [ 读写 ini 文件 ]
            [DllImport("kernel32")]//返回取得字符串缓冲区的长度
            protected static extern long GetPrivateProfileString(string section, string key,
           string def, StringBuilder retVal, int size, string filePath);
            [DllImport("kernel32")]//返回0表示失败,非0为成功
            protected static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

            /// <summary>
            /// 
            /// </summary>
            /// <param name="strSection"></param>
            /// <param name="strKey"></param>
            /// <param name="strValue"></param>
            /// <param name="strIniFilePath"></param>
            /// <returns></returns>
            public static bool WriteIniData(string strSection, string strKey, string strValue, string strIniFilePath)
            {
                if (File.Exists(strIniFilePath))
                {
                    long bOpStation = WritePrivateProfileString(strSection, strKey, strValue, strIniFilePath);
                    if (bOpStation == 0)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }

          

            /// <summary>
            /// 
            /// </summary>
            /// <param name="strSection"></param>
            /// <param name="strKey"></param>
            /// <param name="strNoText"></param>
            /// <param name="strIniFilePath"></param>
            /// <returns></returns>
            protected string ReadIniData(string strSection, string strKey, string strNoText, string strIniFilePath)
            {
                if (File.Exists(strIniFilePath))
                {
                    StringBuilder strbTemp = new StringBuilder(1024);
                    GetPrivateProfileString(strSection, strKey, strNoText, strbTemp, 1024, strIniFilePath);
                    return strbTemp.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
            #endregion

            /// <summary>
            /// Section Name
            /// </summary>
            protected string SectionName = string.Empty;
            /// <summary>
            ///  写入配置文件
            /// </summary>
            /// <summary>
            /// 保存参数至Ini文件
            /// </summary>
            /// <param name="iniFileName">ini文件路径+名称</param>
            public void Save(string iniFileName)
            {
                Type type = base.GetType();
                string text = this.SectionName;
                bool flag = string.IsNullOrEmpty(text);
                if (flag)
                {
                    text = type.Name;
                }
                PropertyInfo[] properties = type.GetProperties();
                PropertyInfo[] array = properties;
                for (int i = 0; i < array.Length; i++)
                {
                    PropertyInfo propertyInfo = array[i];
                    bool flag2 = propertyInfo.Name != "SectionName";
                    if (flag2)
                    {
                        object value = propertyInfo.GetValue(this, null);
                        WriteIniData(text, propertyInfo.Name, propertyInfo.GetValue(this, null).ToString(), iniFileName);
                    }
                }
            }

            /// <summary>
            /// 从ini文件初始化参数
            /// </summary>
            /// <param name="iniFileName">ini文件路径+名称</param>
            public void Ini(string iniFileName)
            {
                Type type = base.GetType();
                string name = type.Name;
                PropertyInfo[] properties = type.GetProperties();
                PropertyInfo[] array = properties;
                for (int i = 0; i < array.Length; i++)
                {
                    PropertyInfo propertyInfo = array[i];
                    try
                    {
                        string text = ReadIniData(name, propertyInfo.Name,"NULL", iniFileName);
                        bool flag = text.ToUpper() == "NULL";
                        if (flag)
                        {
                            object[] customAttributes = propertyInfo.GetCustomAttributes(true);
                            for (int j = 0; j < customAttributes.Length; j++)
                            {
                                try
                                {
                                    DefaultValueAttribute defaultValueAttribute = (DefaultValueAttribute)customAttributes[j];
                                    text = defaultValueAttribute.Value.ToString();
                                    break;
                                }
                                catch
                                {
                                }
                            }
                        }
                        propertyInfo.SetValue(this, Convert.ChangeType(text, propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                    }
                }
            }
        }

上面的帮助类写好了我们就定义参数的类 利用反射与属性去读写操作 可快速实现大批量数据的读写

 		//PLC参数
        public class PLCParams : IniConfig
        {
            const string SYSTEMPARAM = "PLC";
            /// <summary>
            /// PLC_IPAddress
            /// </summary>
            [Category(SYSTEMPARAM), Description(""), DisplayName("PLC_IP"), DefaultValue("192.168.0.2")]
            public string PLC_IPAddress { set; get; }
            /// <summary>
            /// Rack
            /// </summary>
            [Category(SYSTEMPARAM), Description(""), DisplayName("Rack"), DefaultValue(0)]
            public short PLC_Rack { set; get; }
            /// <summary>
            /// Slot
            /// </summary>
           [Category(SYSTEMPARAM), Description(""), DisplayName("Slot"), DefaultValue(2)]
            public short PLC_Slot { set; get; }
            /// <summary>
            /// DB号
            /// </summary>
            [Category(SYSTEMPARAM), Description(""), DisplayName("DataBlock"), DefaultValue(1)]
            public short DBNum { set; get; }

        }

最后就是界面的编写 直接Copy了

  public class PLC_Windows : Form {
            #region [ Designer ]
            /// <summary>
            /// 必需的设计器变量。
            /// </summary>
            private System.ComponentModel.IContainer components = null;

            /// <summary>
            /// 清理所有正在使用的资源。
            /// </summary>
            /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }

            #region Windows 窗体设计器生成的代码

            /// <summary>
            /// 设计器支持所需的方法 - 不要修改
            /// 使用代码编辑器修改此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                this.groupBox1 = new System.Windows.Forms.GroupBox();
                this.button3 = new System.Windows.Forms.Button();
                this.button2 = new System.Windows.Forms.Button();
                this.button1 = new System.Windows.Forms.Button();
                this.Slot = new System.Windows.Forms.TextBox();
                this.Rack = new System.Windows.Forms.TextBox();
                this.IP_Address = new System.Windows.Forms.TextBox();
                this.label3 = new System.Windows.Forms.Label();
                this.label2 = new System.Windows.Forms.Label();
                this.DB_Number = new System.Windows.Forms.TextBox();
                this.label1 = new System.Windows.Forms.Label();
                this.label4 = new System.Windows.Forms.Label();
                this.groupBox2 = new System.Windows.Forms.GroupBox();
                this.Write_Value = new System.Windows.Forms.TextBox();
                this.Data_Type = new System.Windows.Forms.ComboBox();
                this.label8 = new System.Windows.Forms.Label();
                this.Current_Value = new System.Windows.Forms.TextBox();
                this.label7 = new System.Windows.Forms.Label();
                this.Write_Data = new System.Windows.Forms.Button();
                this.Read_Data = new System.Windows.Forms.Button();
                this.Start_Address = new System.Windows.Forms.TextBox();
                this.label6 = new System.Windows.Forms.Label();
                this.label5 = new System.Windows.Forms.Label();
                this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
                this.timer1 = new System.Windows.Forms.Timer(this.components);
                this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
                this.textBox1 = new System.Windows.Forms.TextBox();
                this.button4 = new System.Windows.Forms.Button();
                this.richTextBox1 = new System.Windows.Forms.RichTextBox();
                this.richTextBox2 = new System.Windows.Forms.RichTextBox();
                this.groupBox1.SuspendLayout();
                this.groupBox2.SuspendLayout();
                this.tableLayoutPanel1.SuspendLayout();
                this.SuspendLayout();
                // 
                // groupBox1
                // 
                this.groupBox1.Controls.Add(this.richTextBox2);
                this.groupBox1.Controls.Add(this.button3);
                this.groupBox1.Controls.Add(this.button2);
                this.groupBox1.Controls.Add(this.button1);
                this.groupBox1.Controls.Add(this.Slot);
                this.groupBox1.Controls.Add(this.Rack);
                this.groupBox1.Controls.Add(this.IP_Address);
                this.groupBox1.Controls.Add(this.label3);
                this.groupBox1.Controls.Add(this.label2);
                this.groupBox1.Controls.Add(this.DB_Number);
                this.groupBox1.Controls.Add(this.label1);
                this.groupBox1.Controls.Add(this.label4);
                this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.groupBox1.Location = new System.Drawing.Point(0, 0);
                this.groupBox1.Margin = new System.Windows.Forms.Padding(0);
                this.groupBox1.Name = "groupBox1";
                this.groupBox1.Padding = new System.Windows.Forms.Padding(4);
                this.groupBox1.Size = new System.Drawing.Size(569, 313);
                this.groupBox1.TabIndex = 0;
                this.groupBox1.TabStop = false;
                this.groupBox1.Text = "连接PLC";
                // 
                // button3
                // 
                this.button3.Location = new System.Drawing.Point(380, 207);
                this.button3.Margin = new System.Windows.Forms.Padding(4);
                this.button3.Name = "button3";
                this.button3.Size = new System.Drawing.Size(103, 44);
                this.button3.TabIndex = 9;
                this.button3.Text = "保存参数";
                this.button3.UseVisualStyleBackColor = true;
                this.button3.Click += new System.EventHandler(this.button3_Click);
                // 
                // button2
                // 
                this.button2.Location = new System.Drawing.Point(215, 207);
                this.button2.Margin = new System.Windows.Forms.Padding(4);
                this.button2.Name = "button2";
                this.button2.Size = new System.Drawing.Size(112, 44);
                this.button2.TabIndex = 7;
                this.button2.Text = "断开";
                this.button2.UseVisualStyleBackColor = true;
                this.button2.Click += new System.EventHandler(this.button2_Click);
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(31, 207);
                this.button1.Margin = new System.Windows.Forms.Padding(4);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(127, 44);
                this.button1.TabIndex = 6;
                this.button1.Text = "连接";
                this.button1.UseVisualStyleBackColor = true;
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // Slot
                // 
                this.Slot.Location = new System.Drawing.Point(130, 163);
                this.Slot.Margin = new System.Windows.Forms.Padding(4);
                this.Slot.Name = "Slot";
                this.Slot.Size = new System.Drawing.Size(85, 25);
                this.Slot.TabIndex = 5;
                this.Slot.Text = "1";
                // 
                // Rack
                // 
                this.Rack.Location = new System.Drawing.Point(130, 108);
                this.Rack.Margin = new System.Windows.Forms.Padding(4);
                this.Rack.Name = "Rack";
                this.Rack.Size = new System.Drawing.Size(85, 25);
                this.Rack.TabIndex = 4;
                this.Rack.Text = "0";
                // 
                // IP_Address
                // 
                this.IP_Address.Location = new System.Drawing.Point(130, 64);
                this.IP_Address.Margin = new System.Windows.Forms.Padding(4);
                this.IP_Address.Name = "IP_Address";
                this.IP_Address.Size = new System.Drawing.Size(197, 25);
                this.IP_Address.TabIndex = 3;
                this.IP_Address.Text = "192.168.0.2";
                // 
                // label3
                // 
                this.label3.AutoSize = true;
                this.label3.Location = new System.Drawing.Point(28, 163);
                this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label3.Name = "label3";
                this.label3.Size = new System.Drawing.Size(69, 15);
                this.label3.TabIndex = 2;
                this.label3.Text = "PLC 插槽";
                // 
                // label2
                // 
                this.label2.AutoSize = true;
                this.label2.Location = new System.Drawing.Point(28, 111);
                this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label2.Name = "label2";
                this.label2.Size = new System.Drawing.Size(69, 15);
                this.label2.TabIndex = 1;
                this.label2.Text = "PLC 机架";
                // 
                // DB_Number
                // 
                this.DB_Number.Location = new System.Drawing.Point(346, 160);
                this.DB_Number.Margin = new System.Windows.Forms.Padding(4);
                this.DB_Number.Name = "DB_Number";
                this.DB_Number.Size = new System.Drawing.Size(89, 25);
                this.DB_Number.TabIndex = 8;
                this.DB_Number.Text = "4";
                // 
                // label1
                // 
                this.label1.AutoSize = true;
                this.label1.Location = new System.Drawing.Point(25, 64);
                this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label1.Name = "label1";
                this.label1.Size = new System.Drawing.Size(85, 15);
                this.label1.TabIndex = 0;
                this.label1.Text = "PLC IP地址";
                // 
                // label4
                // 
                this.label4.AutoSize = true;
                this.label4.Location = new System.Drawing.Point(253, 163);
                this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label4.Name = "label4";
                this.label4.Size = new System.Drawing.Size(61, 15);
                this.label4.TabIndex = 8;
                this.label4.Text = "DB 块号";
                // 
                // groupBox2
                // 
                this.groupBox2.Controls.Add(this.richTextBox1);
                this.groupBox2.Controls.Add(this.button4);
                this.groupBox2.Controls.Add(this.Write_Value);
                this.groupBox2.Controls.Add(this.Data_Type);
                this.groupBox2.Controls.Add(this.label8);
                this.groupBox2.Controls.Add(this.Current_Value);
                this.groupBox2.Controls.Add(this.label7);
                this.groupBox2.Controls.Add(this.Write_Data);
                this.groupBox2.Controls.Add(this.Read_Data);
                this.groupBox2.Controls.Add(this.Start_Address);
                this.groupBox2.Controls.Add(this.label6);
                this.groupBox2.Controls.Add(this.label5);
                this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
                this.groupBox2.Location = new System.Drawing.Point(569, 0);
                this.groupBox2.Margin = new System.Windows.Forms.Padding(0);
                this.groupBox2.Name = "groupBox2";
                this.groupBox2.Padding = new System.Windows.Forms.Padding(4);
                this.groupBox2.Size = new System.Drawing.Size(617, 313);
                this.groupBox2.TabIndex = 1;
                this.groupBox2.TabStop = false;
                this.groupBox2.Text = "操作数据";
                // 
                // Write_Value
                // 
                this.Write_Value.Location = new System.Drawing.Point(238, 141);
                this.Write_Value.Margin = new System.Windows.Forms.Padding(4);
                this.Write_Value.Name = "Write_Value";
                this.Write_Value.Size = new System.Drawing.Size(103, 25);
                this.Write_Value.TabIndex = 17;
                // 
                // Data_Type
                // 
                this.Data_Type.FormattingEnabled = true;
                this.Data_Type.Items.AddRange(new object[] {
            "Short",
            "Int",
            "Real",
            "String"});
                this.Data_Type.Location = new System.Drawing.Point(65, 141);
                this.Data_Type.Margin = new System.Windows.Forms.Padding(4);
                this.Data_Type.Name = "Data_Type";
                this.Data_Type.Size = new System.Drawing.Size(110, 23);
                this.Data_Type.TabIndex = 2;
                this.Data_Type.SelectedIndexChanged += new System.EventHandler(this.Data_Type_SelectedIndexChanged);
                // 
                // label8
                // 
                this.label8.AutoSize = true;
                this.label8.Location = new System.Drawing.Point(184, 111);
                this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label8.Name = "label8";
                this.label8.Size = new System.Drawing.Size(52, 15);
                this.label8.TabIndex = 16;
                this.label8.Text = "写入值";
                // 
                // Current_Value
                // 
                this.Current_Value.Location = new System.Drawing.Point(238, 61);
                this.Current_Value.Margin = new System.Windows.Forms.Padding(4);
                this.Current_Value.Name = "Current_Value";
                this.Current_Value.Size = new System.Drawing.Size(103, 25);
                this.Current_Value.TabIndex = 15;
                // 
                // label7
                // 
                this.label7.AutoSize = true;
                this.label7.Location = new System.Drawing.Point(184, 38);
                this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label7.Name = "label7";
                this.label7.Size = new System.Drawing.Size(52, 15);
                this.label7.TabIndex = 14;
                this.label7.Text = "当前值";
                // 
                // Write_Data
                // 
                this.Write_Data.Location = new System.Drawing.Point(187, 220);
                this.Write_Data.Margin = new System.Windows.Forms.Padding(4);
                this.Write_Data.Name = "Write_Data";
                this.Write_Data.Size = new System.Drawing.Size(154, 44);
                this.Write_Data.TabIndex = 13;
                this.Write_Data.Text = "写数据";
                this.Write_Data.UseVisualStyleBackColor = true;
                this.Write_Data.Click += new System.EventHandler(this.Write_Data_Click);
                // 
                // Read_Data
                // 
                this.Read_Data.Location = new System.Drawing.Point(20, 220);
                this.Read_Data.Margin = new System.Windows.Forms.Padding(4);
                this.Read_Data.Name = "Read_Data";
                this.Read_Data.Size = new System.Drawing.Size(155, 44);
                this.Read_Data.TabIndex = 8;
                this.Read_Data.Text = "读数据";
                this.Read_Data.UseVisualStyleBackColor = true;
                this.Read_Data.Click += new System.EventHandler(this.Read_Data_Click);
                // 
                // Start_Address
                // 
                this.Start_Address.Location = new System.Drawing.Point(65, 61);
                this.Start_Address.Margin = new System.Windows.Forms.Padding(4);
                this.Start_Address.Name = "Start_Address";
                this.Start_Address.Size = new System.Drawing.Size(110, 25);
                this.Start_Address.TabIndex = 11;
                this.Start_Address.Text = "0";
                // 
                // label6
                // 
                this.label6.AutoSize = true;
                this.label6.Location = new System.Drawing.Point(8, 111);
                this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label6.Name = "label6";
                this.label6.Size = new System.Drawing.Size(67, 15);
                this.label6.TabIndex = 10;
                this.label6.Text = "数据类型";
                // 
                // label5
                // 
                this.label5.AutoSize = true;
                this.label5.Location = new System.Drawing.Point(8, 38);
                this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
                this.label5.Name = "label5";
                this.label5.Size = new System.Drawing.Size(67, 15);
                this.label5.TabIndex = 9;
                this.label5.Text = "起始地址";
                // 
                // contextMenuStrip1
                // 
                this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
                this.contextMenuStrip1.Name = "contextMenuStrip1";
                this.contextMenuStrip1.Size = new System.Drawing.Size(61, 4);
                // 
                // timer1
                // 
                this.timer1.Enabled = true;
                this.timer1.Interval = 1000;
                this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
                // 
                // tableLayoutPanel1
                // 
                this.tableLayoutPanel1.ColumnCount = 2;
                this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 48.06071F));
                this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 51.93929F));
                this.tableLayoutPanel1.Controls.Add(this.textBox1, 0, 1);
                this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0);
                this.tableLayoutPanel1.Controls.Add(this.groupBox2, 1, 0);
                this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
                this.tableLayoutPanel1.Name = "tableLayoutPanel1";
                this.tableLayoutPanel1.RowCount = 2;
                this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 52.33333F));
                this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 47.66667F));
                this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
                this.tableLayoutPanel1.Size = new System.Drawing.Size(1186, 600);
                this.tableLayoutPanel1.TabIndex = 9;
                // 
                // textBox1
                // 
                this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
                this.tableLayoutPanel1.SetColumnSpan(this.textBox1, 2);
                this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.textBox1.Location = new System.Drawing.Point(4, 317);
                this.textBox1.Margin = new System.Windows.Forms.Padding(4);
                this.textBox1.Multiline = true;
                this.textBox1.Name = "textBox1";
                this.textBox1.Size = new System.Drawing.Size(1178, 279);
                this.textBox1.TabIndex = 8;
                // 
                // button4
                // 
                this.button4.Location = new System.Drawing.Point(450, 268);
                this.button4.Margin = new System.Windows.Forms.Padding(4);
                this.button4.Name = "button4";
                this.button4.Size = new System.Drawing.Size(132, 44);
                this.button4.TabIndex = 18;
                this.button4.Text = "清空记录";
                this.button4.UseVisualStyleBackColor = true;
                this.button4.Click += new System.EventHandler(this.button4_Click);
                // 
                // richTextBox1
                // 
                this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
                this.richTextBox1.Location = new System.Drawing.Point(362, 13);
                this.richTextBox1.Margin = new System.Windows.Forms.Padding(0);
                this.richTextBox1.Name = "richTextBox1";
                this.richTextBox1.ReadOnly = true;
                this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
                this.richTextBox1.ShortcutsEnabled = false;
                this.richTextBox1.Size = new System.Drawing.Size(241, 251);
                this.richTextBox1.TabIndex = 19;
                this.richTextBox1.Text = "西门子 S7 通讯:\n\n    整型:采用两个字节 short int转换成short\n        \n    小数:小数必须截取位数,否则会占用后面寄存器。小" +
        "数必须采用 float类型\n        \n    字符串:字符串只能使用char偏移量\n        ";
                // 
                // richTextBox2
                // 
                this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
                this.richTextBox2.Location = new System.Drawing.Point(28, 22);
                this.richTextBox2.Margin = new System.Windows.Forms.Padding(0);
                this.richTextBox2.Name = "richTextBox2";
                this.richTextBox2.ReadOnly = true;
                this.richTextBox2.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
                this.richTextBox2.ShortcutsEnabled = false;
                this.richTextBox2.Size = new System.Drawing.Size(391, 31);
                this.richTextBox2.TabIndex = 20;
                this.richTextBox2.Text = "机架号 插槽 DB块号 PLC查看        ";
                this.richTextBox2.WordWrap = false;
                // 
                // PLC
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(1186, 600);
                this.Controls.Add(this.tableLayoutPanel1);
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                this.Margin = new System.Windows.Forms.Padding(4);
                this.MaximizeBox = false;
                this.MinimizeBox = false;
                this.Name = "PLC";
                this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
                this.Text = "西门子 通讯";
                this.Load += new System.EventHandler(this.PLC_Load);
                this.groupBox1.ResumeLayout(false);
                this.groupBox1.PerformLayout();
                this.groupBox2.ResumeLayout(false);
                this.groupBox2.PerformLayout();
                this.tableLayoutPanel1.ResumeLayout(false);
                this.tableLayoutPanel1.PerformLayout();
                this.ResumeLayout(false);

            }

            #endregion

            private System.Windows.Forms.GroupBox groupBox1;
            private System.Windows.Forms.Button button2;
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.TextBox Slot;
            private System.Windows.Forms.TextBox Rack;
            private System.Windows.Forms.TextBox IP_Address;
            private System.Windows.Forms.Label label3;
            private System.Windows.Forms.Label label2;
            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.GroupBox groupBox2;
            private System.Windows.Forms.Label label6;
            private System.Windows.Forms.Label label5;
            private System.Windows.Forms.Label label4;
            private System.Windows.Forms.Button Write_Data;
            private System.Windows.Forms.Button Read_Data;
            private System.Windows.Forms.TextBox Start_Address;
            private System.Windows.Forms.TextBox DB_Number;
            private System.Windows.Forms.Label label8;
            private System.Windows.Forms.TextBox Current_Value;
            private System.Windows.Forms.Label label7;
            private System.Windows.Forms.ComboBox Data_Type;
            private System.Windows.Forms.TextBox Write_Value;
            private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
            private System.Windows.Forms.Timer timer1;
            private System.Windows.Forms.Button button3;
            private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.Button button4;
            private System.Windows.Forms.RichTextBox richTextBox1;
            private System.Windows.Forms.RichTextBox richTextBox2;
            #endregion

            #region [_form code]
            private S7Lib _plc;

            public S7_Type cdata_type = S7_Type.Int;
            public PLC_Windows(S7Lib plc)
            {
                InitializeComponent();
                Connect(false);
                _plc = plc;
                this.IP_Address.Text = this._plc.PLCParam.PLC_IPAddress;
                this.DB_Number.Text = this._plc.PLCParam.DBNum.ToString();
                this.Rack.Text = this._plc.PLCParam.PLC_Rack.ToString();
                this.Slot.Text = this._plc.PLCParam.PLC_Slot.ToString();
            }

            private void PLC_Load(object sender, EventArgs e)
            {
                if (_plc.Connected)
                {
                    Connect(true);
                }

            }

            public void Connect(bool flag = false)
            {
                try
                {
                    if (flag)
                    {
                        button1.Enabled = false;
                        button2.Enabled = true;
                        Read_Data.Enabled = true;
                        Write_Data.Enabled = true;
                        // textBox1.Text = "已连接到PLC";
                    }
                    else
                    {
                        button1.Enabled = true;
                        button2.Enabled = false;
                        Read_Data.Enabled = false;
                        Write_Data.Enabled = false;
                    }
                }
                catch { }
            }

            private void Data_Type_SelectedIndexChanged(object sender, EventArgs e)
            {
                switch (this.Data_Type.SelectedIndex)
                {
                    case 0:
                        cdata_type = S7_Type.Short;
                        break;
                    case 1:
                        cdata_type = S7_Type.Int;
                        break;
                    case 2:
                        cdata_type = S7_Type.Real;
                        break;
                    case 3:
                        cdata_type = S7_Type.String;
                        break;
                    default:
                        cdata_type = S7_Type.Int;
                        break;

                }
            }

            private void button2_Click(object sender, EventArgs e)
            {
                _plc.Close();
                Connect(false);
            }

            private void Write_Data_Click(object sender, EventArgs e)
            {
                try
                {
                    bool flag = _plc.Write(Convert.ToInt16(Start_Address.Text), cdata_type, this.Write_Value.Text);
                    if (!flag)
                    {
                        WriteTextLog(string.Format("Write 地址{0} 写入数据失败", Start_Address.Text));
                    }
                    else
                    {
                        WriteTextLog(string.Format("Write 地址{0} 写入数据OK 值:{1}", Start_Address.Text, this.Write_Value.Text));
                    }
                }
                catch (Exception ex)
                {
                    WriteTextLog(ex.Message);

                }
            }

            private void timer1_Tick(object sender, EventArgs e)
            {
                Connect(_plc.Connected);
            }

            private void Read_Data_Click(object sender, EventArgs e)
            {
                try
                {
                    object obj = null;
                    bool flag = _plc.Read(Convert.ToInt32(Start_Address.Text), cdata_type, out obj);
                    Current_Value.Text = obj.ToString();
                    if (!flag)
                    {
                        //  MessageBox.Show("读取数据失败");
                        WriteTextLog(string.Format("Read 地址{0} 读取数据失败", Start_Address.Text));
                    }
                    else
                    {
                        WriteTextLog(string.Format("Read 地址{0} 读取数据OK 值:{1}", Start_Address.Text, obj.ToString()));
                    }
                }
                catch (Exception ex)
                {
                    WriteTextLog(ex.Message);
                }
            }

            /// <summary>
            /// Save
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button3_Click(object sender, EventArgs e)
            {
                try
                {
                    this._plc.PLCParam.PLC_IPAddress = this.IP_Address.Text;
                    this._plc.PLCParam.DBNum = Convert.ToInt16(this.DB_Number.Text);
                    this._plc.PLCParam.PLC_Rack = Convert.ToInt16(this.Rack.Text);
                    this._plc.PLCParam.PLC_Slot = Convert.ToInt16(this.Slot.Text);
                    this._plc.SaveParams();
                    WriteTextLog("保存 PL C参数 OK");
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString());
                    WriteTextLog(ex.ToString());
                }
            }

            private void button1_Click(object sender, EventArgs e)
            {
                bool Flag = this._plc.Open();
                if (Flag)
                {
                    WriteTextLog("PLC连接成功");
                }
                else
                {
                    WriteTextLog("PLC连接失败");
                }
            }

            /// <summary>
            /// 写日志
            /// </summary>
            private void WriteTextLog(string msg)
            {
                try
                {
                    string times = DateTime.Now.ToString("HH:mm:ss");
                    this.textBox1.AppendText(times + ": " + msg + "\r\n");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            private void button4_Click(object sender, EventArgs e)
            {
                this.textBox1.Text = "";
            }
            #endregion
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值