Пример #1
0
        private void ExecuteReadCommand(byte function)
        {
            _lastReadCommand = function;

            try
            {
                var command = new ModbusCommand(function)
                {
                    Offset = StartAddress, Count = DataLength, TransId = _transactionId++
                };
                var result = _driver.ExecuteGeneric(_portClient, command);
                if (result.Status == CommResponse.Ack)
                {
                    command.Data.CopyTo(_registerData, StartAddress);
                    UpdateDataTable();
                    AppendLog(String.Format("Read succeeded: Function code:{0}.", function));
                }
                else
                {
                    AppendLog(String.Format("Failed to execute Read: Error code:{0}", result.Status));
                }
            }
            catch (Exception ex)
            {
                AppendLog(ex.Message);
            }
        }
Пример #2
0
        public CommResponse ExecuteReadCommand(byte function, ushort StartAddress, ushort DataLength)
        {
            CommResponse result = null;

            try
            {
                var command = new ModbusCommand(function)
                {
                    Offset  = StartAddress,
                    Count   = DataLength,
                    TransId = _transactionId++
                };
                result = _driver.ExecuteGeneric(_portClient, command);
                if (result.Status == CommResponse.Ack)
                {
                    //UInt16[] Data = new ushort[command.Data.Length];
                    //command.Data.CopyTo(Data, StartAddress);
                    //foreach (var item in Data)
                    //{
                    //    Console.WriteLine(item);
                    //}
                    Console.WriteLine($"Read succeeded: Function code:{function}  {_transactionId}");
                }
                else
                {
                    Console.WriteLine(String.Format("Failed to execute Read: Error code:{0}", result.Status));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(result);
        }
Пример #3
0
        public override bool ExecuteWrite(int offset)
        {
            FuncWriteMultipleRegisters.Offset = offset;
            FuncWriteMultipleRegisters.Count  = GetCountRegsByTagOffset(offset);
            FuncWriteMultipleRegisters.Data   = new ushort[FuncWriteMultipleRegisters.Count];
            adapter.Write(FuncWriteMultipleRegisters, ref RegistersData);
            CommResponse Response = driver.ExecuteGeneric(medium, FuncWriteMultipleRegisters);

            return(Response.Status == CommResponse.Ack);
        }
Пример #4
0
        private ushort[] GetTagsValueMax(ValueType aValueType, int aStartAddress, int aTagCount)
        {
            byte function;
            int  ModbusCount = 0;

            if (aValueType.Equals(ValueType.Bool))
            {
                function    = ModbusCommand.FuncReadCoils;
                ModbusCount = aTagCount;
            }
            else
            {
                function    = ModbusCommand.FuncReadMultipleRegisters;
                ModbusCount = aTagCount * 2;
            }
            var data    = new ushort[ModbusCount];
            var command = new ModbusCommand(function)
            {
                Offset = aStartAddress, Count = ModbusCount, TransId = _transactionId++
            };
            var result = _driver.ExecuteGeneric(_portClient, command);

            if (result.Status == CommResponse.Ack)
            {
                command.Data.CopyTo(_registerData, aStartAddress);
                for (int i = 0; i < ModbusCount; i++)
                {
                    var index = aStartAddress + i;
                    if (index >= _registerData.Length)
                    {
                        break;
                    }
                    data[i] = _registerData[index];
                }
                Console.WriteLine(String.Format("Read succeeded: Function code:{0}.", function));
            }
            else
            {
                Console.WriteLine(String.Format("Failed to execute Read: Error code:{0}", result.Status));
            }
            return(data);
        }
Пример #5
0
        public static void Main()
        {
#if MASTER_TCP || MASTER_UDP || SLAVE_TCP || SLAVE_UDP
            //setup the board IP
            NetworkInterface.GetAllNetworkInterfaces()[0]
            .EnableStaticIP("192.168.0.99", "255.255.255.0", "192.168.0.1");

            string localip = NetworkInterface.GetAllNetworkInterfaces()[0]
                             .IPAddress;

            Debug.Print("The local IP address of your Netduino Plus is " + localip);

            //define coils, inputs, and analogs
            _inputs  = new InputPort[8];
            _coils   = new OutputPort[6];
            _analogs = new AnalogInput[6];

            _inputs[0] = new InputPort(Pins.GPIO_PIN_D0, true, Port.ResistorMode.PullUp);
            _inputs[1] = new InputPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp);
            _inputs[2] = new InputPort(Pins.GPIO_PIN_D2, true, Port.ResistorMode.PullUp);
            _inputs[3] = new InputPort(Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp);
            _inputs[4] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp);
            _inputs[5] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp);
            _inputs[6] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp);
            _inputs[7] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp);

            _coils[0] = new OutputPort(Pins.GPIO_PIN_D8, false);
            _coils[1] = new OutputPort(Pins.GPIO_PIN_D9, false);
            _coils[2] = new OutputPort(Pins.GPIO_PIN_D10, false);
            _coils[3] = new OutputPort(Pins.GPIO_PIN_D11, false);
            _coils[4] = new OutputPort(Pins.GPIO_PIN_D12, false);
            _coils[5] = new OutputPort(Pins.GPIO_PIN_D13, false);

            _analogs[0] = new AnalogInput(Pins.GPIO_PIN_A0);
            _analogs[1] = new AnalogInput(Pins.GPIO_PIN_A1);
            _analogs[2] = new AnalogInput(Pins.GPIO_PIN_A2);
            _analogs[3] = new AnalogInput(Pins.GPIO_PIN_A3);
            _analogs[4] = new AnalogInput(Pins.GPIO_PIN_A4);
            _analogs[5] = new AnalogInput(Pins.GPIO_PIN_A5);
