Example #1
0
        /// <summary>
        /// 打开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_open_Click(object sender, EventArgs e)
        {
            try
            {
                if (txt_content.Text.Contains("小技巧"))
                {
                    txt_content.Text = string.Empty;
                }
                var PortName = cb_portNameSend.Text.ToString();
                var BaudRate = int.Parse(cb_baudRate.Text.ToString());
                var DataBits = int.Parse(txt_dataBit.Text.ToString());
                var StopBits = (StopBits)int.Parse(txt_stopBit.Text.ToString());
                var parity   = cb_parity.SelectedIndex == 0 ? Parity.None : (cb_parity.SelectedIndex == 1 ? Parity.Odd : Parity.Even);
                client?.Close();
                client = new ModbusRtuClient(PortName, BaudRate, DataBits, StopBits, parity);
                var result = client.Open();
                if (result.IsSucceed)
                {
                    but_open.Enabled        = false;
                    cb_portNameSend.Enabled = false;
                    but_read.Enabled        = true;
                    but_write.Enabled       = true;
                    but_open.Enabled        = false;
                    but_close.Enabled       = true;
                    but_sendData.Enabled    = true;

                    //按了Ctrl后的鼠标点击
                    if ((ModifierKeys & Keys.Control) == Keys.Control)
                    {
                        Task.Run(() =>
                        {
                            AutoOpenRead();
                        });
                    }
                    else
                    {
                        AppendText("连接成功");
                    }
                }
                else
                {
                    AppendText($"连接失败:{result.Err}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public async void ServerHandlesRequestFire()
        {
            // Arrange
            var serialPort = new FakeSerialPort();

            var server = new ModbusRtuServer(unitIdentifier: 1);

            server.Start(serialPort);

            var client = new ModbusRtuClient();

            client.Connect(serialPort);

            await Task.Run(() =>
            {
                var data       = Enumerable.Range(0, 20).Select(i => (float)i).ToArray();
                var sw         = Stopwatch.StartNew();
                var iterations = 10000;

                for (int i = 0; i < iterations; i++)
                {
                    client.WriteMultipleRegisters(0, 0, data);
                }

                var timePerRequest = sw.Elapsed.TotalMilliseconds / iterations;
                _logger.WriteLine($"Time per request: {timePerRequest * 1000:F0} us. Frequency: {1 / timePerRequest * 1000:F0} requests per second.");

                client.Close();
            });

            server.Stop();

            // Assert
        }
Example #3
0
        private void but_sendData_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txt_dataPackage.Text))
                {
                    MessageBox.Show("请输入要发送的报文");
                    return;
                }
                var dataPackageString = txt_dataPackage.Text.Replace(" ", "");
                if (dataPackageString.Length % 2 != 0)
                {
                    MessageBox.Show("请输入正确的的报文");
                    return;
                }

                var dataPackage = DataConvert.StringToByteArray(txt_dataPackage.Text?.Trim(), false);
                var msg         = client.SendPackage(dataPackage);
                AppendText($"[请求报文]{string.Join(" ", dataPackage.Select(t => t.ToString("X2")))}\r");
                AppendText($"[响应报文]{string.Join(" ", msg.Select(t => t.ToString("X2")))}\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                client.Close();
                client.Open();
            }
        }
Example #4
0
        public async Task 长连接主动开关()
        {
            client.Open();

            short Number = 33;

            client.Write("4", Number, stationNumber);
            Assert.True(client.ReadInt16("4", stationNumber).Value == Number);

            Number = 34;
            client.Write("4", Number, stationNumber);
            Assert.True(client.ReadInt16("4", stationNumber).Value == Number);

            Number = 1;
            client.Write("12", Number, stationNumber);
            Assert.True(client.ReadInt16("12", stationNumber).Value == 1);

            Number = 0;
            client.Write("12", Number, stationNumber);
            Assert.True(client.ReadInt16("12", stationNumber).Value == 0);

            int numberInt32 = -12;

            client.Write("4", numberInt32, stationNumber);
            Assert.True(client.ReadInt32("4", stationNumber).Value == numberInt32);

            float numberFloat = 112;

            client.Write("4", numberFloat, stationNumber);
            Assert.True(client.ReadFloat("4", stationNumber).Value == numberFloat);

            double numberDouble = 32;

            client.Write("4", numberDouble, stationNumber);
            Assert.True(client.ReadDouble("4", stationNumber).Value == numberDouble);

            client.Close();
        }
Example #5
0
        static int RunDetectPorts(DetectPortsOptions opts)
        {
            var validPorts = new List <PortDescription>();

            using (var client = new ModbusRtuClient())
            {
                client.BaudRate = opts.BaudRate;
                client.DataBits = opts.DataBits;
                client.Parity   = opts.Parity;

                foreach (var portDesc in SerialPortStream.GetPortDescriptions())
                {
                    client.PortName = portDesc.Port;
                    if (opts.Verbose)
                    {
                        Console.Error.Write($"Trying {portDesc.Port}");
                        if (!string.IsNullOrEmpty(portDesc.Description))
                        {
                            Console.Out.Write($" ({portDesc.Description})");
                        }
                        Console.Out.Write("...");
                    }
                    try
                    {
                        client.Open();
                    }
                    catch (Exception exp) when(exp is UnauthorizedAccessException || exp is InvalidOperationException)
                    {
                        if (opts.Verbose)
                        {
                            Console.Error.WriteLine("already in use.");
                        }
                        continue;
                    }
                    catch (IOException)
                    {
                        if (opts.Verbose)
                        {
                            Console.Error.WriteLine("cannot open.");
                        }
                        continue;
                    }

                    try
                    {
                        client.ReadHoldingRegisters(opts.UnitAddress, 0, 1);
                    }
                    catch (TimeoutException)
                    {
                        if (opts.Verbose)
                        {
                            Console.Error.WriteLine("timeout.");
                        }
                        client.Close();
                        continue;
                    }
                    catch (FormatException)
                    {
                        if (opts.Verbose)
                        {
                            Console.Error.WriteLine("frame error.");
                        }
                        client.Close();
                        continue;
                    }
                    catch (ModbusException)
                    {
                    }
                    if (opts.Verbose)
                    {
                        Console.Error.WriteLine("valid.");
                    }
                    validPorts.Add(portDesc);
                    client.Close();
                }
            }
            if (opts.Verbose)
            {
                Console.Error.WriteLine();
            }
            foreach (var portDesc in validPorts)
            {
                Console.Out.Write($"{portDesc.Port}");
                if (!string.IsNullOrEmpty(portDesc.Description))
                {
                    Console.Out.Write($" ({portDesc.Description})");
                }
                Console.Out.WriteLine();
            }

            return(0);
        }
Example #6
0
        static async Task Main(string[] args)
        {
            /* Modbus RTU uses a COM port for communication. Therefore, to run
             * this sample, you need to make sure that there are real or virtual
             * COM ports available. The easiest way is to install one of the free
             * COM port bridges available in the internet. That way, the Modbus
             * server can connect to e.g. COM1 which is virtually linked to COM2,
             * where the client is connected to.
             *
             * When you only want to use the client and communicate to an external
             * Modbus server, simply remove all server related code parts in this
             * sample and connect to real COM port using only the client.
             */

            /* define COM ports */
            var serverPort = "COM1";
            var clientPort = "COM2";

            /* prepare dependency injection */
            var services = new ServiceCollection();

            ConfigureServices(services);

            /* create types */
            var provider      = services.BuildServiceProvider();
            var loggerFactory = provider.GetRequiredService <ILoggerFactory>();
            var serverLogger  = loggerFactory.CreateLogger("Server");
            var clientLogger  = loggerFactory.CreateLogger("Client");

            /* create Modbus RTU server and client */
            var server = new ModbusRtuServer(unitIdentifier: 1);
            var client = new ModbusRtuClient();

            /* run Modbus RTU server */
            var cts = new CancellationTokenSource();

            var task_server = Task.Run(async() =>
            {
                server.Start(serverPort);
                serverLogger.LogInformation("Server started.");

                while (!cts.IsCancellationRequested)
                {
                    // lock is required to synchronize buffer access between this application and the Modbus client
                    lock (server.Lock)
                    {
                        DoServerWork(server);
                    }

                    // update server buffer content once per second
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }

                server.Dispose();
            }, cts.Token);

            /* run Modbus RTU client */
            var task_client = Task.Run(() =>
            {
                client.Connect(clientPort);

                try
                {
                    DoClientWork(client, clientLogger);
                }
                catch (Exception ex)
                {
                    clientLogger.LogError(ex.Message);
                }

                client.Close();

                Console.WriteLine("Tests finished. Press any key to continue.");
                Console.ReadKey(true);
            });

            // wait for client task to finish
            await task_client;

            // stop server
            cts.Cancel();
            await task_server;

            server.Stop();
            serverLogger.LogInformation("Server stopped.");
        }
Example #7
0
        static async Task Main(string[] args)
        {
            /* Modbus RTU uses a COM port for communication. Therefore, to run
             * this sample, you need to make sure that there are real or virtual
             * COM ports available. The easiest way is to install one of the free
             * COM port bridges available in the internet. That way, the Modbus
             * server can connect to e.g. COM1 which is virtually linked to COM2,
             * where the client is connected to.
             *
             * When you only want to use the client and communicate to an external
             * Modbus server, simply remove all server related code parts in this
             * sample and connect to real COM port using only the client.
             */

            /* define COM ports */
            var serverPort = "COM1";
            var clientPort = "COM2";

            /* create logger */
            var loggerFactory = LoggerFactory.Create(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                loggingBuilder.AddConsole();
            });

            var serverLogger = loggerFactory.CreateLogger("Server");
            var clientLogger = loggerFactory.CreateLogger("Client");

            /* create Modbus RTU server */
            using var server = new ModbusRtuServer(unitIdentifier: 1)
                  {
                      // see 'RegistersChanged' event below
                      EnableRaisingEvents = true
                  };

            /* subscribe to the 'RegistersChanged' event (in case you need it) */
            server.RegistersChanged += (sender, registerAddresses) =>
            {
                // the variable 'registerAddresses' contains a list of modified register addresses
            };

            /* create Modbus RTU client */
            var client = new ModbusRtuClient();

            /* run Modbus RTU server */
            var cts = new CancellationTokenSource();

            var task_server = Task.Run(async() =>
            {
                server.Start(serverPort);
                serverLogger.LogInformation("Server started.");

                while (!cts.IsCancellationRequested)
                {
                    // lock is required to synchronize buffer access between this application and the Modbus client
                    lock (server.Lock)
                    {
                        DoServerWork(server);
                    }

                    // update server register content once per second
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }, cts.Token);

            /* run Modbus RTU client */
            var task_client = Task.Run(() =>
            {
                client.Connect(clientPort);

                try
                {
                    DoClientWork(client, clientLogger);
                }
                catch (Exception ex)
                {
                    clientLogger.LogError(ex.Message);
                }

                client.Close();

                Console.WriteLine("Tests finished. Press any key to continue.");
                Console.ReadKey(true);
            });

            // wait for client task to finish
            await task_client;

            // stop server
            cts.Cancel();
            await task_server;

            server.Stop();
            serverLogger.LogInformation("Server stopped.");
        }