示例#1
0
        public async Task ClientEventsTest()
        {
            int connectEvents    = 0;
            int disconnectEvents = 0;

            using (var server = new MiniTestServer())
            {
                server.Start();
                using (var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger()))
                {
                    client.Connected += (sender, args) =>
                    {
                        connectEvents++;
                    };
                    client.Disconnected += (sender, args) =>
                    {
                        disconnectEvents++;
                    };

                    Assert.AreEqual(0, connectEvents);
                    Assert.AreEqual(0, disconnectEvents);

                    await client.Connect();

                    Assert.IsTrue(client.IsConnected);

                    await EnsureWait();                     // get events raised

                    Assert.AreEqual(1, connectEvents);
                    Assert.AreEqual(0, disconnectEvents);

                    await server.Stop();

                    await client.ReadHoldingRegisters(0, 0, 1);
                    await EnsureWait();                      // time to set all information

                    Assert.IsFalse(client.IsConnected);

                    await EnsureWait();                     // get events raised

                    Assert.AreEqual(1, connectEvents);
                    Assert.AreEqual(1, disconnectEvents);

                    server.Start();
                    await client.ConnectingTask;
                    Assert.IsTrue(client.IsConnected);
                }

                await EnsureWait();                 // get events raised

                Assert.AreEqual(2, connectEvents);
                Assert.AreEqual(2, disconnectEvents);
            }
        }
示例#2
0
 public ModbusTCPService(string ipAddress, int port)
 {
     this.modbusClient = new ModbusClient(ipAddress, port);
     try
     {
         modbusClient.Connect();
     }
     catch (Exception)
     {
     }
 }
        private void Btn_Init_Click(object sender, RoutedEventArgs e)
        {
            StopCamera();
            try     // Init Camera
            {
                //if (Lb_Status_Camera.Content.ToString() != "Good")
                //{
                //GetVideoDevices();
                //StartCamera_02(VideoDevices[Cb_Camera.SelectedIndex].MonikerString);
                StartCamera_02();
                //flag_init_Camera = true;
                Lb_Status_Camera.Content = "Good";
                //}
            }
            catch
            {
                MessageBox.Show("Error103: Failt to start Camera");
                StopCamera();
                //StateMachine_NotInit();
                //flag_init_Camera = false;
                Lb_Status_Camera.Content = "Fail";
            }



            try // ---Modbus Server Setup
            {
                modbusClient = new ModbusClient(Paras.Modbus_Server_IP.Value, int.Parse(Paras.Modbus_Server_Port.Value));
                modbusClient.LogFileFilename = Paras.Modbus_Server_LogFileFilename.Value;
                modbusClient.Connect();
                Dt_Modbus.Start();
                //flag_init_Modbus = true;
                Lb_Status_Modbus.Content = "Good";
            }
            catch
            {
                MessageBox.Show("Error102: Fail to connect to the Modbus Server at the address " + Paras.Modbus_Server_IP.Value + ":" + Paras.Modbus_Server_Port.Value);
                //StateMachine_NotInit();
                //flag_init_Modbus = false;
                Lb_Status_Modbus.Content = "Fail";
            }


            if (Lb_Status_Camera.Content.ToString() == "Good" & Lb_Status_Modbus.Content.ToString() == "Good")
            {
                flag_init = true;
                Lb_Status_Global.Content = "Good";
            }
            else
            {
                flag_init = false;
                Lb_Status_Global.Content = "Fail";
            }
        }
        public EasyModbusRTU(string comPort)
        {
            _master = new ModbusClient(comPort);

            // configure serial port
            _master.Baudrate          = 9600;
            _master.Parity            = Parity.None;
            _master.StopBits          = StopBits.One;
            _master.ConnectionTimeout = 500;
            _master.Connect();
        }
示例#5
0
        private void TnUstawCisnienie_N1_Click(object sender, RoutedEventArgs e)
        {
            ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502);    //Ip-Address and Port of Modbus-TCP-Server

            modbusClient.Connect();
            float CisnienieZadane_N1 = float.Parse(txtCisnienieZadane_N1.Text);

            int[] aaa = ModbusClient.ConvertFloatToRegisters(CisnienieZadane_N1);
            modbusClient.WriteMultipleRegisters(4512, aaa);
            modbusClient.Disconnect();
        }
