Example #1
0
        static void Main(string[] args)
        {
            int port    = 502;
            var address = new IPAddress(new byte[] { 127, 0, 0, 1 });

            var factory = new ModbusFactory();

            using (var serialPort = new SerialPort("COM1"))
            {
                var adapter          = new SerialPortAdapter(serialPort);
                var master           = factory.CreateRtuMaster(adapter);
                var slaveTcpListener = new TcpListener(address, port);
                slaveTcpListener.Start();

                var tcpNetwork = factory.CreateSlaveNetwork(slaveTcpListener);
                var proxy1     = factory.CreateSlaveProxy(1, master);
                var proxy2     = factory.CreateSlaveProxy(2, master);
                tcpNetwork.AddSlave(proxy1);
                tcpNetwork.AddSlave(proxy2);

                var tcpClient    = new TcpClient(address.ToString(), port);
                var secondMaster = factory.CreateMaster(tcpClient);

                ushort[] holdingRegs = secondMaster.ReadHoldingRegisters(1, 1, 2);
            }
        }
Example #2
0
 public void Connection()
 {
     try
     {
         ClientTcp.Connect(IpAdresse, Cst_PortModbus);
         var factory = new ModbusFactory();
         ModBusMaster = factory.CreateMaster(ClientTcp);
         //DeleteUnexistingGroupe();
         Redresseurs = Model.Redresseur.GetAllRedresseurFromAutotameId(IpAdresse);
         foreach (Model.Redresseur redresseur in Redresseurs)
         {
             redresseur.ModBusMaster = ModBusMaster;
         }
         Mode = MODES.Connected.ToString();
     }
     catch (ArgumentNullException e)
     {
         Mode = MODES.Disconnected.ToString();
         Console.WriteLine("ArgumentNullException: {0}", e);
     }
     catch (SocketException e)
     {
         Mode = MODES.Disconnected.ToString();
         Console.WriteLine("SocketException: {0}", e);
     }
 }
Example #3
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);
        }
Example #4
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);
                }
            }
        }
Example #5
0
        private IModbusMaster CreateTcpMaster(ModbusFactory factory)
        {
            _tcpClient = new TcpClient(_configurationSettings.IpAddress, _configurationSettings.IpPort);
            IModbusMaster master = null;

            if (_configurationSettings.ConnectionType.CurrentType == ConnectionType.TcpIp)
            {
                master = factory.CreateMaster(_tcpClient);
            }
            if (_configurationSettings.ConnectionType.CurrentType == ConnectionType.RtuAsciiOverTcpIp)
            {
                var adapter = new TcpClientAdapter(_tcpClient);
                if (_configurationSettings.UseRtu)
                {
                    master = factory.CreateRtuMaster(adapter);
                }
                if (_configurationSettings.UseAscii)
                {
                    master = factory.CreateAsciiMaster(adapter);
                }
            }

            master.Transport.ReadTimeout = _configurationSettings.Timeout;
            return(master);
        }
Example #6
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);
        }
        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);
                }
            }
        }
Example #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);
        }
Example #9
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]);
            }
        }
Example #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);
        }
Example #11
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
        }
Example #12
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);
            }
        }
Example #13
0
        public async Task TestBool()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            bool?data = await modbus.ReadBoolAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            await modbus.WriteBoolAsync(MODBUS_SLAVE, 0, true);

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

            Assert.NotNull(data);
            Assert.True(data);
            await modbus.WriteBoolAsync(MODBUS_SLAVE, 0, false);

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

            Assert.NotNull(data);
            Assert.False(data);
            data = await modbus.ReadOnlyBoolAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
        }
Example #14
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);
        }
Example #15
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);
        }
Example #16
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);
        }
Example #17
0
        public async Task TestUShort()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            ushort?data = await modbus.ReadUShortAsync(MODBUS_SLAVE, 0);

            Assert.NotNull(data);
            await modbus.WriteUShortAsync(MODBUS_SLAVE, 0, 2);

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

            Assert.NotNull(data);
            Assert.Equal((ushort)2, data);
            await modbus.WriteUShortAsync(MODBUS_SLAVE, 0, 0);

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

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

            Assert.NotNull(data);
        }
