protected override void OnDoubleClick(EventArgs e)
        {
            try
            {
                if (String.Compare(this.Text, "0") == 0)
                {
                    this.Text      = "1";
                    this.BackColor = Color.DeepSkyBlue;
                    Value          = true;
                    modbusClient.WriteSingleCoil(Adress, Value);
                }
                else if (String.Compare(this.Text, "1") == 0)
                {
                    this.Text      = "0";
                    this.BackColor = Color.DimGray;
                    Value          = false;
                    modbusClient.WriteSingleCoil(Adress, Value);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bağlı değilsiniz!");
            }

            base.OnDoubleClick(e);
        }
예제 #2
0
        /// <summary>
        /// 启动指示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_Click(object sender, EventArgs e)
        {
            try
            {
                ModbusClient modbusClient = Common.ModbusConnect();
                if (modbusClient != null)
                {
                    int start = 2056;  //启动对应Q10--2056

                    if (this.led_Start.GridentColor == Color.Green)
                    {
                        modbusClient.WriteSingleCoil(start, false);
                    }
                    else
                    {
                        modbusClient.WriteSingleCoil(start, true);
                    }
                    //关闭连接
                    modbusClient.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #3
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));
            }
        }
예제 #4
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                //DialogResult dg = MessageBox.Show(" Close the Application", "Conformatiom", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                //if (dg == DialogResult.OK)
                {
                    plcmodule.WriteSingleCoil(1283, false);
                    plcmodule.WriteSingleCoil(1284, false);
                    //capture.Release();
                    FileStorage fs = new FileStorage("count.yml", FileStorage.Modes.Write);
                    fs.Write("imagecount", imagecount);
                    fs.Write("sno", sno);
                    fs.Write("Thread Passcount", Thread_Passcount);
                    fs.Write("Thread Failcount", Thread_Failcount);
                    fs.Write("Hole Passcount", Hole_Passcount);
                    fs.Write("Hole Failcount", Hole_Failcount);
                    fs.Write("Total Passcount", Total_passcount);
                    fs.Write("Total Failcount", Total_failcount);
                    fs.Write("TotalCount", total_count);

                    e.Cancel = false;
                }
                //else if (dg == DialogResult.Cancel)
                //{
                //    e.Cancel = true;
                //}
            }
            catch (Exception Ex)
            {
                //MessageBox.Show(Ex.Message.ToString());
                log.Error("Error Message: " + Ex.Message.ToString(), Ex);
            }
        }
예제 #5
0
        private void btnWriteSingle_Click(object sender, EventArgs e)
        {
            bool WriteValue;

            if (modbusTCP.Connected == true)
            {
                try
                {
                    if (checkTrueWrite.Checked)
                    {
                        WriteValue = true;
                    }
                    else
                    {
                        WriteValue = false;
                    }

                    int WriteSingleAddress = Int32.Parse(txtWriteSingleAddress.Text);
                    modbusTCP.WriteSingleCoil(WriteSingleAddress, WriteValue);
                }
                catch
                {
                    ;
                }
            }
            else
            {
                ;
            }
        }
예제 #6
0
        public override void Reset()
        {
            base.Reset();

            try
            {
                //lock (this)
                //{
                _waitDataRecived.Reset();
                System.Threading.Thread.Sleep(500);
                _modbusClient.WriteSingleCoil(IAIConstAddr.PMSL, true);
                WaitDataReceived(ReadTimeOut);

                _waitDataRecived.Reset();
                _modbusClient.WriteSingleCoil(IAIConstAddr.ALRS, true);
                WaitDataReceived(ReadTimeOut);


                _waitDataRecived.Reset();
                _modbusClient.WriteSingleCoil(IAIConstAddr.ALRS, false);
                WaitDataReceived(ReadTimeOut);

                OnUpdateCurrentPositions();
                //}
            }
            catch (Exception ex)
            {
                //U.LogAlarmPopup(ex, "Reset Command Fail '{0}'", this.Nickname);
                throw new MCoreExceptionPopup(ex, "Reset Command Fail '{0}'", this.Nickname);
            }
        }
예제 #7
0
        public async Task ClientWriteSingleCoilTest()
        {
            // Function Code 0x05

            byte[] expectedRequest = new byte[] { 0, 0, 0, 6, 1, 5, 0, 173, 255, 0 };

            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 coil = new Coil
            {
                Address   = 173,
                BoolValue = true
            };
            bool success = await client.WriteSingleCoil(1, coil);

            Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
            Assert.IsTrue(success);
        }