示例#6
0
        //подключиться к серверу Modbus
        public void ConnectToServer(string ip, int port)
        {
            if (modbusClient == null)
            {
                modbusClient = new ModbusClient();
            }

            //возможные исключения?
            //исключение будет выбрасываться только при попытке подключения
            //какие могут быть исключения помимо "timeout exception"
            modbusClient.Connect(ip, port);
        }
示例#7
0
 public bool connect(string ipaddress, int port)
 {
     try
     {
         _client.Connect(ipaddress, port);
         return(true);
     }
     catch
     {
         return(false);;
     }
 }
示例#8
0
文件: Program.cs 项目: fr830/PLC_SQL
        static void Main(string[] args)
        {
            ModbusClient modbusClient = new ModbusClient("192.168.18.10", 502);

            while (true)
            {
                DateTime myDateTime       = DateTime.Now;                               // Read time value
                string   sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // Store timestamp as formatted string

                try
                {
                    if (modbusClient.Connected)                                          //Controlling of the system is connected.
                    {
                        int[] csd3_1_14Array = modbusClient.ReadHoldingRegisters(0, 30); //Read data from MODBUS TCP IP, start in memory block 0 and read 30 memory blocks.
                        //int[] csd3_1_15Array = modbusClient.ReadHoldingRegisters(101, 100);
                        //int[] csd3_1_16Array = modbusClient.ReadHoldingRegisters(101, 100);

                        using (PLC_dbEntities db = new PLC_dbEntities()) // Entity framework linQ
                        {
                            CSD3_1_14 dataset_14 = new CSD3_1_14
                            {
                                Timestamp  = sqlFormattedDate,                     // Store timestamp, is used as primary key
                                CO2        = csd3_1_14Array[0],                    // Store CO2 value 400 - 10000 ppm
                                Temperatur = (float)csd3_1_14Array[1] / 10,        // Convert Temperature integer to float with 1 decimal and store.
                                Fugtighed  = csd3_1_14Array[2],                    // Store Fugtighed value 0 - 100 %
                                Strøm      = (float)csd3_1_14Array[3] / 100,       // Convert Strøm integer to float with 2 decimals and store. (Do we need to remove negative values)
                                Spænding   = (float)csd3_1_14Array[4] / 100,       // Convert Spænding integer to float with 2 decimals and store. (Do we need to remove negative values)
                                Effekt     = csd3_1_14Array[5],                    // Store Effekt value (Do we need to remove negative values)
                                Energi     = csd3_1_14Array[6] + csd3_1_14Array[7] // Convert the two integers for Energi to one and store. (What operation is needed?)
                            };
                            db.CSD3_1_14.Add(dataset_14);                          // Save dataset to variable


                            db.SaveChanges();   //Save changes to SQL database
                        }

                        Console.WriteLine("[Data recieved] [" + sqlFormattedDate + "]");
                        Thread.Sleep(60000);    // Sleeps for 60 s to limit data storing
                    }
                    else
                    {
                        Console.WriteLine("[" + sqlFormattedDate + "]: Connection not established, trying to connect.");
                        modbusClient.Connect(); // Connect to ModBUS TCPIP
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[ERROR] " + ex.ToString());
                    modbusClient.Disconnect();
                    Thread.Sleep(30000);
                }
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (svimaster.Connected == false)
                {
                    svimaster.UnitIdentifier    = 1;    // Not necessary since default slaveID = 1;
                    svimaster.Baudrate          = 9600; // Not necessary since default baudrate = 9600
                    svimaster.Parity            = System.IO.Ports.Parity.Even;
                    svimaster.StopBits          = System.IO.Ports.StopBits.One;
                    svimaster.ConnectionTimeout = 1000;
                    svimaster.Connect();
                    label1.BackColor = Color.YellowGreen;
                    label1.Text      = "Connect";
                }


                if (svimaster.Connected == true)
                {
                    int[] Weight;
                    float NetWeight;
                    Weight             = svimaster.ReadInputRegisters(25, 2);
                    NetWeight          = ModbusClient.ConvertRegistersToFloat(Weight);
                    textBoxWeight.Text = Convert.ToString(Convert.ToUInt64(NetWeight.ToString()) - Convert.ToUInt64(textBoxNumberOfPareSnag.Text));
                }
            }

            catch
            {
                svimaster.Disconnect();
                try
                {
                    svimaster.Connect();
                }
                catch
                {
                    textBoxWeight.Text = "99999999";
                }
            }
        }
示例#10
0
        public void OdczytajRejestry()
        {
            ModbusClient modbusClient = new ModbusClient(PLC_IP, PLC_PORT);    //Ip-Address and Port of Modbus-TCP-Server

            modbusClient.Connect();

            CisnienieZadaneN1 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4512, 2));
            CisnienieZadaneN2 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4514, 2));
            CisnienieZadaneN3 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4516, 2));
            CisnienieZadaneN4 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4518, 2));

            TolerancjaCisnieniaN1 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4510, 2));
            TolerancjaCisnieniaN2 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4526, 2));
            TolerancjaCisnieniaN3 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4528, 2));
            TolerancjaCisnieniaN4 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4530, 2));

            CisnienieN1 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2000, 2));
            CisnienieN2 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2002, 2));
            CisnienieN3 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2004, 2));
            CisnienieN4 = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2006, 2));

            CzasPomiaru_N1 = ModbusClient.ConvertRegistersToInt(modbusClient.ReadHoldingRegisters(4532, 2));

            PracaGrzalek = modbusClient.ReadCoils(1296, 1);

            PracaMieszadla = modbusClient.ReadCoils(1298, 1);

            Elektrozawor_N1 = modbusClient.ReadCoils(1298, 1);
            Elektrozawor_N2 = modbusClient.ReadCoils(1299, 1);
            Elektrozawor_N3 = modbusClient.ReadCoils(1300, 1);
            Elektrozawor_N4 = modbusClient.ReadCoils(1301, 1);

            TemperaturaZadana = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4506, 2));

            TolerancjaTemperatury = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(4508, 2));

            Temperatura_T1     = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2008, 2));
            Temperatura_T2     = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2010, 2));
            TemperaturaSrednia = ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(2012, 2));

            GrzanieWody = modbusClient.ReadCoils(2248, 1);

            WodaNagrzana = modbusClient.ReadCoils(2251, 1);

            BadanieZasadnicze = modbusClient.ReadCoils(2249, 1);

            ProbkowanieCisnienia = modbusClient.ReadHoldingRegisters(4504, 1);

            ProbkowanieTemperatury = modbusClient.ReadHoldingRegisters(4505, 1);

            modbusClient.Disconnect();
        }
        static void Main(string[] args)
        {
            ModbusClient mbus_client;
            S7Client     s7_client;
            TProc        tp = new TProc();
            string       ans;

            Console.WriteLine("Select mode of operation:\n(M)odbus, (S)7Comm");
            ans = Console.ReadLine();
            if (ans == "M" || ans == "m")
            {
                mbus_client = new ModbusClient("127.0.0.1", 502);
                try
                {
                    mbus_client.Connect();
                }
                catch
                {
                    Console.WriteLine("Cannot connect via Modbus TCP, aborting execution");
                    return;
                }
                Console.WriteLine("Succesfully connected via Modbus TCP, starting ticking...");
                while (true)
                {
                    Thread.Sleep(1000);
                    tp.Tick(mbus_client);
                }
            }
            else if (ans == "S" || ans == "s")
            {
                s7_client = new S7Client();
                try
                {
                    s7_client.ConnectTo("192.168.56.101", 0, 2);
                }
                catch
                {
                    Console.WriteLine("Cannot connect via S7 Comm, aborting execution");
                    return;
                }
                Console.WriteLine("Succesfully connected via S7 Comm, starting ticking...");
                while (true)
                {
                    Thread.Sleep(1000);
                    tp.Tick(s7_client);
                }
            }
            else
            {
                Console.WriteLine("Invalid mode of operation");
            }
        }
