• C# NModbus TCP 主从站通信样例


    之前做过 C# NModbus4 TCP 主从站通信样例的记录

    连接地址:https://blog.csdn.net/iml6yu/article/details/127748518

    前提

    补充完成对NModbus 的简要使用的记录,因为NModbus4不更新,也不支持core,所以补充一个NModbus 的使用。

    效果图

    https://blog.csdn.net/iml6yu/article/details/127748518

    NModbus

    Nuget引用

    偷懒,沿用了之前的4.8的项目继续做的。

     <package id="NModbus" version="3.0.72" targetFramework="net48" />
    
    • 1

    NModbus中常用方法

    在这里插入图片描述

    Master 客户端代码

    using NModbus;
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using static System.Windows.Forms.AxHost;
    
    /*
     * 注释:
     * 当使用Modbus-TCP时,往往使用Slave作为服务端
     * 所以NModbus-TCP中主站使用的时Slave对象
     */
    namespace NModBus4.Master
    {
        public partial class Form1 : Form
        {
            private TcpListener listener;
            private IModbusSlave slave;
            private IModbusFactory factory;
            private IModbusSlaveNetwork network;
            private CancellationTokenSource tokenSource;
    
            public Form1()
            {
                InitializeComponent();
                factory = new ModbusFactory();
            }
    
            /// 
            /// 启动
            /// 
            /// 
            /// 
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
    
                    listener = new TcpListener(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
                    //Task.Run(() =>
                    //{
                    listener.Start();
                    network = factory.CreateSlaveNetwork(listener);
    
                    /*
                     * 通过源码分析可以得到,如果不指定Store,默认会给一个DefaultSlaveDataStore
                     *     public IModbusSlave CreateSlave(byte unitId, ISlaveDataStore dataStore = null)
                     *       {
                     *           if (dataStore == null)
                     *               dataStore = new DefaultSlaveDataStore();
                     *
                     *           return new ModbusSlave(unitId, dataStore, GetAllFunctionServices());
                     *       }
                     */
                    slave = factory.CreateSlave(1);
                    network.AddSlave(slave);
                    network.ListenAsync();
                    //}); 
                    button1.Enabled = false;
                    tokenSource = new CancellationTokenSource();
                    //轮询读取线圈数据
                    ReadColDatas();
                }
                catch (Exception)
                {
    
                    throw;
                }
    
            }
    
            bool[] values =new bool[10];
            private void ReadColDatas()
            {
                Task.Run(() =>
                {
                    while (!tokenSource.IsCancellationRequested)
                    {
                        Task.Delay(TimeSpan.FromSeconds(1)).Wait();
                        var current  = slave.DataStore.CoilDiscretes.ReadPoints(0, 10);
                        if (string.Join("", current) != string.Join("", values))
                        {
                            values = current;
                            this.Invoke(new Action(() => {
                                richTextBox1.AppendText("数据发生变化:\r\n" + string.Join(",", values) + "\r\n");
                            }));
                        }
                    }
                });
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                network.Dispose();
                button1.Enabled = true;
            }
    
            /// 
            /// 写数据
            /// 
            /// 
            /// 
            private void button3_Click(object sender, EventArgs e)
            {
                //CoilDiscretes表示一个Bit,也就是一个bool类型
                slave.DataStore.CoilDiscretes.WritePoints((ushort)cliAddress.Value, new bool[] { cliValue.Value == 1 ? true : false });
                //HoldingRegisters表示一个无符号的16位整数(2的16次幂:0-65535)
                slave.DataStore.HoldingRegisters.WritePoints((ushort)holAddress.Value, new ushort[] { (ushort)holValue.Value });
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114

    从站客户端代码

    using NModbus;
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using static System.Windows.Forms.AxHost;
    
    namespace NModBus4.从站
    {
        public partial class Form1 : Form
        {
            private TcpClient client;
            private IModbusMaster master;
            private IModbusFactory factory; 
            public CancellationTokenSource tokenSource= new CancellationTokenSource();  
            public Form1()
            {
                InitializeComponent();
                factory = new ModbusFactory();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                client = new TcpClient();
                client.Connect(IPAddress.Parse(textBox1.Text.Trim()),  int.Parse(textBox2.Text));
                master = factory.CreateMaster(client) ; 
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                tokenSource.Cancel();
                master.Dispose();
            }
    
            /// 
            /// 写线圈
            /// 
            /// 
            /// 
            private void button3_Click(object sender, EventArgs e)
            { 
                master.WriteSingleCoil(1,(ushort)cliAddress.Value, cliValue.Value==1?true:false);
            }
    
            /// 
            /// 定时读取数据
            /// 
            /// 
            /// 
            private void button4_Click(object sender, EventArgs e)
            {
                ReadColDatas(); 
            }
    
            bool[] values = new bool[10];
            private void ReadColDatas()
            {
                Task.Run(() =>
                {
                    while (!tokenSource.IsCancellationRequested)
                    {
                        Task.Delay(TimeSpan.FromSeconds(1)).Wait();
                        var current = master.ReadCoils(1, 0, 10);
                        if (string.Join("", current) != string.Join("", values))
                        {
                            values = current;
                            this.Invoke(new Action(() => {
                                richTextBox1.AppendText("数据发生变化:\r\n" + string.Join(",", values) + "\r\n");
                            }));
                        }
                    }
                });
            }
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79

    demo 下载

    https://download.csdn.net/download/iml6yu/87060108

    引用

    https://www.cnblogs.com/pandefu/p/10824331.html
    https://nmodbus.github.io/api/NModbus.Data.html
    https://www.cnblogs.com/Samberger/p/13039429.html (读写字符串,浮点型数据)
    https://blog.csdn.net/helldoger/article/details/122184111

  • 相关阅读:
    2023最新SSM计算机毕业设计选题大全(附源码+LW)之java小区宠物信息管理系统0v9l2
    【CSS】网格布局
    【Git】02-Git常见应用
    计算机网络复习
    数学建模插值分析法(附完整代码)python实现(插值&拟合)
    el-select
    攻克3D神器Blender的第五天-【多边形建形、旋转】
    ARM/DSP+FPGA运动控制机器视觉控制器方案定制
    List集合&UML图
    解决vite首次加载很慢的问题
  • 原文地址:https://blog.csdn.net/iml6yu/article/details/127846177