Tips:
1、目前NetCore下与Modbus通信的框架主要选择了 Modbus.Net https://github.com/parallelbgls/Modbus.Net
2、modbus是常用的工业通信协议,在软件调试时可以通过modbus poll+slave模拟通信通过达到调试目的,下图是我使用软件
1)为串口模拟工具
2)为Modbus Slave模拟工具
3)为Modbus Poll模拟,修改对应Value值即可发送到Slave
调用和测试代码:
public class ModbusTest
{
public Dictionary<string, ReturnUnit> GetModbusValues(List<AddressUnit> addresses, ModbusType connectType = ModbusType.Tcp, string connectString = "127.0.0.1")
{
var _modbusTcpMachine = new ModbusMachine(connectType, connectString, addresses, true, , ); var result = _modbusTcpMachine.GetDatas(MachineGetDataType.Address); return result;
} public bool SetModbusValues(List<AddressUnit> addresses, Dictionary<string, double> setDict, ModbusType connectType = ModbusType.Tcp, string connectString = "127.0.0.1")
{
var _modbusTcpMachine = new ModbusMachine(connectType, connectString, addresses, true, , ); var result = _modbusTcpMachine.SetDatas(MachineSetDataType.Address, setDict); return result;
} //获取测试
[Obsolete("固定写死的测试方法,临时测试用")]
public void TestGetModbusValues()
{
var addresses = new List<AddressUnit>();
for (int i = ; i < ; i++)
{
addresses.Add(new AddressUnit { Id = "", Area = "4X", Address = i + , DataType = typeof(ushort) });
} var _modbusTcpMachine = new ModbusMachine(ModbusType.RtuInTcp, "127.0.0.1", addresses, true, , ); var result = _modbusTcpMachine.GetDatas(MachineGetDataType.Address); foreach (var item in result)
{
Console.WriteLine($"Key:{item.Key} Value:{item.Value.PlcValue}");
}
} //设置测试
[Obsolete("固定写死的测试方法,临时测试用")]
public void TestSetModbusValues()
{
var addresses = new List<AddressUnit>();
var setDict = new Dictionary<string, double>();
for (int i = ; i < ; i++)
{
addresses.Add(new AddressUnit { Id = "", Area = "4X", Address = i + , DataType = typeof(ushort) });
var r = new Random();
var intValue = r.Next(, );
System.Threading.Thread.Sleep();
setDict.Add($"4X {i + 1}.0", intValue);
} var _modbusTcpMachine = new ModbusMachine(ModbusType.RtuInTcp, "127.0.0.1", addresses, true, , ); _modbusTcpMachine.SetDatas(MachineSetDataType.Address, setDict);
}
}
也可以使用Modbus-TCP Client Tester来模拟展现,可以写入或读写寄存器