C#使用Windows窗体应用 NModbus4 实现RTU从站

窗体设计器生成的代码

namespace ModbusRtu_Slave
{
    partial class Form1
    {
        /// <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.Lamp1 = new System.Windows.Forms.Button();
            this.label5 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.cbxStopBits = new System.Windows.Forms.ComboBox();
            this.nudSlaveID = new System.Windows.Forms.NumericUpDown();
            this.cbxParity = new System.Windows.Forms.ComboBox();
            this.cbxDataBits = new System.Windows.Forms.ComboBox();
            this.cbxBaudRate = new System.Windows.Forms.ComboBox();
            this.cbxPort = new System.Windows.Forms.ComboBox();
            this.btConnect = new System.Windows.Forms.Button();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.btMessageClear = new System.Windows.Forms.Button();
            this.tbMessage = new System.Windows.Forms.TextBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.groupBox1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nudSlaveID)).BeginInit();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.Lamp1);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label7);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Controls.Add(this.cbxStopBits);
            this.groupBox1.Controls.Add(this.nudSlaveID);
            this.groupBox1.Controls.Add(this.cbxParity);
            this.groupBox1.Controls.Add(this.cbxDataBits);
            this.groupBox1.Controls.Add(this.cbxBaudRate);
            this.groupBox1.Controls.Add(this.cbxPort);
            this.groupBox1.Controls.Add(this.btConnect);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Left;
            this.groupBox1.Location = new System.Drawing.Point(0, 0);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(232, 482);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "串口状态";
            // 
            // Lamp1
            // 
            this.Lamp1.Location = new System.Drawing.Point(134, 19);
            this.Lamp1.Name = "Lamp1";
            this.Lamp1.Size = new System.Drawing.Size(27, 25);
            this.Lamp1.TabIndex = 11;
            this.Lamp1.UseVisualStyleBackColor = true;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(4, 246);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(53, 12);
            this.label5.TabIndex = 10;
            this.label5.Text = "停止位:";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(4, 209);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 12);
            this.label4.TabIndex = 9;
            this.label4.Text = "校验位:";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(4, 172);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(53, 12);
            this.label3.TabIndex = 8;
            this.label3.Text = "数据位:";
            // 
            // label7
            // 
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(4, 98);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(65, 12);
            this.label7.TabIndex = 11;
            this.label7.Text = "从站地址:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(6, 135);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(53, 12);
            this.label2.TabIndex = 7;
            this.label2.Text = "波特率:";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(6, 61);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 6;
            this.label1.Text = "串口号:";
            // 
            // cbxStopBits
            // 
            this.cbxStopBits.FormattingEnabled = true;
            this.cbxStopBits.Items.AddRange(new object[] {
            "One",
            "Two"});
            this.cbxStopBits.Location = new System.Drawing.Point(80, 243);
            this.cbxStopBits.Name = "cbxStopBits";
            this.cbxStopBits.Size = new System.Drawing.Size(121, 20);
            this.cbxStopBits.TabIndex = 5;
            // 
            // nudSlaveID
            // 
            this.nudSlaveID.Location = new System.Drawing.Point(81, 96);
            this.nudSlaveID.Name = "nudSlaveID";
            this.nudSlaveID.Size = new System.Drawing.Size(120, 21);
            this.nudSlaveID.TabIndex = 8;
            this.nudSlaveID.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            // 
            // cbxParity
            // 
            this.cbxParity.FormattingEnabled = true;
            this.cbxParity.Items.AddRange(new object[] {
            "Odd",
            "Even",
            "None"});
            this.cbxParity.Location = new System.Drawing.Point(80, 206);
            this.cbxParity.Name = "cbxParity";
            this.cbxParity.Size = new System.Drawing.Size(121, 20);
            this.cbxParity.TabIndex = 4;
            // 
            // cbxDataBits
            // 
            this.cbxDataBits.FormattingEnabled = true;
            this.cbxDataBits.Items.AddRange(new object[] {
            "8"});
            this.cbxDataBits.Location = new System.Drawing.Point(80, 169);
            this.cbxDataBits.Name = "cbxDataBits";
            this.cbxDataBits.Size = new System.Drawing.Size(121, 20);
            this.cbxDataBits.TabIndex = 3;
            // 
            // cbxBaudRate
            // 
            this.cbxBaudRate.FormattingEnabled = true;
            this.cbxBaudRate.Items.AddRange(new object[] {
            "9600"});
            this.cbxBaudRate.Location = new System.Drawing.Point(80, 132);
            this.cbxBaudRate.Name = "cbxBaudRate";
            this.cbxBaudRate.Size = new System.Drawing.Size(121, 20);
            this.cbxBaudRate.TabIndex = 2;
            // 
            // cbxPort
            // 
            this.cbxPort.FormattingEnabled = true;
            this.cbxPort.Items.AddRange(new object[] {
            "com1",
            "com2"});
            this.cbxPort.Location = new System.Drawing.Point(80, 58);
            this.cbxPort.Name = "cbxPort";
            this.cbxPort.Size = new System.Drawing.Size(121, 20);
            this.cbxPort.TabIndex = 1;
            // 
            // btConnect
            // 
            this.btConnect.Location = new System.Drawing.Point(6, 20);
            this.btConnect.Name = "btConnect";
            this.btConnect.Size = new System.Drawing.Size(75, 23);
            this.btConnect.TabIndex = 0;
            this.btConnect.Text = "创建连接";
            this.btConnect.UseVisualStyleBackColor = true;
            this.btConnect.Click += new System.EventHandler(this.btConnect_Click);
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.btMessageClear);
            this.groupBox2.Controls.Add(this.tbMessage);
            this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.groupBox2.Location = new System.Drawing.Point(232, 0);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(568, 482);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "通讯信息";
            // 
            // btMessageClear
            // 
            this.btMessageClear.Location = new System.Drawing.Point(8, 19);
            this.btMessageClear.Name = "btMessageClear";
            this.btMessageClear.Size = new System.Drawing.Size(75, 23);
            this.btMessageClear.TabIndex = 1;
            this.btMessageClear.Text = "清空";
            this.btMessageClear.UseVisualStyleBackColor = true;
            this.btMessageClear.Click += new System.EventHandler(this.btMessageClear_Click);
            // 
            // tbMessage
            // 
            this.tbMessage.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.tbMessage.Location = new System.Drawing.Point(3, 48);
            this.tbMessage.Multiline = true;
            this.tbMessage.Name = "tbMessage";
            this.tbMessage.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.tbMessage.Size = new System.Drawing.Size(562, 431);
            this.tbMessage.TabIndex = 0;
            // 
            // timer1
            // 
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 482);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Name = "Form1";
            this.Text = "Slave从站";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nudSlaveID)).EndInit();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button Lamp1;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox cbxStopBits;
        private System.Windows.Forms.ComboBox cbxParity;
        private System.Windows.Forms.ComboBox cbxDataBits;
        private System.Windows.Forms.ComboBox cbxBaudRate;
        private System.Windows.Forms.ComboBox cbxPort;
        private System.Windows.Forms.Button btConnect;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.TextBox tbMessage;
        private System.Windows.Forms.Button btMessageClear;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.NumericUpDown nudSlaveID;
    }
}