#else
            //define coils, inputs, and analogs
            _inputs  = new InputPort[4];
            _coils   = new OutputPort[6];
            _analogs = new AnalogInput[6];

            _inputs[0] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp);
            _inputs[1] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp);
            _inputs[2] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp);
            _inputs[3] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp);

            _coils[0] = new OutputPort(Pins.GPIO_PIN_D8, false);
            _coils[1] = new OutputPort(Pins.GPIO_PIN_D9, false);
            _coils[2] = new OutputPort(Pins.GPIO_PIN_D10, false);
            _coils[3] = new OutputPort(Pins.GPIO_PIN_D11, false);
            _coils[4] = new OutputPort(Pins.GPIO_PIN_D12, false);
            _coils[5] = new OutputPort(Pins.GPIO_PIN_D13, false);

            _analogs[0] = new AnalogInput(Pins.GPIO_PIN_A0);
            _analogs[1] = new AnalogInput(Pins.GPIO_PIN_A1);
            _analogs[2] = new AnalogInput(Pins.GPIO_PIN_A2);
            _analogs[3] = new AnalogInput(Pins.GPIO_PIN_A3);
            _analogs[4] = new AnalogInput(Pins.GPIO_PIN_A4);
            _analogs[5] = new AnalogInput(Pins.GPIO_PIN_A5);
#endif

#if MASTER_TCP
            //create a TCP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                //refine the socket settings
                socket.SetSocketOption(
                    SocketOptionLevel.Tcp,
                    SocketOptionName.NoDelay,
                    true
                    );

                socket.SendTimeout    = 2000;
                socket.ReceiveTimeout = 2000;

                //try the connection against the remote device
                var remoteip = new byte[4] {
                    192, 168, 0, 60
                };
                var ipaddr = new IPAddress(remoteip);
                var ept    = new IPEndPoint(ipaddr, 502);
                socket.Connect(ept);

                //create a wrapper around the socket
                ICommClient portClient = socket.GetClient();

                //create a client driver
                var driver = new ModbusClient(new ModbusTcpCodec());
                driver.Address = 1;

                while (true)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncWriteMultipleRegisters);
                    command.Offset = 49;
                    command.Count  = 4;

                    //attach the Netduino's input values as data
                    command.Data = new ushort[4];
                    for (int i = 0; i < 4; i++)
                    {
                        command.Data[i] = (ushort)(_inputs[i].Read() ? 0 : 1);
                    }

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(portClient, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                    }
                    else
                    {
                        //some error
                        Debug.Print("Error=" + command.ExceptionCode);
                    }

                    //just a small delay
                    Thread.Sleep(1000);
                }
            }
#endif

#if MASTER_UDP
            //create a UDP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                //try the connection against the remote device
                var remoteip = new byte[4] {
                    192, 168, 0, 60
                };
                var ipaddr = new IPAddress(remoteip);
                var ept    = new IPEndPoint(ipaddr, 502);
                socket.Connect(ept);

                //create a wrapper around the socket
                ICommClient portClient = socket.GetClient();

                //create a client driver
                var driver = new ModbusClient(new ModbusTcpCodec());
                driver.Address = 1;

                while (true)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncReadMultipleRegisters);
                    command.Offset = 0;
                    command.Count  = 16;

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(portClient, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                        Debug.Print("Success!");
                        for (int i = 0; i < command.Count; i++)
                        {
                            Debug.Print("Reg#" + i + "=" + command.Data[i]);
                        }
                    }
                    else
                    {
                        //some error
                        Debug.Print("Error=" + command.ExceptionCode);
                    }

                    //just a small delay
                    Thread.Sleep(1000);
                }
            }
