コード例 #1
0
        void IProtocolCodec.ServerEncode(CommDataBase data)
        {
            ModbusServer    ownerProtocol    = (ModbusServer)data.OwnerProtocol;
            ModbusCommand   userData         = (ModbusCommand)data.UserData;
            byte            functionCode     = userData.FunctionCode;
            ByteArrayWriter byteArrayWriter1 = new ByteArrayWriter();

            ModbusCodecBase.CommandCodecs[(int)functionCode]?.ServerEncode(userData, byteArrayWriter1);
            if (userData.ExceptionCode == (byte)0)
            {
                int length = byteArrayWriter1.Length;
            }
            ByteArrayWriter byteArrayWriter2 = new ByteArrayWriter();

            byteArrayWriter2.WriteByte(ownerProtocol.Address);
            if (userData.ExceptionCode == (byte)0)
            {
                byteArrayWriter2.WriteByte(userData.FunctionCode);
                byteArrayWriter2.WriteBytes(byteArrayWriter1);
            }
            else
            {
                byteArrayWriter2.WriteByte((byte)((uint)userData.FunctionCode | 128U));
                byteArrayWriter2.WriteByte(userData.ExceptionCode);
            }
            ushort num = ByteArrayHelpers.CalcCRC16(byteArrayWriter2.ToArray(), 0, byteArrayWriter2.Length);

            byteArrayWriter2.WriteInt16LE((short)num);
            data.OutgoingData = byteArrayWriter2.ToReader();
        }
コード例 #2
0
        CommResponse IProtocolCodec.ServerDecode(CommDataBase data)
        {
            ModbusServer    ownerProtocol = (ModbusServer)data.OwnerProtocol;
            ByteArrayReader incomingData  = data.IncomingData;
            int             length        = incomingData.Length;

            if (length < 4)
            {
                return(new CommResponse(data, 0));
            }
            if ((int)incomingData.ReadByte() == (int)ownerProtocol.Address)
            {
                byte fc = incomingData.ReadByte();
                if ((int)fc < ModbusCodecBase.CommandCodecs.Length)
                {
                    ModbusCommand command = new ModbusCommand(fc);
                    data.UserData            = (object)command;
                    command.QueryTotalLength = 6;
                    ModbusCommandCodec commandCodec = ModbusCodecBase.CommandCodecs[(int)fc];
                    ByteArrayReader    body         = new ByteArrayReader(incomingData.ReadBytes(length - 4));
                    commandCodec.ServerDecode(command, body);
                    ushort num = ByteArrayHelpers.CalcCRC16(incomingData.ToArray(), 0, command.QueryTotalLength - 2);
                    if ((int)ByteArrayHelpers.ReadInt16LE(((IByteArray)incomingData).Data, command.QueryTotalLength - 2) == (int)(short)num)
                    {
                        return(new CommResponse(data, 3));
                    }
                }
            }
            return(new CommResponse(data, 1));
        }
コード例 #3
0
ファイル: ModbusTcpTcpProxy.cs プロジェクト: blinds52/Modbus
        /// <summary>
        /// Stops the proxy.
        /// </summary>
        /// <returns></returns>
        public Task StopAsync()
        {
            try
            {
                logger?.LogTrace("ModbusTcpTcpProxy.StopAsync enter");
                CheckDisposed();
                if (!isStarted)
                {
                    return(Task.CompletedTask);
                }

                isStarted = false;

                server?.Dispose();
                server = null;

                client?.Dispose();
                client = null;

                return(Task.CompletedTask);
            }
            finally
            {
                logger?.LogTrace("ModbusTcpTcpProxy.StopAsync leave");
            }
        }