Example #18
0
        public async Task TestBits()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

            BitArray data = await modbus.ReadBitsAsync(MODBUS_SLAVE, 0);

            Assert.Equal(16, data.Length);
            await modbus.WriteBitsAsync(MODBUS_SLAVE, 0, new BitArray(16, true));

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

            Assert.Equal(16, data.Length);
            Assert.Equal(new BitArray(16, true), data);
            await modbus.WriteBitsAsync(MODBUS_SLAVE, 0, new BitArray(16, false));

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

            Assert.Equal(16, data.Length);
            Assert.Equal(new BitArray(16, false), data);
            data = await modbus.ReadOnlyBitsAsync(MODBUS_SLAVE, 0);

            Assert.Equal(16, data.Length);
        }
Example #19
0
        public void OnButtonMbusConnectClicked(object sender, RoutedEventArgs e)
        {
            ip_addr     = boxModbusIP.Text;
            port        = int.Parse(boxModbusPort.Text);
            mbus_client = new TcpClient();
            mbus_master = mbus_factory.CreateMaster(mbus_client);

            try
            {
                Console.WriteLine("Соединяю с " + ip_addr + " ...");
                mbus_client.Connect(ip_addr, port);
            }
            catch (SocketException)
            {
                Console.WriteLine("Соединение с " + ip_addr + " прервано");
                labelLab2CStatus.Content = "Состояние: Ошибка соединения";
            }

            if (mbus_client.Connected)
            {
                labelLab2CStatus.Content = "Состояние: Соединен с " + ip_addr;
                Console.WriteLine("Соединен с " + ip_addr + ":" + port.ToString());
                buttonModbusStart.Click      -= OnButtonMbusConnectClicked;
                buttonModbusStart.Click      += OnButtonMbusDisconnectClicked;
                buttonModbusStart.Content     = "Отсоединить";
                boxModbusIP.IsEnabled         = false;
                boxModbusPort.IsEnabled       = false;
                buttonModbusExecute.IsEnabled = true;
                manual_dc = false;
                conn_check.Start();
            }
        }
Example #20
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);
        }
        public IModbusMaster Create()
        {
            var factory = new ModbusFactory();

            switch (_connection.Type)
            {
            case ConnectionType.Rtu:
            {
                var serialPort = CreateAndOpenSerialPort(_connection);

                var transport = new SerialPortAdapter(serialPort);

                return(factory.CreateRtuMaster(transport));
            }

            case ConnectionType.Ascii:
            {
                var serialPort = CreateAndOpenSerialPort(_connection);

                var transport = new SerialPortAdapter(serialPort);

                return(factory.CreateRtuMaster(transport));
            }

            case ConnectionType.Tcp:
            {
                var tcpClient = new TcpClient();

                if (!tcpClient.ConnectAsync(_connection.HostName, _connection.Port).Wait(TcpConnectionTimeoutMilliseconds))
                {
                    throw new TimeoutException($"Timed out trying to connect to TCP Modbus device at {_connection.HostName}:{_connection.Port}");
                }

                return(factory.CreateMaster(tcpClient));
            }

            case ConnectionType.Udp:
            {
                var udpClient = new UdpClient();

                return(factory.CreateMaster(udpClient));
            }

            default:
                throw new ArgumentException($"{nameof(_connection.Type)} had an unepected value '{_connection.Type}'.");
            }
        }
        public ModbusProvider(string ipAddress)
        {
            _client = new TcpClient(ipAddress, 502);

            var factory = new ModbusFactory();

            _master = factory.CreateMaster(_client);
        }
