NetCore下模拟和使用Modbus工业通信协议

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, 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来模拟展现,可以写入或读写寄存器

  

 

posted @ 2017-12-01 13:13  leeolevis  阅读(3788)  评论(2编辑  收藏  举报