コード例 #4
0
ファイル: ModbusTcpTcpProxy.cs プロジェクト: blinds52/Modbus
        /// <summary>
        /// Starts the proxy.
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            try
            {
                logger?.LogTrace("ModbusTcpTcpProxy.StartAsync enter");

                CheckDisposed();
                if (isStarted)
                {
                    return;
                }

                isStarted = true;

                client = new ModbusClient(settings.DestinationHost, settings.DestinationPort, logger);
                await client.Connect();

                server = new ModbusServer(settings.ListenPort, settings.ListenAddress, logger, HandleRequest);
                await server.Initialization;
            }
            finally
            {
                logger?.LogTrace("ModbusTcpTcpProxy.StartAsync leave");
            }
        }
コード例 #5
0
ファイル: SlaveForm.cs プロジェクト: FreemanKing/JustTest
        /// <summary>
        /// Running thread handler
        /// </summary>
        protected void Worker()
        {
            var server = new ModbusServer(new ModbusTcpCodec())
            {
                Address = SlaveId
            };

            server.IncommingData += DriverIncommingData;
            server.OutgoingData  += DriverOutgoingData;
            try
            {
                while (_thread.ThreadState == ThreadState.Running)
                {
                    //wait for an incoming connection
                    _listener = _socket.GetTcpListener(server);
                    _listener.ServeCommand += listener_ServeCommand;
                    _listener.Start();
                    AppendLog(String.Format("Accepted connection."));
                    Thread.Sleep(1);
                }
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
            }
        }
コード例 #6
0
ファイル: ModbusTests.cs プロジェクト: adospace/ModbusCore
        public void MasterShouldReadCoilsFromSlave()
        {
            var clientMemory = new ModbusMemoryMap();
            var client       = new ModbusClient(new ModbusRTUTransport(_clientStream));
            var clientDevice = new ModbusDevice(clientMemory, 4);

            var serverMemory = new ModbusMemoryMap();
            var server       = new ModbusServer(new ModbusRTUTransport(_serverStream));
            var serverDevice = new ModbusDevice(serverMemory, 4);

            serverMemory.OutputCoils[10] = true;
            serverMemory.OutputCoils[15] = true;

            clientMemory.OutputCoils[10].ShouldBeFalse();
            clientMemory.OutputCoils[15].ShouldBeFalse();

            Task.Run(() => server.HandleRequest(serverDevice));

            client.ReadCoils(clientDevice, 10, 13);

            //slave memory not touched
            serverMemory.OutputCoils[10].ShouldBeTrue();
            serverMemory.OutputCoils[15].ShouldBeTrue();

            //master memory is synched
            clientMemory.OutputCoils[10].ShouldBeTrue();
            clientMemory.OutputCoils[15].ShouldBeTrue();
        }
コード例 #7
0
ファイル: SlaveForm.cs プロジェクト: gbcwbz/ModbusTool
        private void BtnConnectClick(object sender, EventArgs e)
        {
            try
            {
                switch (CommunicationMode)
                {
                    case CommunicationMode.RTU:
                        _uart = new SerialPort(PortName, Baud, Parity, DataBits, StopBits);
                        _uart.Open();
                        var rtuServer = new ModbusServer(new ModbusRtuCodec()) { Address = SlaveId };
                        rtuServer.OutgoingData += DriverOutgoingData;
                        rtuServer.IncommingData += DriverIncommingData;
                        _listener = _uart.GetListener(rtuServer);
                        _listener.ServeCommand += listener_ServeCommand;
                        _listener.Start();
                        AppendLog(String.Format("Connected using RTU to {0}", PortName));
                        break;

                    case CommunicationMode.UDP:
                        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        _socket.Bind(new IPEndPoint(IPAddress.Any, TCPPort));
                        //create a server driver
                        var udpServer = new ModbusServer(new ModbusTcpCodec()) { Address = SlaveId };
                        udpServer.OutgoingData += DriverOutgoingData;
                        udpServer.IncommingData += DriverIncommingData;
                        //listen for an incoming request
                        _listener = _socket.GetUdpListener(udpServer);
                        _listener.ServeCommand += listener_ServeCommand;
                        _listener.Start();
                        AppendLog(String.Format("Listening to UDP port {0}", TCPPort));
                        break;

                    case CommunicationMode.TCP:
                        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        _socket.Bind(new IPEndPoint(IPAddress.Any, TCPPort));
                        _socket.Listen(10);
                        //create a server driver
                        _thread = new Thread(Worker);
                        _thread.Start();
                        AppendLog(String.Format("Listening to TCP port {0}", TCPPort));

                        // simulate classic
                        broadcasrter = new UDPBroadcaster();
                        broadcasrter.SendDatagrams(TCPPort);
                        break;
                }
            }
            catch (Exception ex)
            {
                AppendLog(ex.Message);
                return;
            }
            btnConnect.Enabled = false;
            buttonDisconnect.Enabled = true;
            grpExchange.Enabled = true;
            groupBoxFunctions.Enabled = false;
            groupBoxTCP.Enabled = false;
            groupBoxRTU.Enabled = false;
            groupBoxMode.Enabled = false;
        }
