Exemple #1
0
        private void UpdateInput()
        {
            //int id = 1;
            byte lenght = 0x00;

            if (_inputs != null)
            {
                try
                {
                    lenght = Convert.ToByte(_inputs.Count);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    return;
                }


                bool[] values = null;
                //lock (_lockObject)
                //{
                if (ReadWriteMultiThread)
                {
                    values = _mbReaderClient.ReadCoils(0, lenght);
                }
                else
                {
                    try
                    {
                        Tuple <int, bool>[] setOutputList = null;
                        lock (_setOutputListBuffer)
                        {
                            if (_setOutputListBuffer.Count > 0)
                            {
                                setOutputList = _setOutputListBuffer.ToArray();
                                _setOutputListBuffer.Clear();
                            }
                        }
                        lock (_lockObject)
                        {
                            if (setOutputList != null)
                            {
                                Array.ForEach(setOutputList, output => _mbReaderClient.WriteSingleCoil(output.Item1, output.Item2));
                            }
                            values = _mbReaderClient.ReadCoils(0, lenght);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                //}
                Task.Run(() => UpdateEthernetInputValue(values));
            }
        }
 private void timer1_Tick(object sender, EventArgs e)
 {
     timer1.Enabled = false;
     bool[] readCoils            = modbusClient.ReadCoils(0, 10);             //Read 10 Coils from Server, starting with address 0
     int[]  readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 10);
     txtGiaTri1.Text = readHoldingRegisters[0].ToString();
     txtGiaTri2.Text = readHoldingRegisters[1].ToString();
     chk1.Checked    = readCoils[0];
     chk2.Checked    = readCoils[1];
     timer1.Enabled  = true;
 }
 private void timer1_Tick(object sender, EventArgs e)
 {
     timer1.Start();
     try
     {
         leer_M  = modbusClient.ReadCoils(0, 100);
         leer_MW = modbusClient.ReadHoldingRegisters(0, 100);
     }
     catch
     {
     }
 }
 private void BtnConnectIO_Click(object sender, RoutedEventArgs e)
 {
     if (Lb_Connection_Status.Content.ToString() != "Connected!")
     {
         try
         {
             modbusClient = new ModbusClient(Paras.Modbus_Server_IP.Value, int.Parse(Paras.Modbus_Server_Port.Value));
             modbusClient.LogFileFilename = Paras.Modbus_Server_LogFileFilename.Value;
             modbusClient.Connect();
             //modbusClient.ConnectionTimeout = 5000;
             Lb_Connection_Status.Content = "Connected!";
             Connect_flag = true;
             // Read all Coils and update to check boxs
             bool[]     _ReadCoils  = modbusClient.ReadCoils(0, 8);
             CheckBox[] _CheckBoxes = { Cb_DO_00, Cb_DO_01, Cb_DO_02, Cb_DO_03, Cb_DO_04, Cb_DO_05, Cb_DO_06, Cb_DO_07 };
             int        _index      = 0;
             foreach (CheckBox _checkBox in _CheckBoxes)
             {
                 _checkBox.IsChecked = _ReadCoils[_index];
                 _index++;
             }
         }
         catch (Exception)
         {
             Lb_Connection_Status.Content = "Fail to Connect!";
         }
     }
 }
Exemple #5
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Start();
            try
            {
                //bool[]
                readcoils = modbusClient.ReadCoils(0, 100);
                //int[]
                readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 100);

                if (readcoils [ENPROCESO] == false && readcoils [CALENTAMIENTO] == false && readcoils [ESTERELIZACION] == false && readcoils[COMPLETADO] == false)
                {
                    pictureBox1.Image = Image.FromFile(@"grisText.bmp");
                    _estado           = "apagado";
                }
                if (readcoils[ENPROCESO] == true && listo < 1)
                {
                    this.iniciarCaptura();
                    listo++;
                }
                if (readcoils[PARADAEMERGENCIA] == true)
                {
                    this.detenerLectura();
                }
            }
            catch
            {
            }
        }
