public void Write(int val)
 {
     try
     {
         if (!TestOnly)
         {
             _ModBusClient.WriteSingleRegister(SMART_ADDRESS, val);
         }
     }
     catch { }
 }
Exemple #2
0
 private void start_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     try
     {
         backgroundWorkerRead.CancelAsync();
         Thread.Sleep(100);
         modbusClient.WriteSingleRegister(24, 1);
         if (!backgroundWorkerRead.IsBusy)
         {
             backgroundWorkerRead.RunWorkerAsync();
         }
     }
     catch { }
 }
 private void btn_confTm1_Click(object sender, EventArgs e)
 {
     try {
         confTime1 = txt_tm1.Text;
         SetTime1  = Int32.Parse(confTime1);
         modbusClient.WriteSingleRegister(0, SetTime1);
         txt_tm1.Clear();
     }
     catch
     {
         MessageBox.Show("No se pudo enviar", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
         MessageBox.Show("Asegurese de introducir solo numeros enteros", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
         txt_tm1.Clear();
     }
 }
Exemple #4
0
        public async Task ClientWriteSingleRegisterTest()
        {
            // Function Code 0x06

            byte[] expectedRequest = new byte[] { 0, 0, 0, 6, 2, 6, 0, 5, 48, 57 };

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

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

            Assert.IsTrue(client.IsConnected);

            var register = new Register
            {
                Type          = ModbusObjectType.HoldingRegister,
                Address       = 5,
                RegisterValue = 12345
            };
            bool success = await client.WriteSingleRegister(2, register);

            Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
            Assert.IsTrue(success);
        }
        private void writeSingleData()
        {
            try
            {
                int value = Convert.ToInt32(kp.Text.ToString());
                if (value > 247 || value < 0)
                {
                    myMessageQueue.Enqueue(rm.GetString("valueRange247Exceeded"), rm.GetString("ok"), () => HandleOKMethod());
                    return;
                }

                backgroundWorker.CancelAsync();
                Thread.Sleep(100);
                modbusClient.WriteSingleRegister(18, value);
                if (!backgroundWorker.IsBusy)
                {
                    backgroundWorker.RunWorkerAsync();
                }

                VarsTension.client.UnitIdentifier        = Convert.ToByte(value);
                Properties.Settings.Default.tensionSlave = value;
                Properties.Settings.Default.Save();
                MessageBox.Show(rm.GetString("writingSuccessful", cultureInfo), rm.GetString("system", cultureInfo),
                                MessageBoxButton.OK, MessageBoxImage.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, rm.GetString("system", cultureInfo), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #6
0
        private void writeSingleData()
        {
            try
            {
                int value = Convert.ToInt32(kp.Text.ToString());
                if (value > 250 || value < 1)
                {
                    myMessageQueue.Enqueue(rm.GetString("valueRange250Exceeded"), rm.GetString("ok"), () => HandleOKMethod());
                    return;
                }

                backgroundWorker.CancelAsync();
                Thread.Sleep(100);
                modbusClient.WriteSingleRegister(28, value);
                if (!backgroundWorker.IsBusy)
                {
                    backgroundWorker.RunWorkerAsync();
                }

                MessageBox.Show(rm.GetString("writingSuccessful", cultureInfo), rm.GetString("system", cultureInfo),
                                MessageBoxButton.OK, MessageBoxImage.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, rm.GetString("system", cultureInfo), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #7
0
 private void save_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         backgroundWorker.CancelAsync();
         Thread.Sleep(100);
         modbusClient.WriteSingleRegister(19, send);
         VarsTension.client.Disconnect();
         VarsTension.client.Baudrate = value;
         VarsTension.client.Connect();
         if (!backgroundWorker.IsBusy)
         {
             backgroundWorker.RunWorkerAsync();
         }
         Properties.Settings.Default.tensionBaudRate = value;
         Properties.Settings.Default.Save();
         MessageBox.Show(rm.GetString("writingSuccessful", cultureInfo), rm.GetString("system", cultureInfo),
                         MessageBoxButton.OK, MessageBoxImage.Information);
         this.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, rm.GetString("system", cultureInfo), MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Exemple #8
0
        public void SetData(PLCDataDomain pLCData)
        {
            switch (pLCData.TypePLC)
            {
            case PLCDataType.Register:
                try
                {
                    modbusClient.WriteSingleRegister(pLCData.Address, int.Parse(pLCData.Data));
                }
                catch (Exception)
                {
                    break;
                }
                break;

            case PLCDataType.Coils:
                try
                {
                    modbusClient.WriteSingleCoil(pLCData.Address, bool.Parse(pLCData.Data));
                }
                catch (Exception)
                {
                    break;
                }
                break;

            default:
                break;
            }
        }
Exemple #9
0
        public override void Execute(ModbusClient modbusClient)
        {
            ModbusWriteCommandParameters mdb_write_comm_pars = this.CommandParameters as ModbusWriteCommandParameters;

            //TODO: Check does current scada model has the requested address, maybe let anyway
            modbusClient.WriteSingleRegister(mdb_write_comm_pars.OutputAddress - 1, mdb_write_comm_pars.Value);
            Logger.LogInfo($"WriteSingleRegisterFunction executed SUCCESSFULLY. OutputAddress: {mdb_write_comm_pars.OutputAddress}, Value: {mdb_write_comm_pars.Value}");
        }
Exemple #10
0
 private void buttonParametr_Click(object sender, EventArgs e)
 {
     try
     {
         if (modbusClient == null || modbusClient.Connected == false)
         {
             connectSKU(IpAdress.Text, Convert.ToInt32(Port.Text));
             textBoxNumberBrigada.Text = RegisterValueConvertToInt(modbusClient, 28).ToString();//Id текущей бригады 27 регистр
             if (RegisterValueConvertToInt(modbusClient, 8) == 1)
             {
                 radioButton2.Checked = true;
             }
             else if (RegisterValueConvertToInt(modbusClient, 8) == 0)
             {
                 radioButton1.Checked = true;
             }
             LabelTimeNow.Text = getDateTimeFromDevice();//время и дата(число секунд прошедших с 1.1.2013 0х420,0х421)
             if (!SubscribeToTimerEvent)
             {
                 TimeSubscribe();
             }
             textBoxPorogLog.Text = RegisterValueConvertToFloat(modbusClient, 58).ToString(); //Порог логирования
             textBoxPorogK2.Text  = RegisterValueConvertToFloat(modbusClient, 54).ToString(); //Порог K1 оповщатель
             textBoxPorogK1.Text  = RegisterValueConvertToFloat(modbusClient, 56).ToString(); //Порог K2 отс клапан
             textBoxImpVP.Text    = RegisterValueConvertToInt(modbusClient, 59).ToString();   //Импульс на оборот ВП
             textBoxImpNP.Text    = RegisterValueConvertToInt(modbusClient, 99).ToString();   //Импульс на оборот НП
             LabelTimeNow.Visible = true;
         }
         modbusClient.WriteSingleRegister(55, ModbusClient.ConvertFloatToRegisters(Convert.ToSingle(textBoxPorogK1.Text))[1]);
         modbusClient.WriteSingleRegister(53, ModbusClient.ConvertFloatToRegisters(Convert.ToSingle(textBoxPorogK2.Text))[1]);
         modbusClient.WriteSingleRegister(57, ModbusClient.ConvertFloatToRegisters(Convert.ToSingle(textBoxPorogLog.Text))[1]);
         modbusClient.WriteSingleRegister(27, Convert.ToInt32(textBoxNumberBrigada.Text));
         modbusClient.WriteSingleRegister(58, Convert.ToInt32(textBoxImpVP.Text));
         modbusClient.WriteSingleRegister(98, Convert.ToInt32(textBoxImpNP.Text));
         if (radioButton2.Checked == true)
         {
             modbusClient.WriteSingleRegister(7, Convert.ToInt32("1"));
         }
         else if (radioButton1.Checked == true)
         {
             modbusClient.WriteSingleRegister(7, Convert.ToInt32("0"));
         }
         modbusClient.ConnectionTimeout = 1;
     }
     catch (Exception ex)
     {
         if (ex.Message == "connection timed out")
         {
             MessageBox.Show("Подключение не установленно. Время ожидания подключения истекло");
         }
         else
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
 private void button1_Click(object sender, EventArgs e)
 {
     //  modbusClient.WriteMultipleCoils(4, new bool[] { true, false, true, true, true, true, true, true, true, true });    //Write 10 Coils starting with Address 5, ghi nhiều ô coil 1 lần
     //   modbusClient.WriteSingleCoil(20, true); // ghi 1 ô coil 1 lần
     //   modbusClient.WriteMultipleRegisters(0, new int[] { 1, 2, 3, 4, 5, 6 }); //ghi nhiều ô register 1 lần
     modbusClient.WriteSingleRegister(Decimal.ToInt32(nudRegNoW.Value), Decimal.ToInt32(nudRegValue.Value));
     modbusClient.WriteSingleCoil(Decimal.ToInt32(nudCoilNoW.Value), chkCoilValue.Checked);
 }
Exemple #12
0
 public void write_number(int register, int val)
 {
     if (connectionEstablished == true)
     {
         //print(register + " " + val);
         modbusClient.WriteSingleRegister(register, val);
     }
 }
    private void AddClientMethod()
    {
        var client = new ModbusClient("127.0.0.1", port);

        client.Connect();
        clients.Add(client);
        MessageBox.Show("Client added.");
        client.WriteSingleRegister(register++, 11);     // event is fired
    }
Exemple #14
0
 private void WriteRegister(int address, int value)
 {
     if (ConnectToSlave(tb_IPAddress.Text))
     {
         address = address - 1;
         modbusClient.WriteSingleRegister(address, value);
         modbusClient.Disconnect();
     }
 }
 private void save_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         modbusClient.WriteSingleRegister(5, send);
         MessageBox.Show("Adrese yazıldı");
         this.Close();
     }
     catch (Exception ex) { MessageBox.Show(ex.Message); }
 }
Exemple #16
0
        private void button4_Click(object sender, EventArgs e)
        {
            //mw yazma butonu
            ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502);

            tcpclient.Connect();
            int bb = Convert.ToInt32(textBox11.Text);

            tcpclient.WriteSingleRegister(bb - 1, Convert.ToInt32(textBox7.Text));
        }
        private void BtnUstawProbkowanieTemperatury_Click(object sender, RoutedEventArgs e)
        {
            ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502);    //Ip-Address and Port of Modbus-TCP-Server

            modbusClient.Connect();
            int ProbkowanieTemperatury = int.Parse(txtProbkowanieTemperatury.Text);

            //int[] aaa = ModbusClient.ConvertIntToRegisters(CzasPomiaru_N1);
            modbusClient.WriteSingleRegister(4505, ProbkowanieTemperatury);
            modbusClient.Disconnect();
        }
 public void WriteSingleRegister(byte slaveAddress, int startAddress, int numberOfPoints)
 {
     Log.Debug("GET ReadCoils: SlaveAddress {0}, StartAddress {1}, NumberOfPoints {2}", slaveAddress, startAddress, numberOfPoints);
     try
     {
         _master.WriteSingleRegister(startAddress, numberOfPoints);
         Log.Debug("RESPONSE WriteSingleRegister: NO ERROR");
     }
     catch (Exception ex)
     {
         Log.Error(ex, "ERROR: WriteSingleRegister: SlaveAddress {0}, StartAddress {1}, NumberOfPoints {2} - MSG: {3}", slaveAddress, startAddress, numberOfPoints, ex.Message);
         // throw ex;
     }
 }
            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);
                }
            }
 private void save_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         modbusClient.WriteSingleRegister(19, send);
         Vars.client.Disconnect();
         Vars.client.Baudrate = value;
         Vars.client.Connect();
         Properties.Settings.Default.tensionBaudRate = value;
         Properties.Settings.Default.Save();
         MessageBox.Show("Adrese yazıldı");
         this.Close();
     }
     catch (Exception ex) { MessageBox.Show(ex.Message); }
 }
Exemple #21
0
 private void writeSingleData()
 {
     try
     {
         int value = Convert.ToInt32(kp.Text.ToString());
         if (value > 100 || value < 0)
         {
             myMessageQueue.Enqueue("0 - 100 arası bir değer giriniz", "OK", () => HandleOKMethod());
             return;
         }
         modbusClient.WriteSingleRegister(13, value);
         MessageBox.Show("Yazıldı");
         this.Close();
     }
     catch (Exception ex) { MessageBox.Show(ex.Message); }
 }
Exemple #22
0
 private void writeSingleData()
 {
     try
     {
         int value = Convert.ToInt32(kp.Text.ToString());
         if (value > 247 || value < 0)
         {
             myMessageQueue.Enqueue("0 - 247 arası bir değer giriniz", "OK", () => HandleOKMethod());
             return;
         }
         modbusClient.WriteSingleRegister(18, value);
         Vars.client.UnitIdentifier = Convert.ToByte(value);
         Properties.Settings.Default.tensionSlave = value;
         Properties.Settings.Default.Save();
         MessageBox.Show("Yazıldı");
         this.Close();
     }
     catch (Exception ex) { MessageBox.Show(ex.Message); }
 }
Exemple #23
0
 private void save_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         backgroundWorker.CancelAsync();
         Thread.Sleep(100);
         modbusClient.WriteSingleRegister(23, send);
         if (!backgroundWorker.IsBusy)
         {
             backgroundWorker.RunWorkerAsync();
         }
         MessageBox.Show(rm.GetString("writingSuccessful", cultureInfo), rm.GetString("system", cultureInfo),
                         MessageBoxButton.OK, MessageBoxImage.Information);
         this.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, rm.GetString("system", cultureInfo), MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Exemple #24
0
        private void btnWriteSingleRegister_Click(object sender, EventArgs e)
        {
            try
            {
                if (!modbusClient.Connected)
                {
                    button3_Click(null, null);
                }

                int registerToSend = 0;

                registerToSend = int.Parse(lsbWriteToServer.Items[0].ToString());


                modbusClient.WriteSingleRegister(int.Parse(txtStartingAddressOutput.Text) - 1, registerToSend);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Exception writing values to Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #25
0
 private void writeSingleData()
 {
     try
     {
         int value = Convert.ToInt32(kp.Text.ToString());
         backgroundWorker.CancelAsync();
         Thread.Sleep(100);
         modbusClient.WriteSingleRegister(27, value);
         if (!backgroundWorker.IsBusy)
         {
             backgroundWorker.RunWorkerAsync();
         }
         MessageBox.Show(rm.GetString("writingSuccessful", cultureInfo), rm.GetString("system", cultureInfo),
                         MessageBoxButton.OK, MessageBoxImage.Information);
         this.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, rm.GetString("system", cultureInfo), MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Exemple #26
0
        private void button_changedata_Click(object sender, EventArgs e)
        {
            int Address = Convert.ToInt32(startingAddress.Text);

            a = new string[dataGridView1.RowCount];

            if (RadioHolding.Checked == true)
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    modbusClient.WriteSingleRegister((Address - 40001), Convert.ToInt32(dataGridView1[1, i].Value.ToString())); //holdeng
                    Address++;
                }
            }
            if (RadioInput.Checked == true)
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    Address++;
                }
            }
        }
Exemple #27
0
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (ligadot)
            {
                if (modbusClient == null)
                {
                    return;
                }

                try
                {
                    //le a temperatura e mostra no supervisório  tratar tensão de o a 10
                    int temperatura = modbusClient.ReadInputRegisters(128, 1)[0];
                    temperatura     = (temperatura / 1000) + 20;
                    trackBar4.Value = temperatura;
                    string temp = temperatura.ToString();
                    label19.Text = temp;

                    //le a tensão e mostra no supervisório tratar de 1 a 5
                    int    tensao = modbusClient.ReadHoldingRegisters(3128, 1)[0]; // recebe valor de 400 a 2000 (1 a 5)
                    double tensa  = (tensao - 400) * 0.137;
                    string tens   = tensa.ToString();
                    label31.Text = tens;

                    // pega a vazão do arduino e envia para o CLP
                    //transforma o valor de vazao para o CLP
                    float vaz = vazao * 1000;
                    int   val = (int)vaz;
                    modbusClient.WriteSingleRegister(10020, val);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Erro na escrita de dados no CLP!");
                }
            }
        }