コード例 #8
0
        private void BtnConnectClick(object sender, EventArgs e)
        {
            try
            {
                switch (CommunicationMode)
                {
                case CommunicationMode.RTU:
                    _uart = new SerialPort(PortName, Baud, Parity, DataBits, StopBits);
                    _uart.Open();
                    var rtuServer = new ModbusServer(new ModbusRtuCodec());
                    rtuServer.OutgoingData  += DriverOutgoingData;
                    rtuServer.IncommingData += DriverIncommingData;
                    _listener = _uart.GetListener(rtuServer);
                    _listener.ServeCommand += listener_ServeCommand;
                    _listener.Start();
                    AppendLog(String.Format("Connected using RTU to {0}", PortName));
                    break;

                case CommunicationMode.UDP:
                    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _socket.Bind(new IPEndPoint(IPAddress.Any, TCPPort));
                    //create a server driver
                    var udpServer = new ModbusServer(new ModbusTcpCodec());
                    udpServer.OutgoingData  += DriverOutgoingData;
                    udpServer.IncommingData += DriverIncommingData;
                    //listen for an incoming request
                    _listener = _socket.GetUdpListener(udpServer);
                    _listener.ServeCommand += listener_ServeCommand;
                    _listener.Start();
                    AppendLog(String.Format("Listening to UDP port {0}", TCPPort));
                    break;

                case CommunicationMode.TCP:
                    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _socket.Bind(new IPEndPoint(IPAddress.Any, TCPPort));
                    _socket.Listen(10);
                    //create a server driver
                    _thread = new Thread(Worker);
                    _thread.Start();
                    AppendLog(String.Format("Listening to TCP port {0}", TCPPort));
                    break;
                }
            }
            catch (Exception ex)
            {
                AppendLog(ex.Message);
                return;
            }
            btnConnect.Enabled       = false;
            buttonDisconnect.Enabled = true;
            grpExchange.Enabled      = true;
            groupBoxTCP.Enabled      = false;
            groupBoxRTU.Enabled      = false;
            groupBoxMode.Enabled     = false;
        }