Example #23
0
        private ModbusResult ReadRegister(dynamic parameters)
        {
            var result = new ModbusResult();

            try
            {
                result.IpAddress    = parameters.ipaddress;
                result.StartAddress = parameters.start_address;
                bool ok = true;

                using (TcpClient client = new TcpClient(result.IpAddress, 502))
                {
                    client.SendTimeout = 1000;

                    var factory = new ModbusFactory();

                    IModbusMaster master = factory.CreateMaster(client);
                    master.Transport.Retries      = 0;
                    master.Transport.ReadTimeout  = 300;
                    master.Transport.WriteTimeout = 300;

                    //if (!client.ConnectAsync(result.IpAddress, 502).Wait(1000))
                    //{
                    //    // connection failure
                    //    ok = false;
                    //}

                    if (ok)
                    {
                        ushort startAddress = (ushort)result.StartAddress;
                        ushort numInputs    = (ushort)int.Parse(parameters.number_of_points);
                        bool[] inputs       = master.ReadInputs(0, startAddress, numInputs);

                        for (int i = 0; i < numInputs; i++)
                        {
                            result.data.Add(inputs[i]);

                            if (parameters.with_html == true)
                            {
                                result.ApiCall            = Request.Url.SiteBase + $"/api/modbus/{parameters.ipaddress}/{parameters.start_address}/{parameters.number_of_points}";
                                result.BitsStringForHtml += $"no {i} = {(inputs[i] ? "1" : "0")}<br />\r\n";
                            }

                            result.HasData = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                result.HasError     = true;
                result.ErrorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
            }

            result.serverTime = DateTime.Now;
            return(result);
        }
Example #24
0
        public void PassesLoggerToMasterFromParameter()
        {
            // Arrange
            var target = new ModbusFactory(Mock.Of <IModbusLogger>());
            var client = new TcpClient("127.0.0.1", 502);

            // Act/Assert
            Assert.Throws <ArgumentNullException>(() => target.CreateMaster(client, null));
        }
Example #25
0
        public void reconecta(int i)
        {
            try
            {
                client.RemoveAt(i);
                masters.RemoveAt(i);


                client.Add(new TcpClient(clps.ElementAt(i), 502));
                //client.ElementAt(client.Count).Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                masters.Add(factory.CreateMaster(client.ElementAt(client.Count - 1)));
                masters.ElementAt(masters.Count - 1).Transport.ReadTimeout = 300;
            }
            catch
            {
                Console.WriteLine("reconecta erro");
            }
        }
Example #26
0
        public void PassesLoggerToMasterFromConstructor()
        {
            // Arrange
            var target = new ModbusFactory(null);
            var client = new TcpClient("127.0.0.1", 502);

            // Act/Assert
            Assert.Throws <ArgumentNullException>(() => target.CreateMaster(client));
        }
Example #27
0
        /// <summary>
        ///     Modbus serial ASCII master and slave example.
        /// </summary>
        public static void ModbusSerialAsciiMasterReadRegistersFromModbusSlave()
        {
            using (SerialPort masterPort = new SerialPort("COM1"))
                using (SerialPort slavePort = new SerialPort("COM2"))
                {
                    // configure serial ports
                    masterPort.BaudRate = slavePort.BaudRate = 9600;
                    masterPort.DataBits = slavePort.DataBits = 8;
                    masterPort.Parity   = slavePort.Parity = Parity.None;
                    masterPort.StopBits = slavePort.StopBits = StopBits.One;
                    masterPort.Open();
                    slavePort.Open();

                    var slaveAdapter = new SerialPortAdapter(slavePort);
                    // create modbus slave on seperate thread
                    byte slaveId = 1;

                    var factory = new ModbusFactory();

                    var transport = factory.CreateAsciiTransport(slaveAdapter);

                    var network = factory.CreateSlaveNetwork(transport);

                    var slave = factory.CreateSlave(slaveId);

                    network.AddSlave(slave);

                    var listenTask = network.ListenAsync();

                    var masterAdapter = new SerialPortAdapter(masterPort);

                    var masterTransport = factory.CreateAsciiTransport(masterAdapter);

                    // create modbus master
                    IModbusSerialMaster master = factory.CreateMaster(masterTransport);

                    master.Transport.Retries = 5;
                    ushort startAddress = 100;
                    ushort numRegisters = 5;

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

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

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Example #28
0
        public async Task TestInput()
        {
            var           factory = new ModbusFactory();
            IModbusMaster modbus  = factory.CreateMaster(_client);
            await _client.ConnectAsync(MODBUS_IP, MODBUS_PORT);

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

            Assert.Equal(5, data.Length);
        }
Example #29
0
        internal async Task ConnectByTCPAsync(string address, int port)
        {
            tcpClient = new TcpClient(address, port);

            var factory = new ModbusFactory();

            master = factory.CreateMaster(tcpClient);

            await master.ReadInputRegistersAsync(SLAVE_ADDRESS, 0, 1);
        }
Example #30
0
 private void Form1_Load(object sender, EventArgs e)
 {
     //初始化modbusmaster
     modbusFactory = new ModbusFactory();
     //在本地测试 所以使用回环地址,modbus协议规定端口号 502
     master = modbusFactory.CreateMaster(new TcpClient("127.0.0.1", 502));
     //设置读取超时时间
     master.Transport.ReadTimeout = 2000;
     master.Transport.Retries     = 2000;
     groupBox1.Enabled            = false;
     groupBox2.Enabled            = false;
 }