示例#12
0
        private void button1_Click(object sender, EventArgs e)
        {
            // if (_modbusMaster == null)
            // _modbusMaster = new RFEnlaces.ModbusProtocol.SerialRTU(comboBox1.SelectedItem.ToString());
            modbusClient = new ModbusClient("COM3");
            modbusClient.UnitIdentifier    = 3;
            modbusClient.Parity            = System.IO.Ports.Parity.None;
            modbusClient.StopBits          = System.IO.Ports.StopBits.One;
            modbusClient.ConnectionTimeout = 500;
            modbusClient.Connect();

            timer1.Start();
        }
示例#13
0
文件: Form1.cs 项目: Vyctrus/PeryfV2
        public void connectAndrzej()
        {
            //ModbusClient modbusClient = new ModbusClient("COM1");
            ModbusClient modbusX = new ModbusClient("127.0.0.1", 502);

            modbusX.ConnectionTimeout = 500;
            modbusX.Connect();
            int[] readHoldingRegisters = modbusX.ReadHoldingRegisters(0, 10);
            foreach (int i in readHoldingRegisters)
            {
                Debug.WriteLine("Value of register " + i + "is" + readHoldingRegisters[i] + "\n");
            }
        }
示例#14
0
 string modbusClient_Connect()
 {
     try
     {
         modbusClient.Disconnect();
         modbusClient.Connect(plcIP.Text, 502);
         return(modbusClient.Connected ? "Conectado" : "Desconectado");
     }
     catch (Exception se)
     {
         return(se.Message);
     }
 }