コード例 #9
0
        public void startServer()
        {
            modbusServer = new ModbusServer();
            modbusServer.UnitIdentifier = 255;

            modbusServer.holdingRegisters[1012] = 1100;
            modbusServer.holdingRegisters[1022] = 1200;
            modbusServer.holdingRegisters[1032] = 1300;
            modbusServer.holdingRegisters[1042] = 1400;
            modbusServer.holdingRegisters[1052] = 1500;

            modbusServer.HoldingRegistersChanged         += holdingRegistersChanged;
            modbusServer.NumberOfConnectedClientsChanged += ModbusServer_NumberOfConnectedClientsChanged;

            modbusServer.Listen();

            Console.WriteLine("ModbusTCP server started");

            while (true)
            {
                try
                {
                    var read = Console.ReadLine().Trim();
                    if (read.Contains(" "))
                    {
                        var addressAndValue = read.Split(' ');
                        var address         = int.Parse(addressAndValue[0]);
                        var value           = short.Parse(addressAndValue[1]);
                        modbusServer.holdingRegisters[address] = value;
                    }
                    else if (read == "q4" || read == "p4")
                    {
                        for (int i = 0; i < modbusServer.holdingRegisters.localArray.Length; i++)
                        {
                            if (modbusServer.holdingRegisters[i] != 0)
                            {
                                PrintHoldingRegister(i);
                            }
                        }
                    }
                    else if (read == "exit" || read == "quit")
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            modbusServer.StopListening();
        }
コード例 #10
0
    private void AddServerMethod()
    {
        var server = new ModbusServer {
            Port = port
        };

        server.Listen();
        server.HoldingRegistersChanged += Ser_HoldingRegistersChanged;
        servers.Add(server);
        MessageBox.Show("Server added.");
        server.holdingRegisters[0] = 11;     // register is changed, but no event is fired
    }
コード例 #11
0
        /// <summary>
        /// Method for removing modbus server - returns null if server does not exist
        /// </summary>
        /// <param name="unitId"></param>
        /// <returns></returns>
        public static ModbusServer RemoveServer(Int32 port)
        {
            ModbusServer serverToReturn = null;

            if (ModbusFactory._allServers.ContainsKey(port))
            {
                StopListening(port);
                serverToReturn = ModbusFactory._allServers[port];
                ModbusFactory._allServers.Remove(port);
            }

            return(serverToReturn);
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: wanglong/modbus-tcp
        static async Task RunServerAsync()
        {
            //InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            ModbusResponse response = new ModbusResponse();
            ModbusServer   server   = new ModbusServer(response);

            await server.Start();

            Console.WriteLine("Server Started");
            Console.ReadLine();

            await server.Stop();
        }
コード例 #13
0
ファイル: ModbusTcpTests.cs プロジェクト: blinds52/Modbus
        public async Task ServerStartTest()
        {
            int port = 0;

            using (var testServer = new MiniTestServer())
            {
                testServer.Start();
                port = testServer.Port;
            }

            using var server = new ModbusServer(port);
            await server.Initialization;

            Assert.IsTrue(server.IsRunning);
        }
コード例 #14
0
 public HttpXmlReader()
 {
     try
     {
         EventLogInit();
         _modbusServer = new ModbusServer();
         Config        = new Config();
         ReConfigur();
         StartServer();
     }
     catch (Exception ex)
     {
         _eventLog.WriteEntry($"Constructor ex: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
     }
 }
コード例 #15
0
        /// <summary>
        /// Method for creating a new server and return it
        /// Returns existing server = if server of given port exists
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        private static ModbusServer CreateServer(Int32 port)
        {
            ModbusServer serverToReturn = null;

            if (ModbusFactory._allServers.ContainsKey(port))
            {
                serverToReturn = ModbusFactory._allServers[port];
            }
            else
            {
                serverToReturn      = new ModbusServer();
                serverToReturn.Port = port;

                ModbusFactory._allServers[port] = serverToReturn;
            }

            return(serverToReturn);
        }
コード例 #16
0
        private void AcceptClient(IAsyncResult ar)
        {
            if (!(ar.AsyncState is Socket listener))
            {
                return;
            }

            try
            {
                var client  = listener.EndAccept(ar);
                var address = client?.RemoteEndPoint.ToString();

                if (address != null)
                {
                    Trace.TraceInformation("ModbusSlave: Client connected " + address);
                    _connectedMasters.Add(client);
                    Connected?.Invoke(address);
                    LastAccess = DateTime.Now;

                    var codec  = new ModbusTcpCodec();
                    var server = new ModbusServer(codec)
                    {
                        Address = Id
                    };
                    var host = new TcpServer(client, server)
                    {
                        IdleTimeout = 60
                    };
                    host.ServeCommand += ListenerServeCommand;
                    host.Start();
                    host.Disconnected += () => OnClientDisconnected(client, address);
                }

                listener.BeginAccept(AcceptClient, listener);
            }
            catch (ObjectDisposedException)
            {
                // listener terminated
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
            }
        }
コード例 #17
0
 private static Task MainAsync()
 {
     using (var mbs = new ModbusServer())
     {
         mbs.AddDevice(1);
         mbs.Initialization.GetAwaiter().GetResult();
         Console.WriteLine("Server started");
         while (true)
         {
             var register = mbs.GetHoldingRegister(1, 0);
             if (register.Value == 99)
             {
                 break;
             }
             Console.WriteLine($"Holding register 0: {register}");
             Thread.Sleep(1000);
         }
         Console.WriteLine("Server closed");
     }
     return(Task.CompletedTask);
 }
コード例 #18
0
        static async Task RunServerAsync()
        {
            //InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            ModbusResponse response = new ModbusResponse();
            ModbusServer   server   = new ModbusServer(response);

            await server.Start();

            Console.WriteLine("Server Started");

            //打开PLC
            try
            {
                MyBuffer.S71200.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                goto exitprog;
            }
            //new 即 start(),所以不能在定义处new
            MyBuffer.myTimer = new System.Threading.Timer(MyBuffer.Display, "Processing timer event", 2000, 10000);


            Console.ReadLine();
exitprog:
            if (MyBuffer.myTimer != null)
            {
                MyBuffer.myTimer.Dispose();
                Console.WriteLine("myTimer Disposed");
            }
            if (MyBuffer.S71200.IsConnected)
            {
                Console.WriteLine("S71200 Closed");
                MyBuffer.S71200.Close();
            }

            await server.Stop();
        }
コード例 #19
0
        public override void Run(CancellationToken token)
        {
            //create an UART port
            using (var uart = new SerialPortEx())
            {
                //open the serial port
                uart.PortName = HardwareModel.Instance.SerialPort;
                uart.Open();

                var prm = new SerialPortParams(
                    HardwareModel.Instance.SerialSettings,
                    false);

                uart.SetParams(prm);

                //create a server driver
                var server = new ModbusServer(new ModbusRtuCodec());
                server.Address = (byte)HardwareModel.Instance.Address;

                while (token.IsCancellationRequested == false)
                {
                    //wait for an incoming connection
                    var listener = uart.GetServer(server);
                    listener.ServeCommand += new ServeCommandHandler(ListenerServeCommand);
                    listener.Start();

                    while (listener.IsRunning)
                    {
                        if (token.IsCancellationRequested)
                        {
                            listener.Abort();
                        }
                        else
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
            }
        }
コード例 #20
0
ファイル: SlaveTcpWorker.cs プロジェクト: josemotta/Netduino
        public override void Run(CancellationToken token)
        {
            //create a TCP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                //place it as listener on the specified port
                var ept = new IPEndPoint(
                    IPAddress.Any,
                    HardwareModel.Instance.NetworkPort
                    );

                socket.Bind(ept);
                socket.Listen(10);

                //create a server driver
                var server = new ModbusServer(new ModbusTcpCodec());
                server.Address = (byte)HardwareModel.Instance.Address;

                while (token.IsCancellationRequested == false)
                {
                    //wait for an incoming connection
                    var listener = socket.GetTcpListener(server);
                    listener.ServeCommand += new ServeCommandHandler(ListenerServeCommand);
                    listener.Start();

                    while (listener.IsRunning)
                    {
                        if (token.IsCancellationRequested)
                        {
                            listener.Abort();
                        }
                        else
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
            }
        }
コード例 #21
0
ファイル: MainWindow.cs プロジェクト: AKSD/unused
    /// <summary>
    /// Initializes a new instance of the <see cref="MainWindow"/> class.
    /// </summary>
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
        statusbar1.TooltipText = "";

        //Modbus client initialize and read - just for testing
        modbusClient          = new ModbusClient(ipAddress, port);
        modbusClient.Baudrate = baudRate;
        modbusClient.Connect();

        if (modbusClient.Connected)
        {
            bool[] readCoils = modbusClient.ReadCoils(0, 2);
            modbusClient.Disconnect();
        }

        //Modbus server
        modbusServer          = new ModbusServer();
        modbusServer.Baudrate = baudRate;
        modbusServer.Listen();
        modbusServer.StopListening();
    }
コード例 #22
0
ファイル: Form1.cs プロジェクト: Sleepy228/ModbusTSP-IP
        private void button1_Click(object sender, EventArgs e)
        {
            if (statusServer.Text == "offline")
            {
                modbusServer = new EasyModbus.ModbusServer();
                modbusServer.holdingRegisters    = new EasyModbus.ModbusServer.HoldingRegisters(modbusServer);
                modbusServer.holdingRegisters[5] = 99; //Для примера зададим одному из регистров конкретное значение

                statusServer.Text      = "online";
                statusServer.ForeColor = Color.Green;


                modbusServer.Listen();
                Console.Read();
            }
            else
            {
                modbusServer.StopListening();

                statusServer.Text      = "offline";
                statusServer.ForeColor = Color.Crimson;
            }
        }
コード例 #23
0
ファイル: SlaveForm.cs プロジェクト: gbcwbz/ModbusTool
        /// <summary>
        /// Running thread handler
        /// </summary>
        protected void Worker()
        {
            var server = new ModbusServer(new ModbusTcpCodec()) { Address = SlaveId };
            server.IncommingData += DriverIncommingData;
            server.OutgoingData += DriverOutgoingData;
            try
            {
                while (_thread.ThreadState == ThreadState.Running)
                {
                    //wait for an incoming connection
                    _listener = _socket.GetTcpListener(server);
                    _listener.ServeCommand += listener_ServeCommand;
                    _listener.Start();
                    AppendLog(String.Format("Accepted connection."));
                    Thread.Sleep(1);
                }
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
            }

        }
コード例 #24
0
ファイル: Form1.cs プロジェクト: cbalakus/Modbus-Writer
        void SetEnableds(bool val)
        {
            var gogo = true;

            if (!val)
            {
                if (startAddr.Text.Trim() == "")
                {
                    startAddr.Focus();
                    return;
                }
                if (endAddr.Text.Trim() == "")
                {
                    endAddr.Text = startAddr.Text;
                }
                if (startRange.Text.Trim() == "")
                {
                    startRange.Focus();
                    return;
                }
                if (endRange.Text.Trim() == "")
                {
                    endRange.Text = (Convert.ToInt32(startRange.Text) + 100).ToString();
                }
                if (IsServer.Checked)
                {
                    _mbSrv          = new ModbusServer();
                    _mbSrv._output += (byte[] bytes, string type) =>
                                      Log?.Invoke(type + " : " + BitConverter.ToString(TrimeZeros(bytes)).Replace('-', ' '));
                    if (radioButton1.Checked)
                    {
                        _mbSrv.Port = Convert.ToInt32(port.Text);
                        _mbSrv.Listen();
                    }
                    else
                    {
                        if (serialPort.Items.Count <= 0)
                        {
                            MessageBox.Show("Comport yok dedik ya..");
                            return;
                        }
                        _mbSrv.SerialPort = serialPort.SelectedItem.ToString();
                        _mbSrv.StopBits   = System.IO.Ports.StopBits.One;
                        _mbSrv.Parity     = System.IO.Ports.Parity.None;
                        _mbSrv.Baudrate   = Convert.ToInt32(baudRate.Text);
                    }
                    _mbSrv.UnitIdentifier = Convert.ToByte(uID.Text);
                }
                else
                {
                    _mbClt = new ModbusClient(ipAddr.Text, Convert.ToInt32(port.Text))
                    {
                        UnitIdentifier = Convert.ToByte(uID.Text)
                    };
                    _mbClt._output += (byte[] bytes, string type) =>
                                      Log?.Invoke(type + " : " + BitConverter.ToString(TrimeZeros(bytes)).Replace('-', ' '));
                    try
                    {
                        _mbClt.Connect();
                    }
                    catch (Exception ex)
                    {
                        gogo = false;
                        MessageBox.Show(ex.Message);
                    }
                }
                if (!gogo)
                {
                    return;
                }
                running = true;
                Task.Run(async() =>
                {
                    var dly          = Convert.ToInt32(delay.Text);
                    var startAddress = Convert.ToInt32(startAddr.Text);
                    var endAddress   = Convert.ToInt32(endAddr.Text);
                    var startRn      = Convert.ToInt32(startRange.Text);
                    var endRn        = Convert.ToInt32(endRange.Text);
                    while (running)
                    {
                        if (randomWriteChk.Checked)
                        {
                            if (IsServer.Checked)
                            {
                                for (int i = startAddress; i < endAddress; i++)
                                {
                                    var rndVal = Convert.ToInt32(_rnd.Next(startRn, endRn >= 65536 ? 65535 : endRn));
                                    if (rndVal >= 32768)
                                    {
                                        rndVal = ((65536 - rndVal) * -1);
                                    }
                                    var booVal = _rnd.Next(0, 2) == 1;
                                    if (radHR.Checked)
                                    {
                                        _mbSrv.holdingRegisters.localArray[i] = Convert.ToInt16(rndVal);
                                    }
                                    else if (radIR.Checked)
                                    {
                                        _mbSrv.inputRegisters.localArray[i] = Convert.ToInt16(rndVal);
                                    }
                                    else if (radCO.Checked)
                                    {
                                        _mbSrv.coils.localArray[i] = booVal;
                                    }
                                    else if (radDis.Checked)
                                    {
                                        _mbSrv.discreteInputs.localArray[i] = booVal;
                                    }
                                }
                            }
                            else
                            {
                                if (radHR.Checked)
                                {
                                    List <int> _values = new List <int>();
                                    for (int i = startAddress; i < endAddress; i++)
                                    {
                                        var rndVal = _rnd.Next(startRn, endRn >= 65536 ? 65535 : endRn);
                                        if (rndVal >= 32768)
                                        {
                                            rndVal = ((65536 - rndVal) * -1);
                                        }
                                        _values.Add(rndVal);
                                    }
                                    _mbClt.WriteMultipleRegisters(startAddress, _values.ToArray());
                                }
                                else if (radCO.Checked)
                                {
                                    List <bool> _values = new List <bool>();
                                    for (int i = startAddress; i < endAddress; i++)
                                    {
                                        _values.Add(_rnd.Next(0, 2) == 1);
                                    }
                                    _mbClt.WriteMultipleCoils(startAddress, _values.ToArray());
                                }
                            }
                        }
                        await Task.Delay(dly);
                    }
                });
            }
            else
            {
                running = false;
                if (IsServer.Checked)
                {
                    _mbSrv.StopListening();
                }
                else
                {
                    _mbClt.Disconnect();
                }
            }
            button2.Enabled         = !val;
            button1.Enabled         = val;
            startAddr.Enabled       = val;
            endAddr.Enabled         = val;
            startRange.Enabled      = val;
            endRange.Enabled        = val;
            delay.Enabled           = val;
            port.Enabled            = val;
            uID.Enabled             = val;
            radioButton1.Enabled    = val;
            radioButton2.Enabled    = val;
            showSignalPanel.Enabled = !val;
        }
コード例 #25
0
 public InputRegisters(ModbusServer modbusServer)
 {
     this.modbusServer = modbusServer;
 }
コード例 #26
0
 public DiscreteInputs(ModbusServer modbusServer)
 {
     this.modbusServer = modbusServer;
 }
コード例 #27
0
ファイル: Coils.cs プロジェクト: hvuSyslogic/DemoModbus
 public Coils(ModbusServer modbusServer)
 {
     this.modbusServer = modbusServer;
 }
コード例 #28
0
        //ModbusClient easyModbusTCPClient;

        public Server()
        {
            InitializeComponent();
            easyModbusTCPServer = new EasyModbus.ModbusServer();
        }
コード例 #29
0
 public HoldingRegisters(ModbusServer modbusServer)
 {
     this.modbusServer = modbusServer;
 }
コード例 #30
0
ファイル: Program.cs プロジェクト: wangzhefeng2000/cetdevelop
        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
        }