Esempio n. 1
0
        public async Task TestFloat()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            float?data = await modbus.ReadFloatAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            await modbus.WriteFloatAsync(MODBUS_SLAVE, 0, 1.234F);

            data = await modbus.ReadFloatAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal(1.234F, data);
            await modbus.WriteFloatAsync(MODBUS_SLAVE, 0, 0);

            data = await modbus.ReadFloatAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal(0, data);
            data = await modbus.ReadOnlyFloatAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
        }
Esempio n. 2
0
        void MakeSureClientIsConnected()
        {
            if (_client != null && !_client.Connected)
            {
                _client.Dispose();
                _client = null;
                _adapter.Dispose();
                _adapter = null;
                _master.Dispose();
                _master = null;
            }

            if (_client == null)
            {
                _client  = new TcpClient(_configuration.Ip, _configuration.Port);
                _adapter = new TcpClientAdapter(_client);
                var factory = new ModbusFactory();
                if (_configuration.UseASCII)
                {
                    _master = factory.CreateAsciiMaster(_adapter);
                }
                else if (_configuration.Protocol == Protocol.Tcp)
                {
                    _master = factory.CreateMaster(_client);
                }
                else
                {
                    _master = factory.CreateRtuMaster(_adapter);
                }
            }
        }
        /// <summary>
        /// 读寄存器(多个数据)
        /// </summary>
        /// <param name="slaveAddress">从站地址</param>
        /// <param name="registerAddress">寄存器地址</param>
        /// <param name="numberOfPoints">读取的数量</param>
        /// <param name="values">数据</param>
        public void ReadRegister(byte slaveAddress, ushort registerAddress, ushort numberOfPoints, out ushort[] values)
        {
            using (SerialPort port = new SerialPort(SerialPortName))
            {
                //配置串口
                port.BaudRate = BaudRate;
                port.DataBits = 8;
                port.Parity   = Parity.Even;
                port.StopBits = StopBits.One;
                port.Open();

                //创建Modbus主机
                var adapter = new SerialPortAdapter(port);
                adapter.ReadTimeout  = ReadTimeout;
                adapter.WriteTimeout = WriteTimeout;
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateRtuMaster(adapter);

                lock (_modbusLock)
                {
                    //读寄存器
                    values = master.ReadHoldingRegisters(slaveAddress, registerAddress, numberOfPoints);
                }
            }
        }
Esempio n. 4
0
        public static async Task StartModbusSerialRtuSlaveWithCustomStore()
        {
            using (SerialPort slavePort = new SerialPort(PrimarySerialPortName))
            {
                // configure serial port
                slavePort.BaudRate = 9600;
                slavePort.DataBits = 8;
                slavePort.Parity   = Parity.None;
                slavePort.StopBits = StopBits.One;
                slavePort.Open();

                var factory      = new ModbusFactory();
                var slaveNetwork = factory.CreateRtuSlaveNetwork(slavePort);

                var dataStore = new SlaveStorage();

                dataStore.CoilDiscretes.StorageOperationOccurred    += (sender, args) => Console.WriteLine($"Coil discretes: {args.Operation} starting at {args.StartingAddress}");
                dataStore.CoilInputs.StorageOperationOccurred       += (sender, args) => Console.WriteLine($"Coil inputs: {args.Operation} starting at {args.StartingAddress}");
                dataStore.InputRegisters.StorageOperationOccurred   += (sender, args) => Console.WriteLine($"Input registers: {args.Operation} starting at {args.StartingAddress}");
                dataStore.HoldingRegisters.StorageOperationOccurred += (sender, args) => Console.WriteLine($"Holding registers: {args.Operation} starting at {args.StartingAddress}");

                IModbusSlave slave1 = factory.CreateSlave(1, dataStore);

                slaveNetwork.AddSlave(slave1);

                await slaveNetwork.ListenAsync();
            }
        }
