Exemplo n.º 1
0
        private void btn_read_Click(object sender, EventArgs e)
        {
            try
            {
                if (_plc == null)
                {
                    lbMsg.Text = "请先连接";
                    return;
                }

                if (string.IsNullOrEmpty(cb_addr.Text))
                {
                    lbMsg.Text = "请输入地址";
                    return;
                }

                lbMsg.Text = "读取中";

                List <DataItem> dataItems = new List <DataItem>();
                var             item      = DataItem.FromAddress(cb_addr.Text);
                dataItems.Add(item);
                _plc.Open();
                _plc.ReadMultipleVars(dataItems);
                _plc.Close();
                var result = dataItems.First().Value.ToString();

                lbMsg.Text = result;
            }
            catch (PlcException ex)
            {
                lbMsg.Text = ex.Message;
            }
        }
Exemplo n.º 2
0
    public ErrorCode PLCComStatus()
    {
        var code = plc.Open();

        plc.Close();
        return(code);
    }
Exemplo n.º 3
0
 private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
 {
     try
     {
         if (plc != null)
         {
             plc.Close();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Exemplo n.º 4
0
        public void TimerCallback(Object o)
        {
            // Display the date/time when this method got called.
            using (var plc = new Plc(CpuType.S71500, "192.168.1.222", 0, 1))
            {
                plc.Open();
                //Write
                WriteTask(plc);
                ReadTask(plc);
                read_datablock DB1_mem = (read_datablock)plc.ReadStruct(typeof(read_datablock), 1, 0);
                read_datablock DB2_mem = (read_datablock)plc.ReadStruct(typeof(read_datablock), 2, 0);
                read_datablock DB3_mem = (read_datablock)plc.ReadStruct(typeof(read_datablock), 3, 0);
                short          second  = (short)((((Int32)(DB1_mem.PT / 1000)) % 3600) % 60);
                short          ms      = (short)(DB1_mem.PT % 1000);
                Console.WriteLine("Frame Data From Plc with IP address   " + plc.IP + ": Frame" + ixx);
                //Update PLC to Readblock
                updatePLC2ReadBlock(DB1_mem, DB2_mem, DB3_mem);
                //Console.WriteLine
                ushort glo = (ushort)plc.Read("MW103");
                //bool st =(bool)plc.R("M101.4");
                //bool sp=(bool)plc.Read("M101.5");
                Console.WriteLine("DB1 mode :" + DB1_mem.mode);
                Console.WriteLine("DB2 mode :" + DB2_mem.mode);
                Console.WriteLine("DB3 mode: " + DB3_mem.mode);
                Console.WriteLine("level: " + level_bar.level);
                Console.WriteLine("glo: " + glo);
                Console.WriteLine("DATA HAD BEEN UPDATED " + "\n\n");
                Console.WriteLine("-------------------------------------------------------------- ");

                //Update Readblock to Writeblock
                updateReadWrite();
                ixx = ixx + 1;
                plc.Close();
            }
        }
 private void timerTick(object sender, EventArgs e)
 {
     {
         Plc plc = new Plc(CpuType.S71500, "192.168.0.202", 0, 1);
         if (plc.IsAvailable)
         {
             plc.Open();
             if (plc.IsConnected)
             {
                 Byte[] buffer2 = new Byte[18];
                 for (int i = 112; i < 2380; i += 126)
                 {
                     buffer2 = plc.ReadBytes(DataType.DataBlock, 9000, i, 1);
                     BackColorTM.Add(buffer2[0]);
                     buffer2[0] = 0;
                 }
             }
             else
             {
                 Console.WriteLine("Connection not alive");
             }
             plc.Close();
         }
         else
         {
             Console.WriteLine("PLC not available");
         }
     }
 }
Exemplo n.º 6
0
        public bool?ReadPowerOn()
        {
            bool?bit = null;

            if (!_lock)
            {
                _lock = true;
                using (var S7Plc = new Plc(CpuType.S7300, IP, 0, 2))
                {
                    try
                    {
                        S7Plc.Open();
                        bit = Convert.ToBoolean(S7Plc.Read(DataType.DataBlock, PcPowerOnDB, 0, VarType.Bit, 1));
                        log.Debug($"real bit read from {IP} cell {PcPowerOnDB}: {bit}");
                        S7Plc.Close();
                    }
                    catch (Exception e)
                    {
                        log.Error($"reading power on bit on {IP}", e);
                    }
                }
                _lock = false;
            }
            else
            {
                log.Debug($"skip bit read from {IP}");
            }
            return(bit);
        }
Exemplo n.º 7
0
        public override void Read(Plc _plc)
        {
            if (this.ReadHandler != null)
            {
                ReadEventArgs e = new ReadEventArgs();
                e.ReadID    = ID;
                e.StartTime = System.DateTime.Now;
                try
                {
                    _plc.ReadMultipleVars(Items.Values.ToList());
                    e.Result = true;
                }
                catch
                {
                    //出现异常断开连接(超时),并休眠1秒
                    _plc.Close();
                    e.Result   = false;
                    e.ErrorMsg = "由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败";
                }

                e.EndTime = System.DateTime.Now;
                e.Data    = new Dictionary <string, object>();
                foreach (var dic in Items)
                {
                    e.Data.Add(dic.Key, dic.Value.Value);
                }

                this.ReadHandler(this, e);
            }
        }
Exemplo n.º 8
0
        public string Close()
        {
            string result = "";

            result = Plc.Close();
            return(result);
        }
Exemplo n.º 9
0
        public override void Read(Plc _plc)
        {
            if (this.ReadHandler != null)
            {
                ReadEventArgs e = new ReadEventArgs();
                e.ReadID    = ID;
                e.StartTime = System.DateTime.Now;
                try
                {
                    foreach (var dic in Items)
                    {
                        var buffer = _plc.ReadBytes(dic.Value.DataType, dic.Value.DB, dic.Value.StartByteAdr, dic.Value.Count);
                        dic.Value.Value = FilterChar(System.Text.Encoding.GetEncoding("GB2312").GetString(buffer).Trim());
                        buffer          = null;
                    }
                    e.Result = true;
                }
                catch (Exception ex)
                {
                    //出现异常断开连接(超时)
                    _plc.Close();
                    e.Result   = false;
                    e.ErrorMsg = ex.Message;
                }
                e.EndTime = System.DateTime.Now;
                e.Data    = new Dictionary <string, object>();
                foreach (var dic in Items)
                {
                    e.Data.Add(dic.Key, dic.Value.Value);
                }

                this.ReadHandler(this, e);
            }
        }
        internal static bool PutBoolean(Plc client, int dbnum, string cycleCompletedLoc, bool val)
        {
            if (client == null)
            {
                Logger.WriteDebugLog("Client is null");
                return(false);
            }

            try
            {
                if (client.IsAvailable)
                {
                    if (!client.IsConnected)
                    {
                        ErrorCode er = client.Open();
                        if (er != ErrorCode.NoError)
                        {
                            Logger.WriteDebugLog("client open error");
                        }
                    }
                    if (client.IsConnected)
                    {
                        ErrorCode er = client.Write(string.Format("DB{0}.DBX{1}", dbnum, cycleCompletedLoc), val);
                        return(er == ErrorCode.NoError);
                    }
                }
            }
            catch (Exception ex)
            {
                client.Close();
                client.Dispose();
            }
            return(false);
        }
Exemplo n.º 11
0
        //ReadBytes it's limited to 200 bytes. Method with recusion
        public static List <byte> ReadMultipleBytes(int numBytes, int db, int startByteAdr)
        {
            Plc         plc         = new Plc(CpuType.S71500, "192.168.0.202", 0, 1);
            List <byte> resultBytes = new List <byte>();
            int         index       = startByteAdr;

            if (plc.IsAvailable)
            {
                plc.Open();
                if (plc.IsConnected)
                {
                    while (numBytes > 0)
                    {
                        var    maxToRead = (int)Math.Min(numBytes, 200);
                        byte[] bytes     = plc.ReadBytes(DataType.DataBlock, db, index, (int)maxToRead);
                        if (bytes == null)
                        {
                            return(resultBytes);
                        }
                        resultBytes.AddRange(bytes);
                        numBytes -= maxToRead;
                        index    += maxToRead;
                    }
                }
                plc.Close();
            }

            return(resultBytes);
        }
Exemplo n.º 12
0
 // Disconnect Plc
 public void DisconnectPlc(Plc plc)
 {
     try
     {
         var _cancelTasks = new CancellationTokenSource();
         var task         = Task.Run(() =>
         {
             if (plc.IsConnected)
             {
                 plc.Close(); // Inchidere conexiune Plc
                 _logger.LogInformation("{data}<=>{Messege} IP: {ip}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), "S-a inchis conexiune cu plc", plc.IP);
             }
             else
             {
                 return;
             }
         }, _cancelTasks.Token);
         if (!task.Wait(TimeSpan.FromSeconds(0.5)))
         {
             _cancelTasks.Cancel();                                        // Daca nu mai raspunde in timp util se opreste Task
         }
     }
     catch (PlcException exPlc)
     {
         _logger.LogError("{data} {exMessege} IP: {ip}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), exPlc.Message, plc.IP);
     }
     catch (OperationCanceledException ex)
     {
         _logger.LogError("{data} {exMessege} IP: {ip}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), ex.Message, plc.IP);
     }
     catch (Exception ex)
     {
         _logger.LogError("{data} {exMessege} IP: {ip}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), ex.Message, plc.IP);
     }
 }
 // Functie deconectare Plc
 public void DeconnectPlc()
 {
     try
     {
         var _cancelTasks = new CancellationTokenSource();
         var performTaskCheckAvailability = Task.Run(() =>
         {
             if (IsConnected)
             {
                 _client.Close(); // Inchidere conexiune Plc
                 if (!_client.IsConnected)
                 {
                     IsConnected = false;                       // Setare IsConected to false
                 }
             }
             else
             {
                 return;
             }
         }, _cancelTasks.Token);
         if (!performTaskCheckAvailability.Wait(TimeSpan.FromSeconds(0.5)))
         {
             _cancelTasks.Cancel();                                                                // Daca nu mai raspundein timp util se opreste Task
         }
     }
     catch (Exception) { }
 }
Exemplo n.º 14
0
        private static void ReadPLC()
        {
            try
            {
                Plc plc = PLCSingleton.CreatePLC(CpuType.S7300, "10.21.189.139", 0, 2);    //new Plc(CpuType.S7300, "10.21.189.139", 0, 2);
                plc.Open();
                UInt32 str = (UInt32)plc.Read(DataType.DataBlock, 181, 0, VarType.DWord, 1);

                Console.WriteLine("Status  " + str.ToString());

                str = (UInt32)plc.Read(DataType.DataBlock, 181, 4, VarType.DWord, 1);
                Console.WriteLine("Operation  " + str.ToString());

                str = (UInt32)plc.Read(DataType.DataBlock, 181, 8, VarType.DWord, 1);
                Console.WriteLine("Program   " + str.ToString());

                str = (UInt32)plc.Read(DataType.DataBlock, 181, 12, VarType.DWord, 1);
                Console.WriteLine("First alarm    " + str.ToString());

                str = (UInt32)plc.Read(DataType.DataBlock, 181, 16, VarType.DWord, 1);
                Console.WriteLine("Current message     " + str.ToString());


                plc.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 15
0
        private static void GetDicPLCData()
        {
            try
            {
                uint         str;
                RowDataPoint point   = null;
                string       openstr = "OK";
                object       readobj = null;
                RowDataPoint eqp     = null;
                foreach (var adapter in DicStatus)
                {
                    point = adapter.Value;
                    if (point != null)
                    {
                        Plc plc = OEMPLC.CreatePLC(CpuType.S7300, adapter.Key, 0, 2);    //new Plc(CpuType.S7300, "10.21.189.139", 0, 2);

                        try
                        {
                            openstr = plc.QMOpen();
                            if (openstr == "OK")
                            {
                                try
                                {
                                    readobj = plc.QMRead((DataType)point.datatype, point.dbNumber, point.startByte, (VarType)point.vartype, 1);
                                    // str = (UInt32)plc.QMRead((DataType)eqp.datatype, eqp.dbNumber, eqp.startByte, (VarType)eqp.vartype, 1);
                                    if (readobj != null)
                                    {
                                        str = Convert.ToUInt16(readobj);
                                        Console.WriteLine("OEM PLC Data " + adapter.Key + "  " + str);
                                        DicReal[adapter.Key] = str;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Error(ex.ToString());
                                }
                            }
                            else
                            {
                                DicReal[adapter.Key] = uint.MaxValue;

                                Log.Error("[PLC][Link Fail] IP Address is : " + eqp.IP);
                                Log.Error(openstr);
                            }
                            //  throw new InvalidAddressException("To few periods for DB address");
                            plc.Close();
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }
Exemplo n.º 16
0
 // Functie Deconectare Plc
 public void DeconectarePlc()
 {
     if (cuptorPLC.IsConnected)
     {
         cuptorPLC.Close();
     }
     MessageBox.Show("S-a inchis polc-ul");
 }
Exemplo n.º 17
0
 private void btnDisconnect_Click(object sender, EventArgs e)
 {
     try
     {
         if (plc != null)
         {
             timer1.Enabled = false;
             plc.Close();
             lblVerbindung.BackColor = Color.Red;
         }
         btnConnect.Enabled = true;
     }
     catch (PlcException ex)
     {
         MessageBox.Show(this, ex.Message, "Verbindung Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 18
0
 public bool DisConnectPLC()
 {
     if (PLCServer != null)
     {
         PLCServer.Close();
     }
     return(true);
 }
Exemplo n.º 19
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (Vipa.IsConnected)
     {
         Vipa.Close();
     }
     toolStripProgressBar1.Value = toolStripProgressBar1.Minimum;
 }
Exemplo n.º 20
0
 public void Disconnect()
 {
     PLC.Close();
     if (!PLC.IsConnected)
     {
         ConnectionSatus = Status.Offline;
     }
 }
Exemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        public void close()
        {
            Plc.Close();

            _logger.LogWarning("This S7 has connect url:{0},rack:{1},slot:{2}",

                               _setting.Url, _setting.Rack, _setting.Slot);
        }
Exemplo n.º 22
0
        protected void btn_lampoff_Click(object sender, EventArgs e)
        {
            btn_lampon.CssClass  = "btn btn-secondary";
            btn_lampoff.CssClass = "btn btn-danger";
            Plc plc = new Plc(CpuType.S71200, "192.168.20.104", 0, 1);

            plc.Open();
            plc.Write("M0.5", 1);
            plc.Write("M0.5", 0);
            plc.Close();
        }
Exemplo n.º 23
0
        private static void ConnectPlc()
        {
            if (Plc.IsConnected)
            {
                Plc.Close();
            }

            try
            {
                Plc.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Plc bağlantısı sağlanamadı. " + ex.Message);
            }

            var args = EventArgs.Empty;

            OnPlcConnectionChanged(args);
        }
Exemplo n.º 24
0
        public void Disconnect()
        {
            if (_client.IsConnected)
            {
                _client.Close();
                ConnectionState = ConnectionStates.Offline;

                LogMessegeRaportareAjustaj.WriteMessegeToLogFile("S-a executat deconectare PLC" + _nume);
                //MessageBox.Show("S-a deconectat PLC" + _nume);
            }
        }
Exemplo n.º 25
0
        protected void btn_alarmin_Click(object sender, EventArgs e)
        {
            btn_alarmin.CssClass  = "btn btn-success";
            btn_alarmout.CssClass = "btn btn-secondary";
            Plc plc = new Plc(CpuType.S71200, "192.168.20.104", 0, 1);

            plc.Open();
            plc.Write("M1.2", 1);
            plc.Write("M1.2", 0);
            plc.Close();
        }
Exemplo n.º 26
0
 public void CloseConnection()
 {
     if (PlcConnection.IsConnected == true)
     {
         PlcConnection.Close();
     }
     else
     {
         MessageBox.Show("NIE MOŻNA ROZŁĄCZYĆ SIĘ ZE STEROWNIKIEM => NIE JESTEŚ POŁĄCZONY");
     }
 }
Exemplo n.º 27
0
        private void ReadM()
        {
            Plc plc = new Plc(CpuType.S7300, "172.29.132.18", 0, 2);

            plc.Open();
            //   float str = (float)plc.Read(DataType.Memory, 0, 622, VarType.Real, 1);
            bool str = (bool)plc.Read(DataType.Output, 8, 3, VarType.Bit, 6);

            //  textBox1.Text = str.ToString();
            plc.Close();
        }
Exemplo n.º 28
0
 public override void Disconnect()
 {
     try {
         if (plc.IsConnected)
         {
             plc.Close();
         }
     }
     catch (Exception) {
     }
 }
        }            /// Zwraca komunikat błędu i łączy się ze sterownikiem

        /*      public void ConnectToPLC(CpuType TypeofCPU, string IP)
         *    {
         *        try
         *        {
         *
         *            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();        // pingowanie wskazanego adresu IP
         *
         *            System.Net.NetworkInformation.PingReply Reply = ping.Send(IP);                             // sprawdzanie odpowiedzi pingu
         *
         *
         *            if (Reply != null)
         *            {
         *                //switch (Reply.Status)
         *                //{
         *                //    case System.Net.NetworkInformation.IPStatus.Success:                               // Jeżeli odpowiedź jest pozytywna przechodzimy do próby połączenia z PLC
         *
         *                        Pelecek = new Plc(TypeofCPU, IP, 0, 0);
         *                        ErrorCode Error = Pelecek.Open();                                            // Łączenie się z adresem IP. Jeżeli pod wskazanym adresem nie ma PLC, wówczas błąd jest zapisywany w zmiennej Error
         *                        bool temp = Convert.ToBoolean(Pelecek.Read("M100.7"));
         *                        temp = !temp;
         *                        int tempint = Convert.ToInt16(temp);                                     // Próba odczytania zmiennej z Memory 100.7, zmiana jej na przeciwną, zapisanie jej w tym samym miejscu
         *                        Pelecek.Write("M100.7", tempint);                                            // Potem następuje jej ponowny odczyt i sprawdzenie poprawności danych odczytanych z wcześniej wysłanymi
         *                        temp = Convert.ToBoolean(Pelecek.Read("M100.7"));
         *                        if (Convert.ToInt16(temp) == tempint)                                    // Jeżeli próba została zakończona pomyślnie, wówczas program gratuluje nam połączenia i wpisuje pierwotny stan Memory 100.7 do PLC
         *                        {
         *
         *                            tempint = Convert.ToInt16(!temp);
         *                            Pelecek.Write("M100.7", tempint);
         *                            Connected = true;
         *                          //  return "Gratulacje! Udało połączyć się ze sterownikiem PLC.";
         *
         *                        }
         *                   //     else
         *                        //    return "Uwaga! Nie udało połączyć się ze sterownikiem! \n Wystąpił błąd:" + Error.ToString();
         *
         *
         *
         *               //     case System.Net.NetworkInformation.IPStatus.TimedOut:                          // Błędy występujące przy pingowaniu : przekroczono limit czasu oraz nieodnaleziono IP
         *                      //  return "Przekroczono czas połączenia.";
         *
         *              //      default:
         *                     //   return "Błąd połączenia";
         *             //   }
         *            }
         *     //       else
         *             //   return "Adres IP nie odpowiada";
         *        }
         *        catch
         *        {
         *         //   return "Adres IP nie odpowiada";
         *        }
         *
         *
         *
         *    }
         */

        public void ClosePLC()
        {
            if (Pelecek != null)
            {
                Pelecek.Close();
            }

            if (Adamek != null)
            {
                Adamek.Disconnect();
            }
        }
        public bool Disconnect()
        {
            if (!IsPlcConnected())
            {
                return(false);
            }

            _dataReadTimer.Stop();
            _s7Plc.Close();

            RaiseIsDisconnected();
            return(true);
        }