예제 #8
0
        public override void Execute(ModbusClient modbusClient)
        {
            ModbusWriteCommandParameters mdb_write_comm_pars = this.CommandParameters as ModbusWriteCommandParameters;
            ushort outputAddress = mdb_write_comm_pars.OutputAddress;
            int    value         = mdb_write_comm_pars.Value;

            if (outputAddress >= ushort.MaxValue || outputAddress == ushort.MinValue)
            {
                string message = $"Address is out of bound. Output address: {outputAddress}.";
                Logger.LogError(message);
                throw new Exception(message);
            }

            bool commandingValue;

            if (value == 0)
            {
                commandingValue = false;
            }
            else if (value == 1)
            {
                commandingValue = true;
            }
            else
            {
                throw new ArgumentException("Non-boolean value in write single coil command parameter.");
            }


            //TODO: Check does current scada model has the requested address, maybe let anyway
            modbusClient.WriteSingleCoil(outputAddress - 1, commandingValue);
            Logger.LogInfo($"WriteSingleCoilFunction executed SUCCESSFULLY. OutputAddress: {outputAddress}, Value: {commandingValue}");
        }
예제 #9
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;
            }
        }
예제 #10
0
 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);
 }
예제 #11
0
        private void btnStartPomiaru(object sender, RoutedEventArgs e)
        {
            ModbusClient modbusClient = new ModbusClient("192.168.1.101", 502);    //Ip-Address and Port of Modbus-TCP-Server

            modbusClient.Connect();
            modbusClient.WriteSingleCoil(2267, true);
            modbusClient.Disconnect();
        }
예제 #12
0
 public void write(int register, bool val)
 {
     if (connectionEstablished == true)
     {
         if (!mode || register > 13 || register == 8)
         {
             modbusClient.WriteSingleCoil(register, val);
         }
     }
 }