#endif

#if MASTER_RTU
            //create an UART port
            using (var uart = new SerialPort("COM2", 38400, Parity.Even, 8))
            {
                //open the serial port
                uart.Open();

                var prm = new SerialPortParams("38400,E,8,1");

                //create a wrapper around the uart
                ICommClient portClient = uart
                                         .GetClient(prm);

                //create a client driver
                var driver = new ModbusClient(new ModbusRtuCodec());
                driver.Address = 1;

                while (true)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncWriteMultipleRegisters);
                    command.Offset = 49;
                    command.Count  = 4;

                    //attach the Netduino's input values as data
                    command.Data = new ushort[4];
                    for (int i = 0; i < 4; i++)
                    {
                        command.Data[i] = (ushort)(_inputs[i].Read() ? 0 : 1);
                    }

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(portClient, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                    }
                    else
                    {
                        //some error
                        Debug.Print("Error=" + command.ExceptionCode);
                    }

                    //just a small delay
                    Thread.Sleep(1000);
                }
            }
#endif

#if SLAVE_RTU
            //create an UART port
            using (var uart = new SerialPort("COM2", 38400, Parity.Even, 8))
            {
                //open the serial port
                uart.Open();

                var prm = new SerialPortParams("38400,E,8,1");

                //create a server driver
                var server = new ModbusServer(new ModbusRtuCodec());
                server.Address = 1;

                //listen for an incoming request
                var listener = uart.GetListener(server);
                listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                listener.Start();

                Thread.Sleep(Timeout.Infinite);
            }
#endif

#if SLAVE_TCP
            //create a TCP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                //place it as listener on the port 502 (standard Modbus)
                var ept = new IPEndPoint(IPAddress.Any, 502);
                socket.Bind(ept);
                socket.Listen(10);

                //create a server driver
                var server = new ModbusServer(new ModbusTcpCodec());
                server.Address = 1;

                while (true)
                {
                    //wait for an incoming connection
                    var listener = socket.GetTcpListener(server);
                    listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                    listener.Start();

                    Thread.Sleep(1);
                }
            }
#endif

#if SLAVE_UDP
            //create a UDP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                //bind it to the port 502 (standard Modbus)
                var ept = new IPEndPoint(IPAddress.Any, 502);
                socket.Bind(ept);

                //create a server driver
                var server = new ModbusServer(new ModbusTcpCodec());
                server.Address = 1;

                //listen for an incoming request
                var listener = socket.GetUdpListener(server);
                listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                listener.Start();

                Thread.Sleep(Timeout.Infinite);
            }
#endif
        }
Пример #6
0
        protected void RunCore(
            ICommClient medium,
            ModbusClient driver,
            CancellationToken token)
        {
            Action <bool> setPollingActivity = act => HardwareModel.Instance.IsPollingEnabled = act;

            int stage = 0;

            while (token.IsCancellationRequested == false)
            {
                //turn the polling activity on
                App.Current.Dispatcher.BeginInvoke(
                    setPollingActivity,
                    true);

                if (stage == 0)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes);
                    command.Offset = 0;
                    command.Count  = 8;

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(medium, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                        for (int i = 0; i < command.Count; i++)
                        {
                            HardwareModel.Instance.Coils[i].Write(command.Data[i] != 0);
                        }

                        stage = 1;
                    }
                    else
                    {
                        //some error
                        Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode);
                    }
                }
                else if (stage == 1)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncReadInputRegisters);
                    command.Offset = 0;
                    command.Count  = 6;

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(medium, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                        for (int i = 0; i < command.Count; i++)
                        {
                            HardwareModel.Instance.Analogs[i].Value = command.Data[i] / 1023.0;
                        }

                        stage = 2;
                    }
                    else
                    {
                        //some error
                        Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode);
                    }
                }
                else if (stage == 2)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncForceMultipleCoils);
                    command.Offset = 0;
                    command.Count  = 6;

                    //attach the Netduino's input values as data
                    command.Data = new ushort[command.Count];
                    for (int i = 0; i < command.Count; i++)
                    {
                        command.Data[i] = (ushort)(HardwareModel.Instance.Discretes[i].Read() ? 1 : 0);
                    }

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(medium, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                        stage = 0;
                    }
                    else
                    {
                        //some error
                        Console.WriteLine("Status={0}; Error={1}", result.Status, command.ExceptionCode);
                    }
                }

                //turn the polling activity off
                App.Current.Dispatcher.Invoke(
                    setPollingActivity,
                    false);

                //just a small delay
                Thread.Sleep(100);
            }
        }