Esempio n. 1
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. 2
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. 3
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. 4
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. 5
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. 6
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);
            }
        }
Esempio n. 7
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
        }
Esempio n. 8
0
        //使用.net core 3.1架構開發 - https://docs.microsoft.com/zh-tw/dotnet/core/introduction
        //使用NModbus開源程式碼實作Modbus通訊 - https://github.com/NModbus/NModbus
        static void Main(string[] args)
        {
            ModbusFactory       modbusFactory      = new ModbusFactory();
            TcpListener         tcpListener        = new TcpListener(new IPEndPoint(IPAddress.Any, 502));
            IModbusSlaveNetwork modbusSlaveNetwork = modbusFactory.CreateSlaveNetwork(tcpListener);
            IModbusSlave        modbusSlave        = modbusFactory.CreateSlave(1);

            modbusSlaveNetwork.AddSlave(modbusSlave);
            modbusSlaveNetwork.ListenAsync();
            Process.GetCurrentProcess().WaitForExit();
        }
Esempio n. 9
0
        /// <summary>
        ///     Modbus TCP master and slave example.
        /// </summary>
        public static void ModbusTcpMasterReadInputsFromModbusSlave()
        {
            byte      slaveId = 1;
            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();

            var factory = new ModbusFactory();

            var network = factory.CreateSlaveNetwork(slaveTcpListener);

            IModbusSlave slave = factory.CreateSlave(slaveId);

            network.AddSlave(slave);

            var listenTask = network.ListenAsync();

            // create the master
            TcpClient     masterTcpClient = new TcpClient(address.ToString(), port);
            IModbusMaster master          = factory.CreateMaster(masterTcpClient);

            ushort numInputs    = 5;
            ushort startAddress = 100;

            // read five register values
            ushort[] inputs = master.ReadInputRegisters(0, startAddress, numInputs);

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

            // clean up
            masterTcpClient.Close();
            slaveTcpListener.Stop();

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }
Esempio n. 10
0
        /// <summary>
        ///     Simple Modbus UDP slave example.
        /// </summary>
        public static void StartModbusUdpSlave()
        {
            using (UdpClient client = new UdpClient(502))
            {
                var factory = new ModbusFactory();
                IModbusSlaveNetwork network = factory.CreateSlaveNetwork(client);

                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. 11
0
        protected override async Task ServiceTaskAsync(CancellationToken cancellationToken)
        {
            ArcController?.NewLogMessage(LogCode.ModbusStarting);

            Logger.Info("begin");

            var tcpListener = new TcpListener(IPAddress.Any, TcpPort);
            var rtuListener = new TcpListener(IPAddress.Any, RtuOverTcpPort);

            Logger.Info("starting listener");

            tcpListener.Start();
            rtuListener.Start();

            Logger.Info("generating slave net");

            var factory = new ModbusFactory();

            var tcpNetwork = factory.CreateSlaveNetwork(tcpListener);
            var rtuNetwork = factory.CreateRtuOverTcpSlaveNetwork(rtuListener);

            var slaveTcp = factory.CreateSlave(1);
            var slaveRtu = factory.CreateSlave(1, slaveTcp.DataStore);

            tcpNetwork.AddSlave(slaveTcp);
            rtuNetwork.AddSlave(slaveRtu);

            iRegisters = slaveTcp.DataStore.InputRegisters;
            hRegisters = slaveTcp.DataStore.HoldingRegisters;

            WfqydbServer.PropertyChanged += Wf_PropertyChanged;

            var timeOfStart = DateTime.Now.ToUnixTimestamp();

            ushort[] timeOfStartBuffer =
            {
                (ushort)(timeOfStart >> 16),
                (ushort)(timeOfStart),
            };

            var ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            ushort[] verBuffer =
            {
                (ushort)ver.Major,
                (ushort)ver.Minor,
                (ushort)ver.Build,
            };

            byte[] myAddress = { 0x01, 0x00, 0x00, 0x00, };

            iRegisters.WritePoints(0, verBuffer);
            iRegisters.WritePoints(3, timeOfStartBuffer);

            Logger.Info("starting slave net. step1");

            var tcpListenerTask = tcpNetwork.ListenAsync(cancellationToken);
            var rtuListenerTask = rtuNetwork.ListenAsync(cancellationToken);

            Logger.Info($"starting slave net. step2 {WfqydbServer.ToString()}");

            ArcController?.NewLogMessage(LogCode.ModbusStarted);
            ArcController?.NewLogMessage(LogCode.WFQYDBConnecting);

            //await WfqydbServer.PullBroadcastQuery().ConfigureAwait(false);
            //WfqydbServer.PullBroadcastQuery();
            ArcController?.NewLogMessage(LogCode.WFQYDBConnected);

            const int waitTime        = 100;    //ms
            const int faultRestTime   = 10_000; //ms
            const int responseTime    = 500;    //ms
            var       lastRequestTime = DateTime.Now;
            var       lastResetTime   = DateTime.Now;
            var       resetInterval   = TimeSpan.FromSeconds(30);

            var faultRestTimer = 0;

            Logger.Info("entering inf loop");
            // Главный цикл до отмены этой задачи.
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    // состояние связи
                    iRegisters.WritePoints(5, new ushort[] { (ushort)WfqydbServer.ConnectionState });
                    // Habdle

                    var buff     = hRegisters.ReadPoints(10, 5);
                    var cmd      = buff[0];
                    var cmdState = buff[1];

                    if ((buff[2] + buff[3]) == 0)
                    {
                        // Чтобы не было пустого места на элкамрм
                        hRegisters.WritePoints(12, new ushort[] { currentData[3], currentData[4], currentData[6] });
                    }

                    // обработка команд по модбас
                    if ((cmd > 0) && (cmdState == (ushort)CmdState.Rdy))
                    {
                        var upFreq    = (byte)buff[2];
                        var dnFreq    = (byte)buff[3];
                        var stokeRate = (byte)buff[4];

                        hRegisters.WritePoints(10, new ushort[] { cmd, (ushort)CmdState.Working });

                        try
                        {
                            switch ((Cmd)cmd)
                            {
                            case Cmd.Reset:
                                cmd      = 0;
                                cmdState = 0;
                                hRegisters.WritePoints(10, new ushort[] { (ushort)Cmd.NoOp, (ushort)CmdState.Rdy });
                                break;

                            case Cmd.BroadcastQuery:
                                lastRequestTime = DateTime.Now;
                                //await WfqydbServer.PullBroadcastQuery().ConfigureAwait(false);
                                WfqydbServer.PullBroadcastQuery();
                                hRegisters.WritePoints(10, new ushort[] { (ushort)Cmd.NoOp, (ushort)CmdState.Rdy });

                                ArcController?.NewLogMessage(LogCode.WFQYDBCmdRead);
                                break;

                            case Cmd.AutoRun:
                                lastRequestTime = DateTime.Now;
                                //await WfqydbServer.PullAutoRun(upFreq, dnFreq, stokeRate).ConfigureAwait(false);
                                WfqydbServer.PullAutoRun(upFreq, dnFreq, stokeRate);
                                hRegisters.WritePoints(10, new ushort[] { (ushort)Cmd.NoOp, (ushort)CmdState.Rdy });

                                ArcController?.NewLogMessage(LogCode.WFQYDBCmdCtart, $"u:{upFreq}, d:{dnFreq}, sr:{stokeRate}");
                                break;

                            case Cmd.Shutdown:
                                lastRequestTime = DateTime.Now;
                                //await WfqydbServer.PullShutdown().ConfigureAwait(false);
                                WfqydbServer.PullShutdown();
                                hRegisters.WritePoints(10, new ushort[] { (ushort)Cmd.NoOp, (ushort)CmdState.Rdy });

                                ArcController?.NewLogMessage(LogCode.WFQYDBCmdCtop);
                                break;

                            case Cmd.ThrowException:
                                throw new Exception("Test exception");

                            default:
                                hRegisters.WritePoints(10, new ushort[] { cmd, (ushort)CmdState.NotImplementedCmd });
                                faultRestTimer = faultRestTime;
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            hRegisters.WritePoints(10, new ushort[] { cmd, (ushort)CmdState.CommonError });
                            faultRestTimer = faultRestTime;
                            FireOnError(ex);

                            Logger.Alarm(ex.Message);
                            ArcController?.NewLogMessage(LogCode.ModbusFailed);
                        }
                    }

                    if (cmdState != (ushort)CmdState.Rdy)
                    {
                        if ((faultRestTimer -= waitTime) <= 0)
                        {
                            hRegisters.WritePoints(10, new ushort[] { (ushort)Cmd.NoOp, (ushort)CmdState.Rdy });
                        }
                    }

                    await Task.Delay(waitTime, cancellationToken).ConfigureAwait(false);

                    // передернем сеть rtu. Так как она периодически подвисает.
                    //var lastResetTime = DateTime.Now;
                    //var resetInterval = TimeSpan.FromSeconds(30);
                    if ((lastResetTime + resetInterval) < DateTime.Now)
                    {
                        lastResetTime = DateTime.Now;
                        Logger.Info("restarting rtu");
                        //var rtuListener = new TcpListener(IPAddress.Any, RtuOverTcpPort);
                        rtuListener.Stop();
                        rtuListener.Start();
                        // var rtuNetwork = factory.CreateRtuOverTcpSlaveNetwork(rtuListener);
                        // var slaveRtu = factory.CreateSlave(1, slaveTcp.DataStore);
                        // rtuNetwork.AddSlave(slaveRtu);
                        // var rtuListenerTask = rtuNetwork.ListenAsync(cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    FireOnError(ex);

                    Logger.Alarm(ex.Message);

                    ArcController?.NewLogMessage(LogCode.ModbusFailed);

                    await Task.Delay(waitTime, cancellationToken).ConfigureAwait(false);
                }
            }// while

            tcpListener.Stop();
            rtuListener.Stop();

            tcpNetwork.Dispose();
            rtuNetwork.Dispose();

            await tcpListenerTask.ConfigureAwait(true);

            await rtuListenerTask.ConfigureAwait(true);
        }