예제 #13
0
        private void button8_Click(object sender, EventArgs e) //botao liga controle de temp
        {
            if (modbusClient == null)
            {
                return;
            }

            try
            {
                //liga o clp e o supervisorio do clp (coloca o bool em uma memória)
                ligadot = true;
                modbusClient.WriteSingleCoil(7005, true);
                modbusClient.WriteSingleCoil(7006, false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erro na escrita de dados no CLP!");
            }
        }
예제 #14
0
        private void btn_Underdraught_Click(object sender, EventArgs e)
        {
            ModbusClient modbusClient = Common.ModbusConnect();

            if (modbusClient != null)
            {
                int start = 2055;  //探针下压对应Q07--2055

                if (this.led_Underdraught.GridentColor == Color.Green)
                {
                    modbusClient.WriteSingleCoil(start, false);
                }
                else
                {
                    modbusClient.WriteSingleCoil(start, true);
                }
                //关闭连接
                modbusClient.Disconnect();
            }
        }
예제 #15
0
        /// <summary>
        /// 停止指示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            ModbusClient modbusClient = Common.ModbusConnect();

            if (modbusClient != null)
            {
                int start = 2056;  //停止指示对应Q10--2056 false

                if (this.led_Stop.GridentColor == Color.Green)
                {
                    modbusClient.WriteSingleCoil(start, false);
                }
                else
                {
                    modbusClient.WriteSingleCoil(start, true);
                }
                //关闭连接
                modbusClient.Disconnect();
            }
        }
 private void WriteToPLC(int address, bool writeValue)
 {
     try
     {
         modbusClient.WriteSingleCoil(address - 1, writeValue);
     }
     catch (Exception exc)
     {
         MessageBox.Show(exc.Message, "Exception writing values to PLC", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
예제 #17
0
        private void btn_Motor_Reverse_Click(object sender, EventArgs e)
        {
            ModbusClient modbusClient = Common.ModbusConnect();

            if (modbusClient != null)
            {
                int start = 2054;  //启动指示对应Q06--2054

                if (this.led_Motor_Reverse.GridentColor == Color.Green)
                {
                    modbusClient.WriteSingleCoil(start, false);
                }
                else
                {
                    modbusClient.WriteSingleCoil(start, true);
                }
                //关闭连接
                modbusClient.Disconnect();
            }
        }
예제 #18
0
        /// <summary>
        /// 流水线启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Assembly_Line_Start_Click(object sender, EventArgs e)
        {
            ModbusClient modbusClient = Common.ModbusConnect();

            if (modbusClient != null)
            {
                int start = 2056;  //流水线启动信号对应Q10--2056

                if (this.led_Motor_Positive.GridentColor == Color.Green)
                {
                    modbusClient.WriteSingleCoil(start, false);
                }
                else
                {
                    modbusClient.WriteSingleCoil(start, true);
                }
                //关闭连接
                modbusClient.Disconnect();
            }
        }
예제 #19
0
        ///// <summary>
        ///// Set the boolean outputs
        ///// </summary>
        ///// <param name="boolOutput"></param>
        ///// <param name="value"></param>
        //public override void Set(BoolOutput boolOutput, bool value)
        //{

        //    int id = 5;
        //    int bitAddress = boolOutput.Channel;
        //    lock (_lockObject)
        //    {
        //        if (MbMaster != null)
        //        {
        //            MbMaster.WriteSingleCoils(id, bitAddress, value);
        //        }
        //    }

        //}


        /// <summary>
        /// Set the boolean outputs
        /// </summary>
        /// <param name="boolOutput"></param>
        /// <param name="value"></param>
        public override void Set(BoolOutput boolOutput, bool value)
        {
            int bitAddress = boolOutput.Channel;

            lock (_lockObject)
            {
                if (_mbClient != null)
                {
                    _mbClient.WriteSingleCoil(bitAddress, value);
                }
            }
        }
예제 #20
0
 private void bt_Lamp1_Click(object sender, EventArgs e)
 {
     if (connection_status == true)
     {
         if (readCoils[0] == true)
         {
             modbusClient.WriteSingleCoil(0, false);
         }
         else
         {
             modbusClient.WriteSingleCoil(0, true);
         }
     }
 }
예제 #21
0
 /// <summary>
 /// 阻挡气缸动作
 /// </summary>
 /// <param name="inOrOut"></param>
 public static void StopCylinderAction(bool inOrOut)
 {
     try
     {
         ModbusClient modbusClient = ModbusConnect();
         if (modbusClient != null)
         {
             int start = 2053;  //阻挡气缸对应Q05--2053
             modbusClient.WriteSingleCoil(start, inOrOut);
             //关闭连接
             modbusClient.Disconnect();
         }
     }
     catch (Exception)
     {
     }
 }
예제 #22
0
        /// <summary>
        /// 流水线送板动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void AssemblyLineSendAction(bool inOrOut)
        {
            try
            {
                ModbusClient modbusClient = ModbusConnect();
                if (modbusClient != null)
                {
                    int start = 2058;  //流水线送板信号对应Q12--2058

                    modbusClient.WriteSingleCoil(start, inOrOut);
                    //关闭连接
                    modbusClient.Disconnect();
                }
            }
            catch (Exception)
            {
            }
        }
예제 #23
0
        private void button1_Click(object sender, EventArgs e)
        {
            istemci.Connect();
            istemci.WriteSingleCoil(0, true);
            //istemci.WriteSingleRegister(0, Convert.ToInt32(textBox1.Text));
            int[] a = new int[5];
etiket:
            a = istemci.ReadHoldingRegisters(0, 1);
            if (a[0] == 5)
            {
                goto etiket2;
            }
            goto etiket;
etiket2:
            textBox1.Text = a[0].ToString();
            istemci.ReceiveDataChanged += İstemci_ReceiveDataChanged;
            istemci.Disconnect();
        }
예제 #24
0
 // Write single coil and check connection
 private void WriteSingleCoilValue(int address, bool value)
 {
     try
     {
         modbusClient.WriteSingleCoil(address, value);
     }
     //catch (EasyModbus.Exceptions.ConnectionException ex)
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         MessageBox.Show("Erro de conexão com a placa Modbus", "Erro de conexão", MessageBoxButtons.OK, MessageBoxIcon.Error);
         modbusClient.Disconnect();
         groupBox1.Enabled = false;
         groupBox2.Enabled = false;
         btConnect.Checked = false;
         textBox1.Enabled  = true;
     }
 }
예제 #25
0
        /// <summary>
        /// 流水线动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Assembly_Line_Start(bool startOrStop)
        {
            try
            {
                ModbusClient modbusClient = ModbusConnect();
                if (modbusClient != null)
                {
                    int start = 2056;  //流水线启动信号对应Q10--2056

                    modbusClient.WriteSingleCoil(start, startOrStop);
                    //关闭连接
                    modbusClient.Disconnect();
                }
            }
            catch (Exception)
            {
            }
        }
예제 #26
0
        /// <summary>
        /// 浸泡气缸动作
        /// </summary>
        /// <param name="inOrOut"></param>
        public static void SoakCylinderAction(bool inOrOut)
        {
            try
            {
                ModbusClient modbusClient = ModbusConnect();
                if (modbusClient != null)
                {
                    int start = 2050;  //浸泡气缸Q02--2050

                    modbusClient.WriteSingleCoil(start, inOrOut);
                    //关闭连接
                    modbusClient.Disconnect();
                }
            }
            catch (Exception)
            {
            }
        }
예제 #27
0
        private void btnWriteSingleCoil_Click(object sender, EventArgs e)
        {
            try
            {
                if (!modbusClient.Connected)
                {
                    button3_Click(null, null);
                }

                bool coilsToSend = false;

                coilsToSend = bool.Parse(lsbWriteToServer.Items[0].ToString());


                modbusClient.WriteSingleCoil(int.Parse(txtStartingAddressOutput.Text) - 1, coilsToSend);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Exception writing values to Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #28
0
        private void button3_Click(object sender, EventArgs e)
        {
            //mb yazma butonu
            ModbusClient tcpclient = new ModbusClient(Convert.ToString(textBox1.Text), 502);

            tcpclient.Connect();
            bool bitvalue = false;

            //
            if (comboBox1.Text == "True")
            {
                bitvalue = true;
            }
            if (comboBox1.Text == "False")
            {
                bitvalue = false;
            }
            //
            int aa = Convert.ToInt32(textBox10.Text);

            tcpclient.WriteSingleCoil((aa - 1), bitvalue);
        }
        private void Dt_ModbusTicker(object sender, EventArgs e)
        {
            try// ---read Input
            {
                bool[] DI_Tray_Present_Sensor = modbusClient.ReadDiscreteInputs(int.Parse(Paras.DI_Tray_Present_Sensor.Value), 1);
                Cb_DI_Tray_Present_Sensor.IsChecked = DI_Tray_Present_Sensor[0];

                if (DI_Tray_Present_Sensor[0])
                {
                    if (Threshold_Counter <= float.Parse(Paras.Threshold_Trigger.Value))
                    {
                        Threshold_Counter++;
                        //Capture_Flag = true;
                    }
                }
                else
                {
                    Threshold_Counter    = 0;
                    Cb_Trigger.IsChecked = false;
                }
                Lb_Trigger.Content = Threshold_Counter.ToString();
            }
            catch
            {
                MessageBox.Show("Error104: Fail to read Digital Input");
                StateMachine_NotInit();
                Dt_Modbus.Stop();
            }

            // ---Write Digital Output
            try
            {
                modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Red_Light.Value), Convert.ToBoolean(Cb_DO_Red_Light.IsChecked));
                //modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Amber_Light.Value), Convert.ToBoolean(//Cb_DO_Amber_Light.IsChecked));
                modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Green_Light.Value), Convert.ToBoolean(Cb_DO_Green_Light.IsChecked));
                modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Buzzer.Value), Convert.ToBoolean(Cb_DO_Buzzer.IsChecked));
                modbusClient.WriteSingleCoil(int.Parse(Paras.DO_Disable_Tray_Loading.Value), Convert.ToBoolean(Cb_DO_Disable_Tray_Loading.IsChecked));
            }
            catch
            {
                MessageBox.Show("Error105: Fail to write Digital Output");
                StateMachine_NotInit();
                Dt_Modbus.Stop();
            }
        }
예제 #30
0
        public void RefreshSimulator()
        {
            List <ScadaBreaker> breakers = new List <ScadaBreaker>();

            using (var context = new ScadaDB.ScadaContext())
            {
                breakers = context.Breakers.Where(x => !x.IsDeleted).ToList();
            }


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

            //modbusClient.UnitIdentifier = 1; Not necessary since default slaveID = 1;
            //modbusClient.Baudrate = 9600;	// Not necessary since default baudrate = 9600
            //modbusClient.Parity = System.IO.Ports.Parity.None;
            // modbusClient.StopBits = System.IO.Ports.StopBits.Two;
            //modbusClient.Port = 502;
            modbusClient.Connect();

            foreach (var breaker in breakers)
            {
                modbusClient.WriteSingleCoil(breaker.SimulatorAddress, breaker.Value);
            }
        }