C# NModbus4 TCP 主从站通信样例
的记录连接地址:https://blog.csdn.net/iml6yu/article/details/127748518
补充完成对NModbus 的简要使用的记录,因为NModbus4不更新,也不支持core,所以补充一个NModbus 的使用。
见 https://blog.csdn.net/iml6yu/article/details/127748518
偷懒,沿用了之前的4.8的项目继续做的。
<package id="NModbus" version="3.0.72" targetFramework="net48" />
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 });
}
}
}
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");
}));
}
}
});
}
}
}
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