Esempio n. 5
0
        /// <summary>
        ///     Write a 32 bit value.
        /// </summary>
        public static void ReadWrite32BitValue()
        {
            using (SerialPort port = new SerialPort(PrimarySerialPortName))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                var factory = new ModbusFactory();
                IModbusRtuTransport transport = factory.CreateRtuTransport(port);
                IModbusSerialMaster master    = factory.CreateMaster(transport);

                byte   slaveId      = 1;
                ushort startAddress = 1008;
                uint   largeValue   = UInt16.MaxValue + 5;

                ushort lowOrderValue  = BitConverter.ToUInt16(BitConverter.GetBytes(largeValue), 0);
                ushort highOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(largeValue), 2);

                // write large value in two 16 bit chunks
                master.WriteMultipleRegisters(slaveId, startAddress, new ushort[] { lowOrderValue, highOrderValue });

                // read large value in two 16 bit chunks and perform conversion
                ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, 2);
                uint     value     = ModbusUtility.GetUInt32(registers[1], registers[0]);
            }
        }
Esempio n. 6
0
        /// <summary>
        ///     Simple Modbus TCP slave example.
        /// </summary>
        private void StartModbusTcpSlave()
        {
            int       port    = 504;
            byte      slaveid = 180;
            IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });

            Console.WriteLine($"Listening on '{address}:{port}' at slave ID={slaveid}.");

            // create and start the TCP slave
            TcpListener slaveTcpListener = new TcpListener(address, port);

            slaveTcpListener.Start();

            IModbusFactory      factory = new ModbusFactory();
            IModbusSlaveNetwork network = factory.CreateSlaveNetwork(slaveTcpListener);

            _storage.HoldingRegisters.StorageOperationOccurred += HoldingRegistersStorageOperationOccurred;

            IModbusSlave slave = factory.CreateSlave(slaveid, _storage);

            network.AddSlave(slave);
            network.ListenAsync().GetAwaiter().GetResult();

            // prevent the main thread from exiting
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 7
0
        /// <summary>
        ///     Simple Modbus serial ASCII master read holding registers example.
        /// </summary>
        public static void ModbusSerialAsciiMasterReadRegisters()
        {
            using (SerialPort port = new SerialPort(PrimarySerialPortName))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                var factory = new ModbusFactory();
                IModbusSerialMaster master = factory.CreateAsciiMaster(port);

                byte   slaveId      = 1;
                ushort startAddress = 1;
                ushort numRegisters = 5;

                // read five registers
                ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

                for (int i = 0; i < numRegisters; i++)
                {
                    Console.WriteLine($"Register {startAddress + i}={registers[i]}");
                }
            }

            // output:
            // Register 1=0
            // Register 2=0
            // Register 3=0
            // Register 4=0
            // Register 5=0
        }
Esempio n. 8
0
        public async Task TestBytes()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            byte[] data = await modbus.ReadBytesAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            await modbus.WriteBytesAsync(MODBUS_SLAVE, 0, new byte[] { 1, 2, 3, 4, 5 });

            data = await modbus.ReadBytesAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new byte[] { 1, 2, 3, 4, 5 }, data);
            await modbus.WriteBytesAsync(MODBUS_SLAVE, 0, new byte[] { 0, 0, 0, 0, 0 });

            data = await modbus.ReadBytesAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new byte[] { 0, 0, 0, 0, 0 }, data);
            data = await modbus.ReadOnlyBytesAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
        }
Esempio n. 9
0
        private static void Main(string[] args)
        {
            const int   port             = 502;
            IPAddress   localaddr        = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener slaveTcpListener = new TcpListener(localaddr, port);

            slaveTcpListener.Start();
            // NullModbusLogger.Instance = ;

            IModbusFactory      factory = new ModbusFactory(null, true, new ReadLogger());
            IModbusSlaveNetwork network = factory.CreateSlaveNetwork(slaveTcpListener);
            List <string>       ips     = new List <string> {
                "192.168.8.200", "192.168.8.201", "192.168.8.202"
            };

            for (int i = 0; i < ips.Count; i++)
            {
                SlaveStorage           storage = new SlaveStorage();
                ElektronikondataReader reader  = new ElektronikondataReader(i + 1, storage);
                Task.Factory.StartNew(ElektronikondataReader.ReadDataThread, reader);
                IModbusSlave slave = factory.CreateSlave((byte)i, storage);
                network.AddSlave(slave);
            }

            network.ListenAsync().GetAwaiter().GetResult();

            // prevent the main thread from exiting
            // Thread.Sleep(Timeout.Infinite);


            Console.WriteLine("Press any key to exit " + args);
            Console.ReadKey();
        }
