Ejemplo n.º 1
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();
            }
        }
Ejemplo n.º 2
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();
            }
        }
        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());
            }
        }
Ejemplo n.º 4
0
        public static async Task StartModbusSerialRtuSlaveNetwork()
        {
            using (SerialPort slavePort = new SerialPort("COM4"))
            {
                // configure serial port
                slavePort.BaudRate = 19200;
                slavePort.DataBits = 8;
                slavePort.Parity   = Parity.Even;
                slavePort.StopBits = StopBits.One;
                slavePort.Open();

                IModbusFactory factory = new ModbusFactory();

                var adapter = new SerialPortAdapter(slavePort);
                IModbusSlaveNetwork modbusSlaveNetwork = factory.CreateRtuSlaveNetwork(adapter);

                adapter.ReadTimeout  = 50;
                adapter.WriteTimeout = 500;

                var acTechDataStore = new SlaveStorage();

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

                var casHmiDataStore = new SlaveStorage();

                casHmiDataStore.InputRegisters.StorageOperationOccurred   += (sender, args) => Console.WriteLine($"CASHMI Input registers: {args.Operation} starting at {args.StartingAddress}");
                casHmiDataStore.HoldingRegisters.StorageOperationOccurred += (sender, args) => Console.WriteLine($"CASHMI Holding registers: {args.Operation} starting at {args.StartingAddress}");

                var danfossStore = new SlaveStorage();

                danfossStore.InputRegisters.StorageOperationOccurred   += (sender, args) => Console.WriteLine($"DANFOSS Input registers: {args.Operation} starting at {args.StartingAddress}");
                danfossStore.HoldingRegisters.StorageOperationOccurred += (sender, args) => Console.WriteLine($"DANFOSS Holding registers: {args.Operation} starting at {args.StartingAddress}");

                IModbusSlave slave1 = factory.CreateSlave(21, acTechDataStore);
                IModbusSlave slave2 = factory.CreateSlave(55, casHmiDataStore);

                IModbusSlave slave3 = factory.CreateSlave(1, danfossStore);

                modbusSlaveNetwork.AddSlave(slave1);
                //modbusSlaveNetwork.AddSlave(slave2);
                modbusSlaveNetwork.AddSlave(slave2);
                modbusSlaveNetwork.AddSlave(slave3);

                await modbusSlaveNetwork.ListenAsync();

                await Task.Delay(1);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Simple Modbus serial RTU slave example.
        /// </summary>
        public static async Task StartModbusSerialRtuSlaveWithCustomMessage(CancellationToken cancellationToken)
        {
            using (SerialPort slavePort = new SerialPort(PrimarySerialPortName))
            {
                // configure serial port
                slavePort.BaudRate = 57600;
                slavePort.DataBits = 8;
                slavePort.Parity   = Parity.Even;
                slavePort.StopBits = StopBits.One;
                slavePort.Open();

                var adapter = new SerialPortAdapter(slavePort);

                var functionServices = new IModbusFunctionService[]
                {
                    new HmiBufferFunctionService()
                };

                var factory = new ModbusFactory(functionServices, true, new ConsoleModbusLogger(LoggingLevel.Debug));

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

                var acTechDataStore = new SlaveStorage();

                acTechDataStore.InputRegisters.StorageOperationOccurred   += (sender, args) => Console.WriteLine($"ACTECH Input registers: {args.Operation} starting at {args.StartingAddress}");
                acTechDataStore.HoldingRegisters.StorageOperationOccurred += (sender, args) => Console.WriteLine($"ACTECH Holding registers: {args.Operation} starting at {args.StartingAddress}");

                var danfossStore = new SlaveStorage();

                danfossStore.InputRegisters.StorageOperationOccurred   += (sender, args) => Console.WriteLine($"DANFOSS Input registers: {args.Operation} starting at {args.StartingAddress}");
                danfossStore.HoldingRegisters.StorageOperationOccurred += (sender, args) => Console.WriteLine($"DANFOSS Holding registers: {args.Operation} starting at {args.StartingAddress}");

                IModbusSlave actechSlave  = factory.CreateSlave(21, acTechDataStore);
                IModbusSlave danfossSlave = factory.CreateSlave(1, danfossStore);

                slaveNetwork.AddSlave(actechSlave);
                slaveNetwork.AddSlave(danfossSlave);

                await slaveNetwork.ListenAsync(cancellationToken);
            }
        }
Ejemplo n.º 6
0
        void ThreadScalWork(object s, DoWorkEventArgs e)
        {
            if (_slavePort == null)
            {
                _slavePort          = new SerialPort("COM3");
                _slavePort.BaudRate = 115200;
                _slavePort.DataBits = 8;
                _slavePort.Parity   = Parity.None;
                _slavePort.StopBits = StopBits.Two;
                _slavePort.Open();
                var          adapter      = new SerialPortAdapter(_slavePort);
                var          factory      = new ModbusFactory();
                var          slaveNetwork = factory.CreateRtuSlaveNetwork(adapter);
                var          dataStore    = new SlaveStorage();
                var          transport    = factory.CreateRtuTransport(adapter);
                IModbusSlave slave1       = factory.CreateSlave(4, dataStore); //5 - у тестового, 4 - scalodrom
                dataStore.CoilDiscretes.StorageOperationOccurred += (sender, args) =>
                {
                    ;
                };
                dataStore.CoilInputs.StorageOperationOccurred += (sender, args) =>
                {
                    if (args.Operation == PointOperation.Read)
                    {
                        //i = "c-i read addr = " + args.StartingAddress.ToString() + " cnt = " + args.Points.Length.ToString();
                        if (false)//switchAngle)
                        {
                            //dataStore.CoilInputs.WritePoints(args.StartingAddress, new bool[] { true });
                            //switchAngle = false;
                        }
                        else
                        {
                            dataStore.CoilInputs.WritePoints(args.StartingAddress, new bool[] { false });
                        }
                    }
                };
                List <ushort> adr = new List <ushort>(); //5 addr - angle, 7 - flag
                dataStore.InputRegisters.StorageOperationOccurred += (sender, args) =>
                {
                    if (args.Operation == PointOperation.Write)
                    {
                        if (args.StartingAddress == 9)
                        {
                        }
                    }
                    else
                    {
                        //if (!adr.Contains(args.StartingAddress)) adr.Add(args.StartingAddress);

                        if (args.StartingAddress == 5)
                        {
                            float f = 0.0f;
                            f = Speed;
                            int    m    = (int)f;
                            byte[] b    = BitConverter.GetBytes(m);
                            ushort high = BitConverter.ToUInt16(b, 0);
                            ushort low  = BitConverter.ToUInt16(b, 2);
                            //dataStore.InputRegisters.WritePointsSilent(args.StartingAddress, new ushort[] { high, low, high, low, high, low });
                        }
                        else if (args.StartingAddress == 1)
                        {
                            //172.16.15.65
                            //1560 220
                            float f = 0.0f;
                            if (IsPlaying)
                            {
                                f = Speed;
                            }
                            else
                            {
                                f = 0.0f;
                            }

                            //Dbg = f.ToString();
                            byte[] b    = BitConverter.GetBytes(f);
                            ushort high = BitConverter.ToUInt16(b, 0);
                            ushort low  = BitConverter.ToUInt16(b, 2);
                            //_currentPoint
                            ushort nil = 0;
                            dataStore.InputRegisters.WritePointsSilent(args.StartingAddress, new ushort[] { nil, nil, nil, nil, high, low, });  //{ high, low, nil, nil, nil, nil });
                            //Dbg = f.ToString();
                        }
                        else if (args.StartingAddress == 9)
                        {
                            //h = args.StartingAddress.ToString() + " " + args.Points.Length.ToString();
                            float f = 0.0f;
                            //if (_currentPoint != null) f = _currentPoint.Speed;
                            byte[] b    = BitConverter.GetBytes(f);
                            ushort high = BitConverter.ToUInt16(b, 0);
                            ushort low  = BitConverter.ToUInt16(b, 2);
                            //dataStore.InputRegisters.WritePointsSilent(args.StartingAddress, new ushort[] { high, low });
                        }
                        else
                        {
                            //h = args.ToString() + " zzzz";
                        }
                    }
                };

                //8.89 на отсчет
                //1280 40
                //1300 220
                int _prevPos = -1;
                dataStore.HoldingRegisters.StorageOperationOccurred += (sender, args) =>
                {
                    if (args.Operation == PointOperation.Write)
                    {
                        if (args.StartingAddress == 9)
                        {
                        }
                        else if (args.StartingAddress == 13)
                        {
                        }
                        else if (args.StartingAddress == 11)
                        {
                            Pos = args.Points[0];

                            if (args.Points[0] == TargetPos)
                            {
                                IsPlaying = false;
                            }

                            if (Pos != _prevPos)
                            {
                                X            = (int)Math.Round(170.2f + 9.2f * (Pos)); // (int)(1280 + args.Points[0] * 8.89);
                                Y            = 590;                                    // 580 + (int)Math.Round(10.3f * (Pos));
                                _sendMessage = true;
                            }
                            _prevPos = Pos;
                        }
                        else if (args.StartingAddress == 7)
                        {
                        }
                    }
                    else
                    {
                    }
                };
                slaveNetwork.AddSlave(slave1);
                try
                {
                    slaveNetwork.ListenAsync();
                }
                catch (Exception exc)
                {
                }
            }
        }
Ejemplo n.º 7
0
        public void ListenPort()
        {
            _slavePort          = new SerialPort("COM5");
            _slavePort.BaudRate = 115200;
            _slavePort.DataBits = 8;
            _slavePort.Parity   = Parity.None;
            _slavePort.StopBits = StopBits.Two;
            _slavePort.Open();
            var          adapter      = new SerialPortAdapter(_slavePort);
            var          factory      = new ModbusFactory();
            var          slaveNetwork = factory.CreateRtuSlaveNetwork(adapter);
            var          dataStore    = new SlaveStorage();
            var          transport    = factory.CreateRtuTransport(adapter);
            IModbusSlave slave1       = factory.CreateSlave(4, dataStore); //5 - у тестового, 4 - scalodrom

            dataStore.CoilDiscretes.StorageOperationOccurred += (sender, args) =>
            {
                File.AppendAllLines("log.txt", new string[1] {
                    $"CoilDiscretes: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}"
                });
                //File.AppendAllLines("log.txt", new string[1] { $"CoilDiscretes: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}" });
            };
            dataStore.CoilInputs.StorageOperationOccurred += (sender, args) =>
            {
                File.AppendAllLines("log.txt", new string[1] {
                    $"CoilInputs: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}"
                });
                if (args.Operation == PointOperation.Read)
                {
                    //i = "c-i read addr = " + args.StartingAddress.ToString() + " cnt = " + args.Points.Length.ToString();
                    //dataStore.CoilInputs.WritePoints(args.StartingAddress, new bool[] { true });
                    if (Math.Abs(_currentAngle.Speed - _realAngle) > 1)
                    {
                        if (!switchAngle)
                        {
                            dataStore.CoilInputs.WritePoints(args.StartingAddress, new bool[] { true, false });
                            switchAngle = true;
                        }
                    }
                    else
                    {
                        dataStore.CoilInputs.WritePoints(args.StartingAddress, new bool[] { false, false });
                        switchAngle = false;
                    }
                }
                else
                {
                    //Dbg += $"Input registers: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}\r\n";
                    //File.AppendAllLines("log.txt", new string[1] { $"CoilInputs: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}" });
                }
            };
            List <ushort> adr = new List <ushort>(); //5 addr - angle, 7 - flag

            dataStore.InputRegisters.StorageOperationOccurred += (sender, args) =>
            {
                File.AppendAllLines("log.txt", new string[1] {
                    $"InputRegisters: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}"
                });
                if (args.Operation == PointOperation.Write)
                {
                    //h = "yes"; //Console.WriteLine($"Input registers: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}");
                    //i = "yes";
                    //Dbg += $"Input registers: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}" ;
                    //File.AppendAllLines("log.txt", new string[1] { $"InputRegisters: {args.Operation} starting at {args.StartingAddress} {args.Points.Length}" });
                }
                else
                {
                    if (args.StartingAddress == 1)
                    {
                        float  curAngle = -15.0f;
                        byte[] ab       = BitConverter.GetBytes(curAngle);
                        ushort high     = BitConverter.ToUInt16(ab, 0);
                        ushort low      = BitConverter.ToUInt16(ab, 2);
                        //dataStore.InputRegisters.WritePointsSilent(5, new ushort[] { high, low });
                        //172.16.15.65
                        float f1 = 0.0f; float f2 = 0.0f; float f3 = 0.0f;
                        if (IsPlaying)
                        {
                            if (_currentPoint1 != null)
                            {
                                f1 = -1 * _currentPoint1.Speed;
                            }
                            else
                            {
                                f1 = 0.0f;
                            }
                            if (_currentPoint2 != null)
                            {
                                f2 = -1 * _currentPoint2.Speed;
                            }
                            else
                            {
                                f2 = 0.0f;
                            }
                            if (_currentPoint3 != null)
                            {
                                f3 = -1 * _currentPoint3.Speed;
                            }
                            else
                            {
                                f3 = 0.0f;
                            }
                        }
                        else
                        {
                            f1 = 0.0f; f2 = 0.0f; f3 = 0.0f;
                        }

                        byte[] b1 = BitConverter.GetBytes(f1); byte[] b2 = BitConverter.GetBytes(f2); byte[] b3 = BitConverter.GetBytes(f3);
                        ushort high1 = BitConverter.ToUInt16(b1, 0); ushort high2 = BitConverter.ToUInt16(b2, 0); ushort high3 = BitConverter.ToUInt16(b3, 0);
                        ushort low1 = BitConverter.ToUInt16(b1, 2); ushort low2 = BitConverter.ToUInt16(b2, 2); ushort low3 = BitConverter.ToUInt16(b3, 2);
                        //_currentPoint1

                        dataStore.InputRegisters.WritePointsSilent(args.StartingAddress, new ushort[] { high3, low3, high1, low1, high2, low2 });
                    }
                    else if (args.StartingAddress == 21)
                    {
                        byte[] hl   = BitConverter.GetBytes(_currentAngle.Speed);
                        ushort high = BitConverter.ToUInt16(hl, 0);
                        ushort low  = BitConverter.ToUInt16(hl, 2);
                        dataStore.InputRegisters.WritePointsSilent(args.StartingAddress, new ushort[] { high, low });
                        //Dbg = _currentAngle.ToString();
                    }
                    else
                    {
                        Dbg += args.ToString() + " zzzz";
                    }
                }
            };


            dataStore.HoldingRegisters.StorageOperationOccurred += (sender, args) =>
            {
                //Console.WriteLine($"Holding registers: {args.Operation} starting at {args.StartingAddress}  {args.Points[0]}");
                if (args.Operation == PointOperation.Write)
                {
                    if (args.StartingAddress == 7)
                    {
                        ushort high  = args.Points[1];
                        ushort low   = args.Points[2];
                        byte[] bytes = new byte[4];
                        bytes[0]   = (byte)(high & 0xFF);
                        bytes[1]   = (byte)(high >> 8);
                        bytes[2]   = (byte)(low & 0xFF);
                        bytes[3]   = (byte)(low >> 8);
                        _realAngle = BitConverter.ToSingle(bytes, 0);
                        File.AppendAllLines("log.txt", new string[1] {
                            $"HoldingRegisters: {args.Operation} starting at {args.StartingAddress} {args.Points.Length} angle = {_realAngle}"
                        });
                        Dbg = _realAngle.ToString();
                    }
                }
                else
                {
                }
            };
            slaveNetwork.AddSlave(slave1);

            try
            {
                slaveNetwork.ListenAsync();
            }
            catch (Exception exc) {
            }
        }