Exemple #28
0
        static async Task RunClientAsync()
        {
            //InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            ModbusClient client = new ModbusClient(0x01, "127.0.0.1");

            try
            {
                await client.Connect();

                while (true)
                {
                    Console.WriteLine(@"
<------------------------------------------------------->
1: Read Coils; 2: Read Discrete Inputs; 
3: Read Holding Registers; 4: Read Input Registers; 
5: Write Single Coil; 6: Write Single Register; 
15: Write Multiple Coils; 16: Write Multiple Registers;
<------------------------------------------------------->");
                    var line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        break;
                    }

                    Console.WriteLine("<------------------------------------------------------->");
                    var command = Convert.ToInt32(line);

                    ModbusFunction response        = null;
                    ushort         startingAddress = 0x0000;
                    ushort         quantity        = 0x000A;
                    var            state           = true;
                    ushort         value           = 0x0001;

                    switch (command)
                    {
                    case 1:
                        response = client.ReadCoils(startingAddress, quantity);
                        var coils = (response as ReadCoilsResponse).Coils;
                        for (int i = 0; i < quantity; i++)
                        {
                            Console.WriteLine(coils[i]);
                        }
                        break;

                    case 2:
                        response = client.ReadDiscreteInputs(startingAddress, quantity);
                        var inputs = (response as ReadDiscreteInputsResponse).Inputs;
                        for (int i = 0; i < quantity; i++)
                        {
                            Console.WriteLine(inputs[i]);
                        }
                        break;

                    case 3:
                        response = client.ReadHoldingRegisters(startingAddress, quantity);
                        foreach (var register in (response as ReadHoldingRegistersResponse).Registers)
                        {
                            Console.WriteLine(register);
                        }
                        break;

                    case 4:
                        response = client.ReadInputRegisters(startingAddress, quantity);
                        foreach (var register in (response as ReadInputRegistersResponse).Registers)
                        {
                            Console.WriteLine(register);
                        }
                        break;

                    case 5:
                        response = client.WriteSingleCoil(startingAddress, state);
                        Console.WriteLine((response as WriteSingleCoilResponse).State == state ? "Successed" : "Failed");
                        break;

                    case 6:
                        response = client.WriteSingleRegister(startingAddress, value);
                        Console.WriteLine((response as WriteSingleRegisterResponse).Value == value ? "Successed" : "Failed");
                        break;

                    case 15:
                        var states = new bool[] { true, true, true, true, true, true, true, true, true, true };
                        response = client.WriteMultipleCoils(startingAddress, states);
                        Console.WriteLine((response as WriteMultipleCoilsResponse).Quantity == states.Length);
                        break;

                    case 16:
                        var registers = new ushort[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
                        response = client.WriteMultipleRegisters(startingAddress, registers);
                        Console.WriteLine((response as WriteMultipleRegistersResponse).Quantity == registers.Length);
                        break;
                    }
                }

                await client.Close();

                Console.ReadLine();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
 private void dispatch_valve_btn_Click(object sender, EventArgs e)
 {
     stations_data.stationVariables[0].man_isolation_valve_state = (stations_data.stationVariables[0].man_isolation_valve_state == 1) ? 0 : 1;
     modbusClient.WriteSingleRegister(6, stations_data.stationVariables[0].man_isolation_valve_state);
 }
Exemple #30
0
 private void start_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     modbusClient.WriteSingleRegister(24, 1);
 }