Esempio n. 10
0
        public async Task TestDoubleArrayAsync()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            double[] data = await modbus.ReadDoubleArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            await modbus.WriteDoubleArrayAsync(MODBUS_SLAVE, 0, new double[] { 0.12345, 1.2345, 12.345, 123.45, 1234.5 });

            data = await modbus.ReadDoubleArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new double[] { 0.12345, 1.2345, 12.345, 123.45, 1234.5 }, data);
            await modbus.WriteDoubleArrayAsync(MODBUS_SLAVE, 0, new double[] { 0, 0, 0, 0, 0 });

            data = await modbus.ReadDoubleArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new double[] { 0, 0, 0, 0, 0 }, data);
            data = await modbus.ReadOnlyDoubleArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
        }
Esempio n. 11
0
        public async Task TestLongArrayAsync()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            long[] data = await modbus.ReadLongArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            await modbus.WriteLongArrayAsync(MODBUS_SLAVE, 0, new long[] { -1, -2, -3, -4, -5 });

            data = await modbus.ReadLongArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new long[] { -1, -2, -3, -4, -5 }, data);
            await modbus.WriteLongArrayAsync(MODBUS_SLAVE, 0, new long[] { 0, 0, 0, 0, 0 });

            data = await modbus.ReadLongArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new long[] { 0, 0, 0, 0, 0 }, data);
            data = await modbus.ReadOnlyLongArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
        }
Esempio n. 12
0
        public async Task TestBoolArrayAsync()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            bool[] data = await modbus.ReadBoolArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            await modbus.WriteBoolArrayAsync(MODBUS_SLAVE, 0, new bool[] { true, false, true, true, false });

            data = await modbus.ReadBoolArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new bool[] { true, false, true, true, false }, data);
            await modbus.WriteBoolArrayAsync(MODBUS_SLAVE, 0, new bool[] { false, false, false, false, false });

            data = await modbus.ReadBoolArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
            Assert.Equal(new bool[] { false, false, false, false, false }, data);
            data = await modbus.ReadOnlyBoolArrayAsync(MODBUS_SLAVE, 0, 5);

            Assert.Equal(5, data.Length);
        }
Esempio n. 13
0
        public async Task TestULong()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            ulong?data = await modbus.ReadULongAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            await modbus.WriteULongAsync(MODBUS_SLAVE, 0, 2000000);

            data = await modbus.ReadULongAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal((ulong)2000000, data);
            await modbus.WriteULongAsync(MODBUS_SLAVE, 0, 0);

            data = await modbus.ReadULongAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal((ulong)0, data);
            data = await modbus.ReadOnlyULongAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
        }
Esempio n. 14
0
        public async Task TestDouble()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            double?data = await modbus.ReadDoubleAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            await modbus.WriteDoubleAsync(MODBUS_SLAVE, 0, 1.23456789);

            data = await modbus.ReadDoubleAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal(1.23456789, data);
            await modbus.WriteDoubleAsync(MODBUS_SLAVE, 0, 0);

            data = await modbus.ReadDoubleAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal(0, data);
            data = await modbus.ReadOnlyDoubleAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
        }
Esempio n. 15
0
        /// <summary>
        /// 读多个寄存器
        /// </summary>
        /// <param name="slaveAddress">从站地址</param>
        /// <param name="registerAddress">寄存器地址</param>
        /// <param name="value">数据</param>
        private void ModbusSerialRtuMasterReadRegister(byte slaveAddress, ushort registerAddress, ushort numberOfPoints, out ushort[] data)
        {
            data = null;
            using (SerialPort port = new SerialPort(PrimarySerialPortName))
            {
                //配置串口
                port.BaudRate = SerialPortBaudRate;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                //创建Modbus主机
                var adapter = new SerialPortAdapter(port);
                adapter.ReadTimeout  = ReadTimeout;
                adapter.WriteTimeout = WriteTimeout;
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateRtuMaster(adapter);

                lock (powerLock)
                {
                    //读寄存器
                    data = master.ReadHoldingRegisters(slaveAddress, registerAddress, numberOfPoints);
                }
            }
        }