Exemple #6
0
        static void Main(string[] args)
        {
            ModbusClient modbusClient = new ModbusClient("10.128.1.27", 502);

            modbusClient.Connect();

            bool[] readCoils            = modbusClient.ReadCoils(196, 1);            // Coil 400197
            int[]  readHoldingRegisters = modbusClient.ReadHoldingRegisters(196, 1); // Address 400197

            for (int i = 0; i < readCoils.Length; i++)
            {
                Console.WriteLine("Value of Coil " + readCoils[i].ToString());
            }

            for (int i = 0; i < readHoldingRegisters.Length; i++)
            {
                Console.WriteLine("Value for HoldingRegister " + readHoldingRegisters[i].ToString());
            }

            // TODO: Logic will go here

            Console.Write("Press any key to continue ...");
            Console.ReadKey(true);

            Console.ReadKey(true);
        }
Exemple #7
0
 public void ReadCoils()
 {
     try
     {
         if (modbusTCP.Connected)
         {
             bool[] readCoil;
             txtRead.Text = "";
             int StartAddress = 0;     //Int32.Parse(txtReadAddress.Text);
             int Quantity     = 74;    //Int32.Parse(txtQuantity.Text);
             readCoil = modbusTCP.ReadCoils(StartAddress, Quantity);
             for (int i = 0; i < readCoil.Length; i++)
             {
                 txtRead.Text += readCoil[i].ToString() + "\r\n";
             }
             fill_HMI(readCoil);
             LabelStrip001.Text = "Leitura sem erros";
         }
         else
         {
             LabelStrip001.Text = " O sistema não está conectado ao PLC. ";
         }
     }
     catch
     {
         LabelStrip001.Text = "Leitura não foi possível POS 05";
     }
 }
