Tips:git
一、目前NetCore下與Modbus通訊的框架主要選擇了 Modbus.Net https://github.com/parallelbgls/Modbus.Netgithub
二、modbus是經常使用的工業通訊協議,在軟件調試時能夠經過modbus poll+slave模擬通訊經過達到調試目的,下圖是我使用軟件框架
1)爲串口模擬工具dom
2)爲Modbus Slave模擬工具工具
3)爲Modbus Poll模擬,修改對應Value值便可發送到Slave測試
調用和測試代碼:spa
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, 2, 0); 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, 2, 0); var result = _modbusTcpMachine.SetDatas(MachineSetDataType.Address, setDict); return result; } //獲取測試 [Obsolete("固定寫死的測試方法,臨時測試用")] public void TestGetModbusValues() { var addresses = new List<AddressUnit>(); for (int i = 0; i < 6; i++) { addresses.Add(new AddressUnit { Id = "1", Area = "4X", Address = i + 1, DataType = typeof(ushort) }); } var _modbusTcpMachine = new ModbusMachine(ModbusType.RtuInTcp, "127.0.0.1", addresses, true, 2, 0); 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 = 0; i < 6; i++) { addresses.Add(new AddressUnit { Id = "1", Area = "4X", Address = i + 1, DataType = typeof(ushort) }); var r = new Random(); var intValue = r.Next(0, 100); System.Threading.Thread.Sleep(100); setDict.Add($"4X {i + 1}.0", intValue); } var _modbusTcpMachine = new ModbusMachine(ModbusType.RtuInTcp, "127.0.0.1", addresses, true, 2, 0); _modbusTcpMachine.SetDatas(MachineSetDataType.Address, setDict); } }
也能夠使用Modbus-TCP Client Tester來模擬展示,能夠寫入或讀寫寄存器
3d