Esempio n. 16
0
        public bool TryConnectModbus(ModbusSystem config)
        {
            try
            {
                if (tcpClient != null)
                {
                    tcpClient.Dispose();
                    tcpClient = null;
                    //master.Dispose();
                    //master = null;
                }
                _config   = config;
                tcpClient = new TcpClient(config.IpAddress, config.PortNum);
                var factory = new ModbusFactory();

                master = factory.CreateMaster(tcpClient);

                return(true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "#### MODBUS CONNECTING FAILED ####");
                return(false);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 写多个寄存器
        /// </summary>
        /// <param name="slaveAddress">从站地址</param>
        /// <param name="registerAddress">寄存器地址</param>
        /// <param name="data">数据</param>
        private void ModbusSerialRtuMasterWriteRegister(byte slaveAddress, ushort registerAddress, ushort[] data)
        {
            using (SerialPort port = new SerialPort(PrimarySerialPortName))
            {
                //配置串口
                port.BaudRate = SerialPortBaudRate;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                //创建Modbus主机
                var adapter = new SerialPortAdapter(port);
                adapter.ReadTimeout  = ReadTimeout;
                adapter.WriteTimeout = WriteTimeout;
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateRtuMaster(adapter);

                lock (powerLock)
                {
                    //写到寄存器
                    master.WriteMultipleRegisters(slaveAddress, registerAddress, data);
                }
            }
        }
        public async Task StartModbusSerialRtuSlaveWithCustomStore()
        {
            using (SerialPort slavePort = new SerialPort(PrimarySerialPortName))
            {
                // configure serial port
                slavePort.BaudRate = 9600;
                slavePort.DataBits = 8;
                slavePort.Parity   = Parity.None;
                slavePort.StopBits = StopBits.One;
                slavePort.Open();

                var factory      = new ModbusFactory();
                var slaveNetwork = factory.CreateRtuSlaveNetwork(slavePort);

                slavePort.ReadTimeout  = 500;
                slavePort.WriteTimeout = 500;

                var dataStore  = new SlaveStorage();
                var dataStore2 = new SlaveStorage();

                dataStore.HoldingRegisters.StorageOperationOccurred += HoldingRegisters_StorageOperationOccurred;

                IModbusSlave slave1 = factory.CreateSlave(1, dataStore);
                IModbusSlave slave2 = factory.CreateSlave(2, dataStore2);

                slaveNetwork.AddSlave(slave1);
                slaveNetwork.AddSlave(slave2);
                //  await slaveNetwork.ListenAsync();
                await slaveNetwork.ListenWorkAroundAsync(new CancellationToken());
            }
        }
        private void Reconnect(object obj)
        {
            if (_disabled)
            {
                return;
            }

            try
            {
                var client  = new TcpClient(_ip, _port);
                var factory = new ModbusFactory();
                _master = factory.CreateMaster(client);

                SetConnected(true);
            }
            catch (Exception e)
            {
                Logger.Error(e, "Не удалось подключиться к Modbus TCP серверу");

                if (_connected)
                {
                    SetConnected(false);
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        ///     Simple Modbus TCP slave example.
        /// </summary>
        public static void StartModbusTcpSlave()
        {
            IPAddress address = new IPAddress(new byte[] { 0, 0, 0, 0 });

            // create and start the TCP slave
            TcpListener slaveTcpListener = new TcpListener(address, _port);

            slaveTcpListener.Start();

            IModbusFactory factory = new ModbusFactory();

            IModbusSlaveNetwork network = factory.CreateSlaveNetwork(slaveTcpListener);

            for (byte i = 1; i <= _maxDeviceId; i++)
            {
                var          dataStore = new MySlaveDataStore(_maxSize);
                IModbusSlave slave     = factory.CreateSlave(i, dataStore);
                network.AddSlave(slave);
                SlaveDataStores.Add(i, dataStore);
            }

            network.ListenAsync().GetAwaiter().GetResult();

            // prevent the main thread from exiting
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 21
0
        /// <summary>
        ///     Simple Modbus TCP master read inputs example.
        /// </summary>
        public static void ModbusTcpMasterReadInputs()
        {
            using (TcpClient client = new TcpClient("127.0.0.1", 502))
            {
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateMaster(client);

                // read five input values
                ushort startAddress = 100;
                ushort numInputs    = 5;
                bool[] inputs       = master.ReadInputs(0, startAddress, numInputs);

                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Input {(startAddress + i)}={(inputs[i] ? 1 : 0)}");
                }
            }

            // output:
            // Input 100=0
            // Input 101=0
            // Input 102=0
            // Input 103=0
            // Input 104=0
        }
Esempio n. 22
0
        /// <summary>
        ///     Simple Modbus TCP slave example.
        /// </summary>
        private void StartModbusTcpSlave()
        {
            IPAddress ipaddress = IPAddress.Parse(Address);

            Console.WriteLine($"Listening on '{Address}:{Port}' at slave ID={SlaveID}.");

            // create and start the TCP slave
            TcpListener slaveTcpListener = new TcpListener(ipaddress, Port);

            slaveTcpListener.Start();

            IModbusFactory      factory = new ModbusFactory();
            IModbusSlaveNetwork network = factory.CreateSlaveNetwork(slaveTcpListener);

            // Set the storage operation event handlers.
            _storage.InputRegisters.StorageOperationOccurred   += InputRegistersStorageOperationOccurred;
            _storage.HoldingRegisters.StorageOperationOccurred += HoldingRegistersStorageOperationOccurred;

            // Start the update timer.
            _timer = new Timer(OnTimerElapsed, null, 0, -1);

            // create and start the Modbus slave
            IModbusSlave slave = factory.CreateSlave(SlaveID, _storage);

            network.AddSlave(slave);
            network.ListenAsync().GetAwaiter().GetResult();

            // prevent the main thread from exiting
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 23
0
        /// <summary>
        ///     Simple Modbus TCP slave example.
        /// </summary>
        public static void StartModbusTcpSlave()
        {
            int       port    = 502;
            IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });

            // create and start the TCP slave
            TcpListener slaveTcpListener = new TcpListener(address, port);

            slaveTcpListener.Start();

            IModbusFactory factory = new ModbusFactory();

            IModbusSlaveNetwork network = factory.CreateSlaveNetwork(slaveTcpListener);

            IModbusSlave slave1 = factory.CreateSlave(1);
            IModbusSlave slave2 = factory.CreateSlave(2);

            network.AddSlave(slave1);
            network.AddSlave(slave2);

            network.ListenAsync().GetAwaiter().GetResult();

            // prevent the main thread from exiting
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 24
0
        /// <summary>
        ///     Simple Modbus serial RTU slave example.
        /// </summary>
        public static void StartModbusSerialRtuSlave()
        {
            using (SerialPort slavePort = new SerialPort("COM2"))
            {
                // configure serial port
                slavePort.BaudRate = 9600;
                slavePort.DataBits = 8;
                slavePort.Parity   = Parity.None;
                slavePort.StopBits = StopBits.One;
                slavePort.Open();

                var adapter = new SerialPortAdapter(slavePort);

                var factory = new ModbusFactory();

                // create modbus slave
                var slaveNetwork = factory.CreateRtuSlaveNetwork(adapter);

                IModbusSlave slave1 = factory.CreateSlave(1);
                IModbusSlave slave2 = factory.CreateSlave(2);

                slaveNetwork.AddSlave(slave1);
                slaveNetwork.AddSlave(slave2);

                slaveNetwork.ListenAsync().GetAwaiter().GetResult();
            }
        }
Esempio n. 25
0
        public static async Task SendStart(SerialPort port, ushort address, int value)
        {
            var adapter = new SerialPortAdapter(port);
            // create modbus master
            var factory = new ModbusFactory();

            IModbusMaster master = factory.CreateRtuMaster(adapter);

            byte slaveId = 1;

            ushort[] result = new ushort[] {
                BitConverter.ToUInt16(BitConverter.GetBytes(value), 0),
                BitConverter.ToUInt16(BitConverter.GetBytes(value), 2)
            };
            // write three registers
            await master.WriteMultipleRegistersAsync(slaveId, address, result);

            // 写入距离二
            await master.WriteSingleCoilAsync(slaveId, 2054, true);

            await master.WriteSingleCoilAsync(slaveId, 2054, false);

            // 启动
            await master.WriteSingleCoilAsync(slaveId, 2078, true);

            // read registers
            //var x = await master.ReadHoldingRegistersAsync(slaveId, address, 2);
            //System.Diagnostics.Debug.WriteLine(BitConverter.ToInt32(BitConverter.GetBytes(x[0]).Concat(BitConverter.GetBytes(x[1])).ToArray(), 0));
        }
Esempio n. 26
0
        /// <summary>
        ///     Simple Modbus serial RTU master write holding registers example.
        /// </summary>
        public static void ModbusSerialRtuMasterWriteRegisters()
        {
            using (SerialPort port = new SerialPort("COM1"))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                var adapter = new SerialPortAdapter(port);
                // create modbus master
                var factory = new ModbusFactory();

                IModbusMaster master = factory.CreateRtuMaster(adapter);

                byte     slaveId      = 1;
                ushort   startAddress = 100;
                ushort[] registers    = new ushort[] { 1, 2, 3 };

                // write three registers
                master.WriteMultipleRegisters(slaveId, startAddress, registers);
            }
        }
        /// <summary>
        /// 读取线圈
        /// </summary>
        /// <param name="slaveAddress">从站地址</param>
        /// <param name="registerAddress">寄存器地址</param>
        /// <param name="value">数据</param>
        public void ReadCoil(byte slaveAddress, ushort registerAddress, out bool value)
        {
            value = false;
            using (SerialPort port = new SerialPort(SerialPortName))
            {
                //配置串口
                port.BaudRate = BaudRate;
                port.DataBits = 8;
                port.Parity   = Parity.Even;
                port.StopBits = StopBits.One;
                port.Open();

                //创建Modbus主机
                var adapter = new SerialPortAdapter(port);
                adapter.ReadTimeout  = ReadTimeout;
                adapter.WriteTimeout = WriteTimeout;
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateRtuMaster(adapter);

                lock (_modbusLock)
                {
                    //读寄存器
                    var values = master.ReadCoils(slaveAddress, registerAddress, 1);
                    if (values?.Length >= 1)
                    {
                        value = values[0];
                    }
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 读单个寄存器
        /// </summary>
        /// <param name="slaveAddress">从站地址</param>
        /// <param name="registerAddress">寄存器地址</param>
        /// <param name="value">数据</param>
        private void ModbusSerialRtuMasterReadRegister(byte slaveAddress, ushort registerAddress, out ushort value)
        {
            value = 0xFFFF;
            using (SerialPort port = new SerialPort(PrimarySerialPortName))
            {
                //配置串口
                port.BaudRate = SerialPortBaudRate;
                port.DataBits = 8;
                port.Parity   = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();

                //创建Modbus主机
                var adapter = new SerialPortAdapter(port);
                adapter.ReadTimeout  = ReadTimeout;
                adapter.WriteTimeout = WriteTimeout;
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateRtuMaster(adapter);

                lock (powerLock)
                {
                    //读寄存器
                    var values = master.ReadHoldingRegisters(slaveAddress, registerAddress, 1);
                    if (values?.Length >= 1)
                    {
                        value = values[0];
                    }
                }
            }
        }
        /// <summary>
        /// 写线圈
        /// </summary>
        /// <param name="slaveAddress">从站地址</param>
        /// <param name="registerAddress">寄存器地址</param>
        /// <param name="value">数据</param>
        public void WriteCoil(byte slaveAddress, ushort registerAddress, bool value)
        {
            using (SerialPort port = new SerialPort(SerialPortName))
            {
                //配置串口
                port.BaudRate = BaudRate;
                port.DataBits = 8;
                port.Parity   = Parity.Even;
                port.StopBits = StopBits.One;
                port.Open();

                //创建Modbus主机
                var adapter = new SerialPortAdapter(port);
                adapter.ReadTimeout  = ReadTimeout;
                adapter.WriteTimeout = WriteTimeout;
                var           factory = new ModbusFactory();
                IModbusMaster master  = factory.CreateRtuMaster(adapter);

                lock (_modbusLock)
                {
                    //写到寄存器
                    master.WriteSingleCoil(slaveAddress, registerAddress, value);
                }
            }
        }
Esempio n. 30
0
        public async Task TestInt32()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            int?data = await modbus.ReadInt32Async(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            await modbus.WriteInt32Async(MODBUS_SLAVE, 0, -2000);

            data = await modbus.ReadInt32Async(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal(-2000, data);
            await modbus.WriteInt32Async(MODBUS_SLAVE, 0, 0);

            data = await modbus.ReadInt32Async(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            Assert.Equal(0, data);
            data = await modbus.ReadOnlyInt32Async(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
        }