示例#15
0
        public (bool rtn, string msg) Open(ePWR_PortName Port, int[] addrAry, int enb4Bit)
        {
            try
            {
                int   idx      = 0;
                Any64 EnbItems = new Any64();
                EnbItems.INT32_0 = enb4Bit;
                foreach (var addr in addrAry)
                {
                    var item = _dicItems[(ePWRREAD_ITEMS)idx];
                    item.bEnb = EnbItems[idx];
                    item.add  = addr;
                    idx++;
                }
                modbusClnt = new ModbusClient();
                modbusClnt.ConnectedChanged += new EasyModbus.ModbusClient.ConnectedChangedHandler(On_Connected);
                modbusClnt.SerialPort        = Port.ToString();
                modbusClnt.Baudrate          = 38400;
                switch (type)
                {
                case ePWRTYPE.ElgenBattery:
                    modbusClnt.ReceiveDataChanged += new ModbusClient.ReceiveDataChangedHandler(On_ReceiveData);
                    modbusClnt.SendDataChanged    += new ModbusClient.SendDataChangedHandler(On_SendData);
                    modbusClnt.Baudrate            = 9600;
                    modbusClnt.StopBits            = System.IO.Ports.StopBits.One;
                    break;

                case ePWRTYPE.ElgenCharger:
                    modbusClnt.StopBits = System.IO.Ports.StopBits.One;
                    break;

                case ePWRTYPE.AutonicMeter:
                    modbusClnt.Baudrate = 9600;
                    modbusClnt.StopBits = System.IO.Ports.StopBits.Two;
                    break;

                default: return(false, $"Wrong {type} setting!!!!");
                }
                modbusClnt.Parity            = System.IO.Ports.Parity.None;
                modbusClnt.ConnectionTimeout = 500;
                if (!modbusClnt.Connected)
                {
                    modbusClnt.Connect();
                }
                return(true, null);
            }
            catch (Exception e)
            {
                return(false, e.ToString());
            }
        }
示例#16
0
 private void Form1_Load(object sender, EventArgs e)
 {
     WarDisplay   = new WarningDisplay();
     modbusClient = new ModbusClient("192.168.10.65", 502);    //Ip-Address and Port of Modbus-TCP-Server
     modbusClient.Connect();                                   //Connect to Server
     if (modbusClient.Connected)
     {
         WarDisplay.Data = "=======================";
         WarDisplay.Data = "  Connection stablish ";
         WarDisplay.Data = "=======================";
         txtWarning.Text = WarDisplay.Data;
     }
     TData.Enabled = true;
 }