Exemple #8
0
        private void UpdateInput()
        {
            //int id = 1;
            byte lenght = 0x00;

            if (_inputs != null)
            {
                try
                {
                    lenght = Convert.ToByte(_inputs.Count);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    return;
                }

                lock (_lockObject)
                {
                    try
                    {
                        //MbMaster.ReadCoils(id, 0, lenght);
                        bool[] values = _mbClient.ReadCoils(0, lenght);
                        UpdateEthernetInputValue(values);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
Exemple #9
0
        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();
        }
Exemple #10
0
        public void ReadCoil()
        {
            try
            {
                Console.WriteLine("Please Enter the Starting Adderess of Read Coils");
                string readCoil = Console.ReadLine();
                int    coil     = Convert.ToInt32(readCoil);

                bool[] readCoils = modbusClient.ReadCoils(coil, 10);
                if (readCoils != null)
                {
                    for (int i = 0; i < readCoils.Length; i++)
                    {
                        Console.WriteLine((coil) + ":" + "<" + readCoils[i] + ">");
                        coil++;
                    }
                }
                modbusClient.Disconnect();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.ResetColor();
                Console.ReadLine();
            }
        }
Exemple #11
0
        int?getData(DataType type, ModbusClient modbus, int adres)
        {
            int?dön = null;

            try
            {
                switch (type)
                {
                case DataType.Bool:
                    dön = Convert.ToInt32(modbus.ReadCoils(adres, 1).FirstOrDefault());
                    break;

                case DataType.Word:
                    dön = modbus.ReadHoldingRegisters(adres, 1).FirstOrDefault();
                    break;

                case DataType.DoubleWord:
                    dön = ModbusClient.ConvertRegistersToInt(modbus.ReadHoldingRegisters(adres, 2));
                    break;

                case DataType.RaporBiti:
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(dön);
        }
Exemple #12
0
        public List <PLCDataDomain> GetData(List <PLCDataDomain> listAddresses)
        {
            foreach (var item in listAddresses)
            {
                try
                {
                    switch (item.TypePLC)
                    {
                    case PLCDataType.Register:
                        item.Data = modbusClient.ReadHoldingRegisters(item.Address, 1).FirstOrDefault().ToString();
                        break;

                    case PLCDataType.Coils:
                        item.Data = modbusClient.ReadCoils(item.Address, 1).FirstOrDefault().ToString();
                        break;

                    default:
                        item.Data = "None data";
                        break;
                    }
                }
                catch (Exception)
                {
                    item.Data = "None data";
                }
            }

            return(listAddresses);
        }
Exemple #13
0
        static void Main(string[] args)
        {
            ModbusClient modBusClient = new ModbusClient("127.0.0.1", 502);

            modBusClient.Connect();
            bool[] readCoils             = modBusClient.ReadCoils(0, 10);
            int[]  readInputRegisters    = modBusClient.ReadInputRegisters(0, 10);
            int[]  readsHoldingRegisters = modBusClient.ReadHoldingRegisters(0, 10);
            bool[] readDiscreteInputs    = modBusClient.ReadDiscreteInputs(0, 10);
            int[]  ar = new int[5];
            ar[0] = 1;
            ar[1] = 2;
            ar[2] = 3;
            int[] readMultipleRegisters = modBusClient.ReadWriteMultipleRegisters(0, 10, 0, ar);

            for (int i = 0; i < readCoils.Length; i++)
            {
                Console.WriteLine("Value of Coil :" + (9 + i + 1) + " " + readCoils[i].ToString());
            }

            for (int i = 0; i < readsHoldingRegisters.Length; i++)
            {
                Console.WriteLine("Value of HoldingRegister :" + (9 + i + 1) + " " + readsHoldingRegisters[i].ToString());
            }

            Console.Read();
        }
Exemple #14
0
        //private void CoilOdczyt(int st, int licz, ref ListBox listB1)
        //private void CoilOdczyt()
        //{
        //    start = Int32.Parse(addBox1.Text);
        //    licznik = Int32.Parse(addBox2.Text);

        //    if (listBox1.InvokeRequired)
        //    {
        //        var d = new SafeCallDelegate(CoilOdczyt);
        //        listBox1.Invoke(d, new object[] {  });
        //    }
        //    else
        //    {
        //        listBox1.DataSource = modbusClient.ReadCoils(start, licznik);
        //    }
        //    Thread.Sleep(1000);

        //    //listB1.DataSource = modbusClient.ReadCoils(st, licz);
        //    //Thread.Sleep(1000);

        //}

        private void CoilOdczyt(object obj)
        {
            CancellationToken token = (CancellationToken)obj;

            start   = Int32.Parse(addBox1.Text);
            licznik = Int32.Parse(addBox2.Text);
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }
                else
                {
                    //listBox1.DataSource = modbusClient.ReadCoils(start, licznik);
                    if (listBox1.InvokeRequired)
                    {
                        var d = new SafeCallDelegate(CoilOdczyt);
                        listBox1.Invoke(d, new object[] { obj });
                    }
                    else
                    {
                        listBox1.DataSource = modbusClient.ReadCoils(start, licznik);
                    }
                    Thread.Sleep(1000);
                }
            }
        }
Exemple #15
0
        private void updateModbus()
        {
            try
            {
                int[]  registers  = modbusClient.ReadHoldingRegisters(0, 4);
                int[]  inputs     = modbusClient.ReadInputRegisters(0, 5);
                bool[] coilStatus = modbusClient.ReadCoils(0, 5);

                double pressure         = ((float)inputs[0] - 100) / 100.0;
                double tank_lvl         = inputs[1] / 10.0;
                double flow_rate        = inputs[4];
                double return_flow_rate = inputs[2];
                double tank_flow_rate   = inputs[3];
                int    mode             = registers[3];
                pump_state            = coilStatus[0];
                relief_valve_state    = coilStatus[4];
                isolation_valve_state = coilStatus[2];
                return_valve_state    = coilStatus[3];
                inlet_valve_state     = coilStatus[1];

                station_pressure.Text    = "Value: " + pressure.ToString() + " bar";
                station_flow.Text        = "Rate: " + flow_rate.ToString() + " KL/h";
                station_return_flow.Text = "Rate: " + return_flow_rate.ToString() + " KL/h";
                station_tank_flow.Text   = "Rate: " + tank_flow_rate.ToString() + " KL/h";
                station_tank_lvl.Text    = tank_lvl.ToString() + " KL";

                isolation_valve.Image = (isolation_valve_state == true) ? Image.FromFile("./sprites/valve_on.png") : Image.FromFile("./sprites/valve_off.png");
                station_pump.Image    = (pump_state == true) ? Image.FromFile("./sprites/pump_on.png") : Image.FromFile("./sprites/pump_off.png");
                relief_valve.Image    = (relief_valve_state == true) ? Image.FromFile("./sprites/valve_on_90.png") : Image.FromFile("./sprites/valve_off_90.png");
                inlet_valve.Image     = (inlet_valve_state == true) ? Image.FromFile("./sprites/valve_on_90.png") : Image.FromFile("./sprites/valve_off_90.png");
                return_valve.Image    = (return_valve_state == true) ? Image.FromFile("./sprites/valve_on.png") : Image.FromFile("./sprites/valve_off.png");

                isolation_valve_btn.BackColor = (stations_data.stationVariables[4].man_isolation_valve_state == 1) ? Color.LimeGreen : Color.Gainsboro;
                pump_btn.BackColor            = (stations_data.stationVariables[4].man_pump_state == 1) ? Color.LimeGreen : Color.Gainsboro;
                relief_valve_btn.BackColor    = (stations_data.stationVariables[4].man_valve_state == 1) ? Color.LimeGreen : Color.Gainsboro;
                return_valve_btn.BackColor    = (stations_data.stationVariables[4].man_return_valve_state == 1) ? Color.LimeGreen : Color.Gainsboro;
                inlet_valve_btn.BackColor     = (stations_data.stationVariables[4].man_inlet_valve_state == 1) ? Color.LimeGreen : Color.Gainsboro;
            }

            catch
            {
                isolation_valve.Image = Image.FromFile("./sprites/valve_offline.png");
                station_pump.Image    = Image.FromFile("./sprites/pump_offline.png");
                relief_valve.Image    = Image.FromFile("./sprites/valve_offline_90.png");
                inlet_valve.Image     = Image.FromFile("./sprites/valve_offline_90.png");
                return_valve.Image    = Image.FromFile("./sprites/valve_offline.png");

                station_pressure.Text    = "Value: - ";
                station_flow.Text        = "Rate: - ";
                station_return_flow.Text = "Rate: - ";
                station_tank_flow.Text   = "Rate: - ";
                station_tank_lvl.Text    = " - ";

                isolation_valve_btn.Enabled = false;
                pump_btn.Enabled            = false;
                relief_valve_btn.Enabled    = false;
                return_valve_btn.Enabled    = false;
                inlet_valve_btn.Enabled     = false;
            }
        }
Exemple #16
0
        public async Task ClientReadCoilsTest()
        {
            // Function Code 0x01

            byte[] expectedRequest  = new byte[] { 0, 0, 0, 6, 12, 1, 0, 20, 0, 10 };
            var    expectedResponse = new List <Coil>
            {
                new Coil {
                    Address = 20, BoolValue = true
                },
                new Coil {
                    Address = 21, BoolValue = false
                },
                new Coil {
                    Address = 22, BoolValue = true
                },
                new Coil {
                    Address = 23, BoolValue = true
                },
                new Coil {
                    Address = 24, BoolValue = false
                },
                new Coil {
                    Address = 25, BoolValue = false
                },
                new Coil {
                    Address = 26, BoolValue = true
                },
                new Coil {
                    Address = 27, BoolValue = true
                },
                new Coil {
                    Address = 28, BoolValue = true
                },
                new Coil {
                    Address = 29, BoolValue = false
                },
            };

            using var server = new MiniTestServer
                  {
                      RequestHandler = (request, clientIp) =>
                      {
                          CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect");
                          Console.WriteLine("Server sending response");
                          return(new byte[] { request[0], request[1], 0, 0, 0, 5, 12, 1, 2, 205, 1 });
                      }
                  };
            server.Start();

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

            Assert.IsTrue(client.IsConnected);

            var coils = await client.ReadCoils(12, 20, 10);

            Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
            CollectionAssert.AreEqual(expectedResponse, coils, "Response is incorrect");
        }
Exemple #17
0
        public async Task ClientReadExceptionTest()
        {
            byte[] expectedRequest          = new byte[] { 0, 0, 0, 6, 2, 1, 0, 24, 0, 2 };
            string expectedExceptionMessage = ErrorCode.GatewayTargetDevice.GetDescription();

            using var server = new MiniTestServer
                  {
                      RequestHandler = (request, clientIp) =>
                      {
                          CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect");
                          Console.WriteLine("Server sending error response");
                          return(new byte[] { request[0], request[1], 0, 0, 0, 3, 2, 129, 11 });
                      }
                  };
            server.Start();

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

            Assert.IsTrue(client.IsConnected);

            try
            {
                var response = await client.ReadCoils(2, 24, 2);

                Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
                Assert.Fail("Exception not thrown");
            }
            catch (ModbusException ex)
            {
                Assert.AreEqual(expectedExceptionMessage, ex.Message);
            }
        }
Exemple #18
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();
        }
        public static bool[] LayDuLieuTCPCoils(ModbusClient modbus, ushort quantityCoils, ushort minAddressCoils, ThietBiModel thietBiModel)
        {
            List <bool> readCoil = new List <bool>();

            if (quantityCoils != 0)
            {
                try
                {
                    int soNguyenSauChia = quantityCoils / DonViQuantityMoiLanDoc;
                    for (int i = 0; i <= soNguyenSauChia; i++)
                    {
                        if (i != soNguyenSauChia)
                        {
                            int startAddress = i * DonViQuantityMoiLanDoc + minAddressCoils;
                            int quantity     = DonViQuantityMoiLanDoc - minAddressCoils;
                            var temp         = modbus.ReadCoils(startAddress, (ushort)(quantity));
                            readCoil.AddRange(temp.ToList());
                        }
                        else if (i == soNguyenSauChia)
                        {
                            int startAddress = i * DonViQuantityMoiLanDoc + minAddressCoils;
                            int quantity     = quantityCoils % DonViQuantityMoiLanDoc - minAddressCoils;
                            if (quantity != 0)
                            {
                                var temp = modbus.ReadCoils(startAddress, (ushort)(quantity));
                                readCoil.AddRange(temp.ToList());
                            }
                        }
                    }
                }
                catch (ModbusException ex)
                {
                    ExceptionFunctionCode(ex, thietBiModel);
                    throw;
                }
                catch (Exception ex)//Lỗi lấy dữ liệu thất bại
                {
                    ExceptionErrorConnection(ex, thietBiModel);
                    throw;
                }
            }
            return(readCoil.ToArray());
        }
Exemple #20
0
        static async Task ReadCoilsAndLog(ModbusClient client, int start, int end)
        {
            var coils = await client.ReadCoils((ushort)start, (ushort)end);

            var index = start;

            foreach (var coil in coils)
            {
                var onOrOff = coil ? "on" : "off";
                Console.WriteLine($"Coil {index++} is {onOrOff}");
            }
        }
        private void tmr_Modbus_Com_Tick(object sender, EventArgs e)
        {
            tmr_Modbus_Com.Enabled = false;
            readCoils = modbusClient.ReadCoils(0, 4);           //Read 4 Coils from Server, starting with address 1
            tmr_Modbus_Com.Enabled = true;

            if (readCoils[0] == true)
            {
                bt_Lamp1.BackColor = Color.Green;
                bt_Lamp1.Text      = "ON";
            }
            else
            {
                bt_Lamp1.BackColor = Color.Red;
                bt_Lamp1.Text      = "OFF";
            }

            if (readCoils[1] == true)
            {
                bt_Lamp2.BackColor = Color.Green;
                bt_Lamp2.Text      = "ON";
            }
            else
            {
                bt_Lamp2.BackColor = Color.Red;
                bt_Lamp2.Text      = "OFF";
            }

            if (readCoils[2] == true)
            {
                bt_Lamp3.BackColor = Color.Green;
                bt_Lamp3.Text      = "ON";
            }
            else
            {
                bt_Lamp3.BackColor = Color.Red;
                bt_Lamp3.Text      = "OFF";
            }

            if (readCoils[3] == true)
            {
                bt_Lamp4.BackColor = Color.Green;
                bt_Lamp4.Text      = "ON";
            }
            else
            {
                bt_Lamp4.BackColor = Color.Red;
                bt_Lamp4.Text      = "OFF";
            }
        }
        public void lerDados(int tipo)
        {
            int startadd, quant;
            string[] dados = new string[1];

            try
            {
                if (modbus.Connected)
                {
                    if (int.TryParse(tb_endi.Text, out startadd) && int.TryParse(tb_quantidade.Text, out quant)
                    {
                        tb_dados.Text = "";

                        switch (tipo)
                        {
                            case 1:
                                bool[] dadosCo = modbus.ReadCoils(startadd, quant);
                                dados = dadosCo.Select(x => x.ToString()).ToArray();
                                break;
                            case 2:
                                bool[] dadosDI = modbus.ReadDiscreteInputs(startadd, quant);
                                dados = dadosDI.Select(x => x.ToString()).ToArray();
                                break;
                            case 3:
                                int[] dadosHR = modbus.ReadHoldingRegisters(startadd, quant);
                                dados = dadosHR.Select(x => x.ToString()).ToArray();
                                break;
                            case 4:
                                int[] dadosIR = modbus.ReadInputRegisters(startadd, quant);
                                dados = dadosIR.Select(x => x.ToString()).ToArray();
                                break;
                        }

                        for (int i = 0; i < dados.Length; i++)
                        {
                            tb_dados.Text += "Dado " + i.ToString() + ": " + dados[i].ToString() + "\r\n";
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Servidor MODBUS TCP Desconectado");
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("Erro na leitura dos dados MODBUS. \r\nErro: " + err.Message);
            }
        }
            public void Tick(ModbusClient c)
            {
                gas_v     = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(0, 2), ModbusClient.RegisterOrder.HighLow);
                pump      = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(2, 2), ModbusClient.RegisterOrder.HighLow);
                steam_v   = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(4, 2), ModbusClient.RegisterOrder.HighLow);
                water_lvl = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(6, 2), ModbusClient.RegisterOrder.HighLow);
                pressure  = ModbusClient.ConvertRegistersToFloat(c.ReadHoldingRegisters(8, 2), ModbusClient.RegisterOrder.HighLow);
                torch     = c.ReadCoils(5, 1)[0];

                alrm = c.ReadHoldingRegisters(10, 1)[0];

                if (alrm == 0)
                {
                    water_lvl += 0.02f * pump;
                    if (torch)
                    {
                        water_lvl -= 0.01f * gas_v;
                        pressure  += 0.01f * gas_v;
                    }
                    pressure -= 0.03f * steam_v;

                    if (water_lvl < 0)
                    {
                        water_lvl = 0;
                        alrm      = 3;
                    }
                    if (water_lvl > 1)
                    {
                        water_lvl = 1;
                        alrm      = 4;
                    }
                    if (pressure < 0.3f)
                    {
                        pressure = 0.3f;
                    }
                    if (pressure > 0.95f)
                    {
                        alrm = 1;
                    }
                    if (pressure > 1)
                    {
                        alrm = 2;
                    }

                    c.WriteMultipleRegisters(6, ModbusClient.ConvertFloatToRegisters(water_lvl, ModbusClient.RegisterOrder.HighLow));
                    c.WriteMultipleRegisters(8, ModbusClient.ConvertFloatToRegisters(pressure, ModbusClient.RegisterOrder.HighLow));
                    c.WriteSingleRegister(10, alrm);
                }
            }
Exemple #24
0
        private void tmr_Modbus_Com_Tick(object sender, EventArgs e)
        {
            tmr_Modbus_Com.Enabled = false;

            modbusClient.WriteMultipleCoils(4, new bool[] { true, true, true, true, true, true, true, true, true, true }); //Write Coils starting with Address 5
            bool[] readCoils            = modbusClient.ReadCoils(0, 10);                                                   //Read 10 Coils from Server, starting with address 0
            int[]  readHoldingRegisters = modbusClient.ReadHoldingRegisters(0, 10);                                        //Read 10 Holding Registers from Server, starting with Address 1

            aGauge1.Value = readHoldingRegisters[0];

            cb_coil_1.Checked = readCoils[0];
            cb_coil_2.Checked = readCoils[1];


            tmr_Modbus_Com.Enabled = true;
        }
Exemple #25
0
        private string ReadDataFromSlave(int FunctionCode, int startingAddress)
        {
            try     // 데이터 Gathering 시도
            {
                switch (FunctionCode)
                {
                case 0:
                    return(modbusClient.ReadCoils(startingAddress, 1)[0].ToString());    // FC 1 00000-100000 시작번지 부터 지정한 개수 읽기

                case 1:
                    return(modbusClient.ReadDiscreteInputs(startingAddress, 1)[0].ToString());     // FC 2 100001-200000

                case 2:
                    return(modbusClient.ReadHoldingRegisters(startingAddress, 1)[0].ToString());       // FC 3 400001-500000

                case 3:
                    return(modbusClient.ReadInputRegisters(startingAddress, 1)[0].ToString()); // FC 4 300000-400000

                default:                                                                       // 이외의 값이 들어올 때 처리
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
            #region 예외처리 보관함

            /*catch (ModbusException) // 모드버스 예외 발생 시
             * {
             *  i--;        // 예외 발생한 부분 다시 반복
             * }
             * catch (TimeoutException)    // 타임 아웃 에러 시
             * {
             *  i--;        // 예외 발생한 부분 다시 반복
             * }
             * catch (StackOverflowException)  // 데이터 과다복용 사망 시
             * {
             *  i--;
             * }
             * catch (NullReferenceException)
             * {
             *  readData[i] = "Null 붙잡을 노래";
             * }
             */
            #endregion
        }
Exemple #26
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                //Client tanımlama
                ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502);
                //
                //Bağlan
                tcpclient.Connect();
                //
                //okuma
                //

                int a = Convert.ToInt32(textBox2.Text);
                int b = Convert.ToInt32(textBox3.Text);
                int c = Convert.ToInt32(textBox4.Text);
                int d = Convert.ToInt32(textBox5.Text);

                //
                //okuma
                //
                bool[] mb = tcpclient.ReadCoils(a - 1, 1);
                int [] mw = tcpclient.ReadHoldingRegisters((b - 1), 1);
                int[]  mi = tcpclient.ReadHoldingRegisters((c - 1), 2);
                int[]  mf = tcpclient.ReadHoldingRegisters((d - 1), 2);
                //
                double mii = ModbusClient.ConvertRegistersToDouble(mi);
                //
                float mff = ModbusClient.ConvertRegistersToFloat(mf);



                //
                //labela yazma
                //
                label7.Text  = Convert.ToString(mb[0]);
                label8.Text  = Convert.ToString(mw[0]);
                label12.Text = Convert.ToString(mii);
                label13.Text = Convert.ToString(mff);
            }
            //
            //hata yakalama
            catch (Exception)
            { timer1.Stop(); MessageBox.Show("Hata"); }
        }
Exemple #27
0
        // read %Q
        public bool[] ReadQ(int startingAddress, int quantity)
        {
            bool[] val = new bool[quantity];
            try
            {
                ModbusClient client = new ModbusClient(IPAddress, Port);

                client.Connect();
                val = client.ReadCoils(startingAddress, quantity);
                client.Disconnect();
            }
            catch
            {
            }


            return(val);
        }
Exemple #28
0
        private void button1_Click(object sender, EventArgs e)
        {
            EasyModbus.ModbusClient sdast  = new ModbusClient();
            ModbusClient            modbus = new ModbusClient()
            {
                SerialPort     = "COM4",
                Baudrate       = 9600,
                Parity         = System.IO.Ports.Parity.None,
                StopBits       = System.IO.Ports.StopBits.One,
                UnitIdentifier = 1
            };

            modbus.Connect();
            Stopwatch sw = new Stopwatch();

            Task.Factory.StartNew(() =>
            {
                while (modbus.Connected)
                {
                    sw.Start();
                    //coils = modbus.ReadCoils(1, 1);
                    Gelenler = modbus.ReadHoldingRegisters(0, 70);
                    //var sad = modbus.ReadCoils(0, 100);
                    if (Coils.Count == 0)
                    {
                        int index = 0;
                        modbus.ReadCoils(0, 256).ToList().ForEach(x =>
                        {
                            Coils.Add(index.ToString("{M}-000") + "=>" + string.Format("{0:TRUE;0;FALSE}", x.GetHashCode()));
                            index++;
                        });
                    }


                    this.InvokeIfRequired(() =>
                    {
                        label1.Text         = string.Join("\n", Gelenler);
                        listBox1.DataSource = Coils;
                    });
                }
            });
        }
Exemple #29
0
 void BtnReadCoilsClick(object sender, EventArgs e)
 {
     try
     {
         if (!modbusClient.Connected)
         {
             button3_Click(null, null);
         }
         bool[] serverResponse = modbusClient.ReadCoils(int.Parse(txtStartingAddressInput.Text) - 1, int.Parse(txtNumberOfValuesInput.Text));
         lsbAnswerFromServer.Items.Clear();
         for (int i = 0; i < serverResponse.Length; i++)
         {
             lsbAnswerFromServer.Items.Add(serverResponse[i]);
         }
     }
     catch (Exception exc)
     {
         MessageBox.Show(exc.Message, "Exception Reading values from Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        private void bReadOp_Click(object sender, RoutedEventArgs e)
        {
            //读取输出线圈信号
            bool[] OutputStatus = modbusClient.ReadCoils(8, 3);
            // MessageBox.Show(OutputStatus[0].ToString());
            ///
            if (OutputStatus[0] == true)
            {
                label3_Copy9.Background = new SolidColorBrush(Colors.Green);
                label3_Copy9.Content    = OutputStatus[0].ToString();
            }
            else
            {
                label3_Copy9.Background = new SolidColorBrush(Colors.Red);
                label3_Copy9.Content    = OutputStatus[0].ToString();
            }

            ///
            if (OutputStatus[1] == true)
            {
                label3_Copy10.Background = new SolidColorBrush(Colors.Green);
                label3_Copy10.Content    = OutputStatus[1].ToString();
            }
            else
            {
                label3_Copy10.Background = new SolidColorBrush(Colors.Red);
                label3_Copy10.Content    = OutputStatus[1].ToString();
            }

            ///
            if (OutputStatus[2] == true)
            {
                label3_Copy11.Background = new SolidColorBrush(Colors.Green);
                label3_Copy11.Content    = OutputStatus[2].ToString();
            }
            else
            {
                label3_Copy11.Background = new SolidColorBrush(Colors.Red);
                label3_Copy11.Content    = OutputStatus[2].ToString();
            }
        }