后台代码

using Modbus.Data;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ModbusRtu_Slave
{
    public partial class Form1 : Form
    {
        #region 定义全局变量
        //端口序号
        private int serialPortName = 0;
        //控件中端口号
        string cbxPortName;
        //获取PC设备中已连接的串口号
        string[] getPortNames = null;
        //串口实例
        private SerialPort serialPort = new SerialPort();
        //ModbusRTU从站字段
        private static ModbusSerialSlave slave;
        //创建线程
        Task requestTask;
        //功能码
        byte functionCode;
        //整个消息内容
        byte[] data;
        //起始地址
        byte[] byteStartAddress;
        short StartAddress;
        //地址长度
        byte[] byteNum;
        short NumOfPoint;
        string dataString;
        int iAddress;
        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //窗口开启定时器默认打开
            timer1.Enabled = true;
            //设置默认选中项
            cbxBaudRate.SelectedIndex = 0;
            cbxDataBits.SelectedIndex = 0;
            cbxParity.SelectedIndex = 2;
            cbxStopBits.SelectedIndex = 0;
            //通讯信息文本框清空
            tbMessage.Text = "";
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            cbxPortName = cbxPort.Text;
            try
            {
                getPortNames = SerialPort.GetPortNames();

                if (serialPortName != getPortNames.Length)
                {
                    serialPortName = getPortNames.Length;

                    cbxPort.Items.Clear();
                    cbxPort.Text = null;

                    for (int i = 0; i < serialPortName; i++)//判断串口刷新后状态
                    {
                        if (getPortNames[i] == cbxPortName) { cbxPort.Text = cbxPortName; }
                        cbxPort.Items.Add(getPortNames[i]);
                    }
                    cbxPort.Text = getPortNames[0];
                    serialPort.PortName = cbxPort.Text;
                }
            }

            catch (Exception ex)
            {
                if (ex.Source != null)
                {
                }
            }

            if (Lamp1.BackColor == Color.Red)
            {
                Lamp1.BackColor = Color.Green;
            }
            else
            {
                Lamp1.BackColor = Color.Red;
            }
        }

        /// <summary>
        /// 获取窗体选中的奇偶校验
        /// </summary>
        /// <returns></returns>
        private Parity GetSelectedParity()
        {
            switch (cbxParity.SelectedItem.ToString())
            {
                case "Odd":
                    return Parity.Odd;
                case "Even":
                    return Parity.Even;
                case "None":
                    return Parity.None;
                default:
                    return Parity.None;
            }
        }

        /// <summary>
        /// 获取窗体选中的停止位
        /// </summary>
        /// <returns></returns>
        private StopBits GetSelectedStopBits()
        {
            switch (cbxStopBits.SelectedItem.ToString())
            {
                case "One":
                    return StopBits.One;
                case "Two":
                    return StopBits.Two;
                default:
                    return StopBits.One;
            }
        }

        void ShowMesage(string Mes)//通讯显示函数
        {
            tbMessage.Invoke(new Action(() => { tbMessage.AppendText(Mes + "\r\n"); }));
        }

        /// <summary>
        /// 创建连接事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btConnect_Click(object sender, EventArgs e)
        {
            //启动连接
            if (serialPort.IsOpen)
            {
                timer1.Enabled = true;
                serialPort.Close();

                slave.ModbusSlaveRequestReceived -= new EventHandler<ModbusSlaveRequestEventArgs>(Modbus_Request_Event);
                slave.DataStore.DataStoreWrittenTo -= new EventHandler<DataStoreEventArgs>(Modbus_DataStoreWriteTo);

                btConnect.Text = "创建连接";
                ShowMesage(serialPort.PortName.ToString() + "," + serialPort.BaudRate.ToString() + "," + serialPort.DataBits.ToString() + ","
                    + serialPort.Parity.ToString() + "," + serialPort.StopBits.ToString() + "," + "通信已断开");
            }
            else
            {
                try
                {
                    timer1.Enabled = false;
                    //创建Rtu从站
                    serialPort.PortName = cbxPort.SelectedItem.ToString();//"COM11"; 
                    serialPort.BaudRate = Convert.ToInt32(cbxBaudRate.SelectedItem);
                    serialPort.DataBits = Convert.ToInt32(cbxDataBits.SelectedItem);
                    serialPort.Parity = GetSelectedParity();
                    serialPort.StopBits = GetSelectedStopBits();
                    serialPort.Open();

                    //创建Modbus RTU从站
                    slave = ModbusSerialSlave.CreateRtu((byte)nudSlaveID.Value, serialPort);
                    //Modbus从站获取主站请求
                    requestTask = new Task(Modubus_RequestReceive);
                    requestTask.Start();

                    Lamp1.BackColor = Color.Green;
                }
                catch (Exception ex)
                {
                    btConnect.Text = "创建连接";
                    ShowMesage(serialPort.PortName.ToString() + "," + serialPort.BaudRate.ToString() + "," + serialPort.DataBits.ToString() + ","
                    + serialPort.Parity.ToString() + "," + serialPort.StopBits.ToString() + "," + "通信未建立,原因:" + ex.Message);
                    return;
                }

                btConnect.Text = "断开连接";
                ShowMesage(serialPort.PortName.ToString() + "," + serialPort.BaudRate.ToString() + "," + serialPort.DataBits.ToString() + ","
                + serialPort.Parity.ToString() + "," + serialPort.StopBits.ToString() + "," + "通信已建立");
            }
        }
/// <summary>
        /// 新线程中执行Modbus主站的请求数据
        /// </summary>
        private void Modubus_RequestReceive()
        {
            slave.ModbusSlaveRequestReceived += new EventHandler<ModbusSlaveRequestEventArgs>(Modbus_Request_Event); 
            slave.DataStore = Modbus.Data.DataStoreFactory.CreateDefaultDataStore();
            slave.DataStore.DataStoreWrittenTo += new EventHandler<DataStoreEventArgs>(Modbus_DataStoreWriteTo);
            slave.Listen();
        }

        /// <summary>
        /// 主站的请求事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Modbus_Request_Event(object sender, Modbus.Device.ModbusSlaveRequestEventArgs e)
        {
            try
            {
                /*
                功能码:
                1:读线圈寄存器
                2:读离散输入状态
                3:读保持寄存器
                4:读输入寄存器
                5:写入单个线圈
                6:写入单个保持寄存器
                15:写多个线圈
                16:写多个保持寄存器
                 */
                functionCode = e.Message.FunctionCode;

                data = e.Message.MessageFrame;

                byteStartAddress = new byte[] { data[3], data[2] };

                byteNum = new byte[] { data[5], data[4] };

                StartAddress = BitConverter.ToInt16(byteStartAddress, 0);

                NumOfPoint = BitConverter.ToInt16(byteNum, 0);

                /*
                if (functionCode.ToString() == "6")
                {
                    //AO
                    slave.DataStore.HoldingRegisters[StartAddress] = 16;
                    slave.DataStore.HoldingRegisters[StartAddress + 1] = 17;
                }
                */

                
                ShowMesage(functionCode.ToString() + "," + StartAddress.ToString() + "," + NumOfPoint.ToString());
            }
            catch (Exception ex)
            {
                //Form1.runStatusFile.WriteString("", "readReg", "3");
                //Form1.runStatusFile.WriteString("", "readRegErrorMsg", ex.Message);
                ShowMesage(ex.Message);
            }
        }
        /// <summary>
        /// 数据存储事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Modbus_DataStoreWriteTo(object sender, Modbus.Data.DataStoreEventArgs e)
        {
            //this.Text = "DataType=" + e.ModbusDataType.ToString() + "  StartAdress=" + e.StartAddress;
            
            iAddress = e.StartAddress;//e.StartAddress;
            dataString = "";

            switch (e.ModbusDataType)
            {
                //保持寄存器
                case ModbusDataType.HoldingRegister:
                    for (int i = 0; i < e.Data.B.Count; i++)
                    {
                        //模拟量输出
                        slave.DataStore.HoldingRegisters[e.StartAddress + i + 1] = e.Data.B[i];

                        dataString += e.Data.B[i].ToString() + "_";

                        //DoAOUpdate(iAddress, e.Data.B[i].ToString());
                        iAddress++;
                    }
                    ShowMesage("功能码:" + functionCode.ToString() + ",起始地址:" + StartAddress.ToString() + ",地址长度:" + NumOfPoint.ToString()+",接收数据:" + dataString);
                    break;
                //线圈
                case ModbusDataType.Coil:
                    for (int i = 0; i < e.Data.A.Count; i++)
                    {
                        //数字量输出
                        slave.DataStore.CoilDiscretes[e.StartAddress + i + 1] = e.Data.A[i];

                        dataString += e.Data.A[i].ToString()+"_";

                        //DoDOUpdate(iAddress, e.Data.A[i]);
                        iAddress++;
                        if (e.Data.A.Count == 1)
                        {
                            break;
                        }
                    }
                    ShowMesage("功能码:" + functionCode.ToString() + ",起始地址:" + StartAddress.ToString() + ",地址长度:" + NumOfPoint.ToString() + ",接收数据:" + dataString);
                    break;
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (serialPort.PortName != null)
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                if (ex.Source != null)
                {

                }
            }
        }

        private void btMessageClear_Click(object sender, EventArgs e)
        {
            tbMessage.Text = "";
        }

        
    }
}

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值