示例#17
0
 public Connect(string ip, int port)
 {
     this.ip   = ip;
     this.port = port;
     try
     {
         modbusClient = new ModbusClient(ip, port);
         modbusClient.Connect();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
示例#18
0
        public async Task ClientConnectTest()
        {
            using var server = new MiniTestServer();
            server.Start();

            using var client = new ModbusClient(IPAddress.Loopback, server.Port);
            await client.Connect();

            Assert.IsTrue(client.IsConnected, "Client shoud be connected");

            await client.Disconnect();

            Assert.IsFalse(client.IsConnected, "Client should not be connected");
        }
示例#19
0
        // GET api/values
        public double Get()
        {
            plc.Connect();
            int[] read = plc.ReadHoldingRegisters(2, 1);
            analogValue = read[0]; // I

            mAValue = analogValue / 1000;

            temperature = ((pvHigh - pvLow) / (iHigh - iLow)) * (mAValue - iLow) + pvLow;

            result = Math.Round(temperature, 1);

            return(result);
        }
示例#20
0
        private void button_givedata_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();

            modbusClient = new ModbusClient("192.168.100.8", 502);    //Ip-Address and Port of Modbus-TCP-Server
            modbusClient.Connect();

            try
            {
                int Address = Convert.ToInt32(startingAddress.Text);
                int kolvo   = Convert.ToInt32(quantity.Text);

                if (RadioHolding.Checked == true)
                {
                    int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters((Address - 40001), (kolvo - Address + 1));

                    for (int i = 0; i < readHoldingRegisters.Length; i++)
                    {
                        if (i < readHoldingRegisters.Length - 1)
                        {
                            dataGridView1.Rows.Insert(i, 1);
                        }

                        dataGridView1.Rows[i].Cells[1].Value = readHoldingRegisters[i].ToString();
                        dataGridView1.Rows[i].Cells[0].Value = (Address + i);
                    }
                }

                if (RadioInput.Checked == true)
                {
                    int[] ReadInputRegisters = modbusClient.ReadInputRegisters((Address - 30001), (kolvo - Address + 1));

                    for (int i = 0; i < ReadInputRegisters.Length; i++)
                    {
                        if (i < ReadInputRegisters.Length - 1)
                        {
                            dataGridView1.Rows.Insert(i, 1);
                        }

                        dataGridView1.Rows[i].Cells[1].Value = ReadInputRegisters[i].ToString();
                        dataGridView1.Rows[i].Cells[0].Value = (Address + i);
                    }
                }
                button_changedata.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString() + "\n\nДиапазон адрессов:\n\nInputRegister - 30001\nHoldingRegisters - 40001");
            }
        }
示例#21
0
        public async Task ClientReadDeviceInformationBasicTest()
        {
            var expectedRequest  = new byte[] { 0, 0, 0, 5, 13, 43, 14, 1, 0 };
            var expectedResponse = new Dictionary <DeviceIDObject, string>
            {
                { DeviceIDObject.VendorName, "AM.WD" },
                { DeviceIDObject.ProductCode, "Mini-Test" },
                { DeviceIDObject.MajorMinorRevision, "1.2.3.4" }
            };

            using (var server = new MiniTestServer())
            {
                server.RequestHandler = (request, clientIp) =>
                {
                    CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect");
                    Console.WriteLine("Server sending response");

                    var bytes = new List <byte>();
                    bytes.AddRange(request.Take(2));
                    bytes.AddRange(new byte[] { 0, 0, 0, 0, 13, 43, 14, 1, 1, 0, 0, (byte)expectedResponse.Count });
                    var len = 8;
                    foreach (var kvp in expectedResponse)
                    {
                        var b = Encoding.ASCII.GetBytes(kvp.Value);
                        bytes.Add((byte)kvp.Key);
                        len++;
                        bytes.Add((byte)b.Length);
                        len++;
                        bytes.AddRange(b);
                        len += b.Length;
                    }
                    bytes[5] = (byte)len;

                    return(bytes.ToArray());
                };
                server.Start();
                using (var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger()))
                {
                    await client.Connect();

                    Assert.IsTrue(client.IsConnected);

                    var deviceInfo = await client.ReadDeviceInformation(13, DeviceIDCategory.Basic);

                    Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
                    CollectionAssert.AreEqual(expectedResponse, deviceInfo, "Response is incorrect");
                }
            }
        }
示例#22
0
        private void button5_Click(object sender, EventArgs e)
        {
            //mi yazma butonu
            ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502);

            tcpclient.Connect();
            int cc = Convert.ToInt32(textBox12.Text);

            int[] mideger = ModbusClient.ConvertDoubleToTwoRegisters(Convert.ToInt32(textBox8.Text));

            tcpclient.WriteMultipleRegisters(cc - 1, mideger);

            //tcpclient.WriteSingleRegister(cc-1, mideger[0]);
            //tcpclient.WriteSingleRegister(cc-1, mideger[1]);
        }
示例#23
0
 private void bt_Connect_Click(object sender, EventArgs e)
 {
     try
     {
         modbusClient = new ModbusClient(tb_Modbus_Server_IP.Text, 502);    //Ip-Address and Port of Modbus-TCP-Server
         modbusClient.Connect();
         lb_status.Text         = "Connected!";
         tmr_Modbus_Com.Enabled = true;
     }
     catch (Exception ex)
     {
         lb_status.Text = ex.ToString();
         throw;
     }
 }
示例#24
0
 //Con 버튼
 private void button1_Click(object sender, EventArgs e)
 {
     MBClient = new ModbusClient(textBox2.Text, 502);
     if (MBClient.Connected != true)
     {
         MBClient.Connect();
         if (MBClient.Connected == true)
         {
             button1.Enabled = false;
             button2.Enabled = true;
             button3.Enabled = false;
             button4.Enabled = true;
         }
     }
 }
示例#25
0
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (whileBoolean)
            {
                Thread.Sleep(100);
                try
                {
                    if (!modbusClient.Connected)
                    {
                        string[] ports = SerialPort.GetPortNames();
                        modbusClient.SerialPort     = ports[0];
                        modbusClient.UnitIdentifier = Convert.ToByte(Properties.Settings.Default.tensionSlave);
                        modbusClient.Baudrate       = Properties.Settings.Default.tensionBaudRate;
                        modbusClient.Connect();
                        VarsTension.client = modbusClient;
                        if (!backgroundWorkerRead.IsBusy)
                        {
                            backgroundWorkerRead.RunWorkerAsync();
                        }
                    }
                    else if (modbusClient.Connected && !backgroundWorkerRead.IsBusy)
                    {
                        backgroundWorkerRead.RunWorkerAsync();
                    }
                }
                catch { }

                //this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                //{
                //    if (modbusClient.Connected)
                //        ss.Text = i++.ToString();
                //    else
                //        sd.Text = j++.ToString();
                //}));
            }
        }
示例#26
0
        /// <summary>
        /// 센서 장비에 연결하고 정상 연결이 되면 true, 아니면 false 반환함.
        /// </summary>
        /// <param name="slave">ModbusClient 변수</param>
        /// <param name="ip">IP 주소</param>
        /// <param name="port">Port주소</param>
        /// <returns></returns>
        private static bool connect(ModbusClient slave, string ip, int port)
        {
            bool result = false;

            try
            {
                slave.Connect(ip, port);
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"Connection Error: slaveID:{slave.UnitIdentifier}, IP:{ip}" + e.Message + " " + e.StackTrace);
            }
            return(result);
        }
示例#27
0
        static async Task Run()
        {
            modbusClient = new ModbusClient("modbus.centralus.azurecontainer.io", 502);
            await modbusClient.Connect();

            int counter = 0;

            do
            {
                Console.WriteLine(getRegister(counter).Result);
                counter += 1;
            } while (counter <= 4);

            await modbusClient.Disconnect();
        }
示例#28
0
        public bool ConnectToSlave(string IP)
        {
            bool ToReturn = false;

            try
            {
                modbusClient = new ModbusClient(IP, 502);    //Ip-Address and Port of Modbus-TCP-Server
                modbusClient.Connect();
                ToReturn = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return(ToReturn);
        }
示例#29
0
        private void button6_Click(object sender, EventArgs e)
        {
            //mf yazma butonu
            ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502);

            tcpclient.Connect();
            int dd = Convert.ToInt32(textBox13.Text);

            float mff = float.Parse(textBox9.Text);

            int[] mfdeger = ModbusClient.ConvertFloatToTwoRegisters(mff);

            tcpclient.WriteMultipleRegisters(dd - 1, mfdeger);
            //tcpclient.WriteSingleRegister(dd, mfdeger[0]);
            //tcpclient.WriteSingleRegister(dd, mfdeger[1]);
        }
        private void ConnectToModbusClient()
        {
            int numberOfTries = 0;
            int sleepInterval = 500;

            string message = $"Connecting to modbus client...";

            Console.WriteLine(message);
            Logger.LogInfo(message);

            while (!ModbusClient.Connected)
            {
                try
                {
                    ModbusClient.Connect();
                }
                catch (ConnectionException ce)
                {
                    Logger.LogWarn("ConnectionException on ModbusClient.Connect().", ce);
                }

                if (!ModbusClient.Connected)
                {
                    numberOfTries++;
                    Logger.LogDebug($"Connecting try number: {numberOfTries}.");

                    if (numberOfTries >= 100)
                    {
                        sleepInterval = 1000;
                    }

                    Thread.Sleep(sleepInterval);
                }
                else if (!ModbusClient.Connected && numberOfTries == int.MaxValue)
                {
                    string timeoutMessage = "Failed to connect to Modbus client by exceeding the maximum number of connection retries.";
                    Logger.LogError(timeoutMessage);
                    throw new Exception(timeoutMessage);
                }
                else
                {
                    message = $"Successfully connected to modbus client.";
                    Console.WriteLine(message);
                    Logger.LogInfo(message);
                }
            }
        }