Ejemplo n.º 1
0
        private void cmdLoadBlockList_Click(object sender, RoutedEventArgs e)
        {
            myConn.Connect();
            var blks = myConn.PLCListBlocks(PLCBlockType.AllEditableBlocks);

            lstBlocks.ItemsSource = blks;
            myConn.Disconnect();
        }
Ejemplo n.º 2
0
        private void synchronizePLCTimes(object tmp)
        {
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                LibNoDaveConfig plcConnConf = connectionConfig as LibNoDaveConfig;
                if (plcConnConf != null)
                {
                    PLCConnection tmpConn = (PLCConnection)ConnectionList[connectionConfig];

                    if (plcConnConf.SynchronizePLCTime)
                    {
                        try
                        {
                            if (!tmpConn.Connected)
                            {
                                tmpConn.Connect();
                            }

                            tmpConn.PLCSetTime(DateTime.Now);
                            if (!plcConnConf.StayConnected)
                            {
                                tmpConn.Disconnect();
                            }
                        }
                        catch (Exception ex)
                        { }
                    }
                }
            }
        }
        private void synchronizePLCTimes(object tmp)
        {
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                LibNoDaveConfig plcConnConf = connectionConfig as LibNoDaveConfig;
                if (plcConnConf != null)
                {
                    PLCConnection tmpConn = (PLCConnection)ConnectionList[connectionConfig];

                    if (plcConnConf.SynchronizePLCTime)
                    {
                        try
                        {
                            if (!tmpConn.Connected)
                            {
                                Logging.LogTextToLog4Net("synchronizePLCTimes() => \"" + plcConnConf.Name + "\" => Connect...");
                                tmpConn.Connect();
                            }

                            tmpConn.PLCSetTime(DateTime.Now);
                            if (!plcConnConf.StayConnected)
                            {
                                Logging.LogTextToLog4Net("synchronizePLCTimes() => \"" + plcConnConf.Name + "\" Discconnect because !StayConnected");
                                tmpConn.Disconnect();
                            }
                        }
                        catch (Exception ex)
                        { }
                    }
                }
            }
        }
 private void cmdDisconnect_Click(object sender, EventArgs e)
 {
     timer1.Enabled     = false;
     progressBar1.Value = 0;
     myConn.Disconnect();
     cmdConnect.BackColor = cmdDisconnect.BackColor;
 }
Ejemplo n.º 5
0
 private void unwatchToolStripMenuItem_Click(object sender, EventArgs e)
 {
     lblConnected.BackColor = Color.DarkGray;
     if (myConn != null && myConn.Connected)
     {
         myConn.Disconnect();
     }
 }
 public override void Close()
 {
     if (myThread != null)
     {
         myThread.Abort();
     }
     if (_plcConnection != null)
     {
         _plcConnection.Disconnect();
     }
 }
        public bool Disconnect()
        {
            if (!_plcConnection.Connected)
            {
                return(false);
            }

            _dataReadTimer.Stop();
            _plcConnection.Disconnect();

            RaiseIsDisconnected();
            return(true);
        }
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         PLCConnection myConn = new PLCConnection(lstConnections.SelectedItem.ToString());
         myConn.Connect();
         PLCTag plcTag=new PLCTag(){TagDataType = TagDataType.ByteArray, TagDataSource = MemoryArea.Datablock, DataBlockNumber = Convert.ToInt32(txtDB.Text), ByteAddress = Convert.ToInt32(txtStartByte.Text), ArraySize = Convert.ToInt32(txtBytes.Text)};
         myConn.ReadValue(plcTag);
         readBytes = (byte[]) plcTag.Value;
         myConn.Disconnect();
         lblState.Text = readBytes.Length.ToString() + " Bytes gelesen";
         MessageBox.Show("So nun den neuen DB übertragen....");
     }
     catch (Exception ex)
     {
         lblState.Text = ex.Message;
     }
 }
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         PLCConnection myConn = new PLCConnection(lstConnections.SelectedItem.ToString());
         myConn.Connect();
         PLCTag plcTag = new PLCTag()
         {
             TagDataType = TagDataType.ByteArray, TagDataSource = MemoryArea.Datablock, DataBlockNumber = Convert.ToInt32(txtDB.Text), ByteAddress = Convert.ToInt32(txtStartByte.Text), ArraySize = Convert.ToInt32(txtBytes.Text)
         };
         myConn.ReadValue(plcTag);
         readBytes = (byte[])plcTag.Value;
         myConn.Disconnect();
         lblState.Text = readBytes.Length.ToString() + " Bytes gelesen";
         MessageBox.Show("So nun den neuen DB übertragen....");
     }
     catch (Exception ex)
     {
         lblState.Text = ex.Message;
     }
 }
Ejemplo n.º 10
0
        private void EstablishConnections()
        {
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                LibNoDaveConfig plcConnConf   = connectionConfig as LibNoDaveConfig;
                TCPIPConfig     tcpipConnConf = connectionConfig as TCPIPConfig;
                DatabaseConfig  dbConnConf    = connectionConfig as DatabaseConfig;


                if (plcConnConf != null)
                {
                    Logging.LogText("Connection: " + connectionConfig.Name + " is starting...", Logging.LogLevel.Information);

                    PLCConnection tmpConn = new PLCConnection(plcConnConf.Configuration);
                    try
                    {
                        tmpConn.Connect();
                        if (!plcConnConf.StayConnected)
                        {
                            tmpConn.Disconnect();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.LogText("Connection: " + connectionConfig.Name, ex, Logging.LogLevel.Warning);
                    }

                    ConnectionList.Add(connectionConfig, tmpConn);
                }
                else if (dbConnConf != null)
                {
                    var tmpConn = new DatabaseConnection(dbConnConf);
                    try
                    {
                        tmpConn.Connect();
                    }
                    catch (Exception ex)
                    {
                        Logging.LogText("Connection: " + connectionConfig.Name, ex, Logging.LogLevel.Warning);
                    }
                    ConnectionList.Add(connectionConfig, tmpConn);
                }
                else if (tcpipConnConf != null)
                {
                    //todo: legth of tcp conn
                    //TCPFunctionsAsync tmpConn = new TCPFunctionsAsync(new SynchronizationContext(), tcpipConnConf.IPasIPAddres, tcpipConnConf.Port, !tcpipConnConf.PassiveConnection, 0);

                    //tmpConn.Connect();

                    //ConnectionList.Add(connectionConfig, tmpConn);
                }
            }

            myReEstablishConnectionsThreads = new List <Thread>();
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                if (connectionConfig is LibNoDaveConfig)
                {
                    var thrd = new Thread(new ParameterizedThreadStart(ReEstablishConnectionsThreadProc))
                    {
                        Name = "EstablishConnectionsThreadProc"
                    };
                    thrd.Start(connectionConfig as LibNoDaveConfig);
                    this.myReEstablishConnectionsThreads.Add(thrd);
                }
            }
        }
Ejemplo n.º 11
0
        public static IEnumerable <object> ReadDataFromDataSources(DatasetConfig datasetConfig, IEnumerable <DatasetConfigRow> datasetConfigRows, Dictionary <ConnectionConfig, Object> activConnections, bool StartedAsService)
        {
            var usedConnections = from n in datasetConfigRows
                                  group n by n.Connection into g       //Es wird in das Object g hineingruppiert.
                                  select new { Connection = g.Key };   //n.Connection ist dann g.Key, g ist eine ganze Zeile

            foreach (var usedConnection in usedConnections)
            {
                var tags = from n in datasetConfigRows
                           where n.Connection == usedConnection.Connection
                           select n.PLCTag;
                if (usedConnection.Connection.GetType() == typeof(DatabaseConfig))
                {
                    //Read Data from a Database
                    var dbConn = (DatabaseConnection)activConnections[usedConnection.Connection];

                    var dta = dbConn.ReadData();

                    try
                    {
                        foreach (var plcTag in tags)
                        {
                            plcTag.Value = dta[plcTag.ValueName];
                        }
                    }
                    finally
                    {
                        dta.Close();
                    }
                }
                else if (usedConnection.Connection.GetType() == typeof(LibNoDaveConfig))
                {
                    PLCConnection plcConn = (PLCConnection)activConnections[usedConnection.Connection];

                    if (!plcConn.Connected)
                    {
                        plcConn.Connect();
                    }

                    if (plcConn.Connected)
                    {
                        try
                        {
                            plcConn.ReadValues(tags);
                        }
                        catch (Exception ex)
                        {
                            if (StartedAsService)
                            {
                                Logging.LogText("Error: Exception during ReadData, maybe Connection interupted?", ex, Logging.LogLevel.Error);
                                return(null);
                            }

                            throw;
                        }
                        foreach (var plcTag in tags)
                        {
                            if (plcTag.ItemDoesNotExist)
                            {
                                if (StartedAsService)
                                {
                                    Logging.LogText("Tag does not Exist! " + plcConn.Configuration.ConnectionName + ": " + plcTag.S7FormatAddress, Logging.LogLevel.Error);
                                }
                                else
                                {
                                    throw new Exception("Tag does not Exist! " + plcConn.Configuration.ConnectionName + ": " + plcTag.S7FormatAddress);
                                }
                            }
                        }

                        if (usedConnection.Connection is LibNoDaveConfig)
                        {
                            if (!((LibNoDaveConfig)usedConnection.Connection).StayConnected)
                            {
                                plcConn.Disconnect();
                            }
                        }
                    }
                    else
                    {
                        Logging.LogText("Error: Read Data returned \"null\" maybe a Connection is offline?", Logging.LogLevel.Error);
                        return(null);
                    }
                }
            }

            List <object> retVal = new List <object>();

            foreach (var datasetConfigRow in datasetConfigRows)
            {
                retVal.Add(datasetConfigRow.Value(datasetConfig.UseFloatIfMultiplierIsUsed));
            }

            return(retVal);
        }
Ejemplo n.º 12
0
        private void WaitForTrigger()
        {
            try
            {
                bool alreadyWritten = false;
                while (true)
                {
                    if (triggerConn.Connected)
                    {
                        try
                        {
                            //Read the Trigger Bit
                            triggerConn.ReadValue(readBit);
                        }
                        catch (Exception ex)
                        {
                            if (StartedAsService)
                            {
                                Logging.LogText("Error: Exception during ReadData, maybe Connection interupted?", ex, Logging.LogLevel.Error);
                                try
                                {
                                    triggerConn.Disconnect();
                                    triggerConn.Connect();
                                }
                                catch (Exception exex)
                                {
                                    Logging.LogText("Error: Exception during Connect...", exex, Logging.LogLevel.Error);
                                }
                            }
                            else
                            {
                                throw;
                            }
                        }
                        //If the cycle counter is 0, switch to the slower interval (it means that no new data was there for a long time! ;-)
                        if (cycle_counter > 0)
                        {
                            //Logging.LogTextToLog4Net("WaitForTrigger() => \"" + datasetConfig.TriggerConnection.Name + "\" - NoDataInterval active");
                            cycle_counter--;

                            if (cycle_counter == 0)
                            {
                                ak_interval = NoDataInterval;
                            }

                            if ((!((bool)readBit.Value) && !alreadyWritten) && datasetConfig.TriggerConnection is LibNoDaveConfig && !((LibNoDaveConfig)datasetConfig.TriggerConnection).StayConnected)
                            {
                                ak_interval = NoDataInterval;
                                Logging.LogTextToLog4Net("WaitForTrigger() => \"" + datasetConfig.TriggerConnection.Name + "\" Discconnect because !StayConnected");
                                triggerConn.Disconnect();
                            }
                        }

                        if (((bool)readBit.Value & !alreadyWritten) || ((bool)readBit.Value) && onlyUseOneTag)
                        {
                            //Logging.LogTextToLog4Net("WaitForTrigger() => \"" + datasetConfig.TriggerConnection.Name + "\" - NewDataInterval active");
                            alreadyWritten = true;
                            cycle_counter  = NoDataCycles;
                            ak_interval    = NewDataInterval;

                            IEnumerable <object> values = ReadData.ReadDataFromDataSources(datasetConfig, datasetConfig.DatasetConfigRows, activConnections, StartedAsService);
                            if (values != null)
                            {
                                dbInterface.Write(values);

                                if (!onlyUseOneTag)
                                {
                                    quittBit.Value = true;
                                    try
                                    {
                                        triggerConn.WriteValue(quittBit);
                                    }
                                    catch (Exception ex)
                                    {
                                        if (StartedAsService)
                                        {
                                            Logging.LogText(
                                                "Error: Exception during WriteValue, maybe Connection interupted?", ex,
                                                Logging.LogLevel.Error);
                                            try
                                            {
                                                triggerConn.Disconnect();
                                                triggerConn.Connect();
                                            }
                                            catch (Exception exex)
                                            {
                                                Logging.LogText("Error: Exception during Connect...", exex, Logging.LogLevel.Error);
                                            }
                                        }
                                        else
                                        {
                                            throw;
                                        }
                                    }
                                }
                                else
                                {
                                    readBit.Value = false;
                                    triggerConn.WriteValue(readBit);
                                }
                            }
                        }
                        else if (!(bool)readBit.Value && !onlyUseOneTag)
                        {
                            if (alreadyWritten)
                            {
                                alreadyWritten = false;
                                quittBit.Value = false;
                                try
                                {
                                    triggerConn.WriteValue(quittBit);
                                }
                                catch (Exception ex)
                                {
                                    if (StartedAsService)
                                    {
                                        Logging.LogText("Error: Exception during WriteValue, maybe Connection interupted?", ex, Logging.LogLevel.Error);
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                        }

                        //Logging.LogTextToLog4Net("Sleep() => \"" + datasetConfig.TriggerConnection.Name + "\" Interval:" + ak_interval);
                        Thread.Sleep(ak_interval);
                    }
                    else
                    {
                        Logging.LogTextToLog4Net("WaitForTrigger() => \"" + datasetConfig.TriggerConnection.Name + "\" => Connect...");
                        cycle_counter = NoDataCycles;
                        triggerConn.Connect();
                    }
                }
            }
            catch (ThreadAbortException ex)
            {
                //ThreadExceptionOccured.Invoke(this, new ThreadExceptionEventArgs(ex));
            }
            catch (Exception ex)
            {
                ThreadExceptionOccured.Invoke(this, new ThreadExceptionEventArgs(ex));
            }
        }
        private void EstablishConnections()
        {
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                LibNoDaveConfig plcConnConf = connectionConfig as LibNoDaveConfig;
                TCPIPConfig tcpipConnConf = connectionConfig as TCPIPConfig;
                DatabaseConfig dbConnConf = connectionConfig as DatabaseConfig;

                if (plcConnConf != null)
                {
                    Logging.LogText("Connection: " + connectionConfig.Name + " is starting...", Logging.LogLevel.Information);

                    PLCConnection tmpConn = new PLCConnection(plcConnConf.Configuration);
                    try
                    {
                        tmpConn.Connect();
                        if (!plcConnConf.StayConnected)
                            tmpConn.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        Logging.LogText("Connection: " + connectionConfig.Name, ex, Logging.LogLevel.Warning);
                    }

                    ConnectionList.Add(connectionConfig, tmpConn);
                }
                else if (dbConnConf != null)
                {
                    var tmpConn = new DatabaseConnection(dbConnConf);
                    try
                    {
                        tmpConn.Connect();
                    }
                    catch (Exception ex)
                    {
                        Logging.LogText("Connection: " + connectionConfig.Name, ex, Logging.LogLevel.Warning);
                    }
                    ConnectionList.Add(connectionConfig, tmpConn);
                }
                else if (tcpipConnConf != null)
                {
                    //todo: legth of tcp conn
                    //TCPFunctionsAsync tmpConn = new TCPFunctionsAsync(new SynchronizationContext(), tcpipConnConf.IPasIPAddres, tcpipConnConf.Port, !tcpipConnConf.PassiveConnection, 0);

                    //tmpConn.Connect();

                    //ConnectionList.Add(connectionConfig, tmpConn);
                }
            }

            myReEstablishConnectionsThreads = new List<Thread>();
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                if (connectionConfig is LibNoDaveConfig)
                {
                    var thrd = new Thread(new ParameterizedThreadStart(ReEstablishConnectionsThreadProc)) { Name = "EstablishConnectionsThreadProc" };
                    thrd.Start(connectionConfig as LibNoDaveConfig);
                    this.myReEstablishConnectionsThreads.Add(thrd);
                }
            }
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine();
                Console.WriteLine("Bitte so starten:");
                Console.WriteLine();
                Console.WriteLine("BackupS7 Configfile Zielverzeichnis");
                Console.WriteLine();
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("Creating Directory...");
                var configFile      = args[0];
                var targetDirectory = Path.Combine(Environment.CurrentDirectory, args[1]);

                var text   = File.ReadAllText(configFile);
                var config = JsonConvert.DeserializeObject <Config>(text);

                Directory.CreateDirectory(targetDirectory);

                Console.WriteLine("Connecting to PLC...");
                var connection = new PLCConnection(new PLCConnectionConfiguration("BackupS7", LibNodaveConnectionConfigurationType.ObjectSavedConfiguration)
                {
                    ConnectionType = LibNodaveConnectionTypes.ISO_over_TCP, CpuIP = config.Ip, CpuRack = config.Rack, CpuSlot = config.Slot
                });
                connection.Connect();

                var szlDat = connection.PLCGetSZL(0x0111, 1);
                if (szlDat.SZLDaten.Length > 0)
                {
                    xy11Dataset xy11Szl = szlDat.SZLDaten[0] as xy11Dataset;
                    if (xy11Szl != null)
                    {
                        Console.WriteLine("Connected, MLFB: " + xy11Szl.MlfB);
                    }
                }

                Console.WriteLine("Read Blocks...");
                var existingBlocks = connection.PLCListBlocks(PLCBlockType.AllEditableBlocks);

                var backupBlocks = new List <string>();
                if (config.BackupBlocks != null)
                {
                    foreach (var b in config.BackupBlocks)
                    {
                        var txt = b.Trim().ToUpper().Replace(" ", "");
                        if (txt.Contains("-"))
                        {
                            var range = txt.Split('-');
                            var type  = range[0].Substring(0, 2);
                            var start = int.Parse(range[0].Substring(2));
                            var end   = int.Parse(range[1].Substring(2));
                            backupBlocks.AddRange(Enumerable.Range(start, (end - start) + 1).Select(x => type + x));
                        }
                        else
                        {
                            backupBlocks.Add(txt);
                        }
                    }
                }

                Console.WriteLine("Backup Blocks...");
                foreach (var b in existingBlocks)
                {
                    bool backUp = false;
                    if (config.BackupType.HasFlag(BackupType.Datablocks) && b.StartsWith("DB"))
                    {
                        backUp = true;
                    }
                    if (config.BackupType.HasFlag(BackupType.Functions) && b.StartsWith("FC"))
                    {
                        backUp = true;
                    }
                    if (config.BackupType.HasFlag(BackupType.FunctionBlocks) && b.StartsWith("FB"))
                    {
                        backUp = true;
                    }
                    if (backupBlocks.Contains(b.ToUpper().Trim()))
                    {
                        backUp = true;
                    }

                    if (backUp)
                    {
                        var blk = connection.PLCGetBlockInMC7(b);

                        string       file = Path.Combine(targetDirectory, b + ".blk");
                        BinaryWriter wrt  = new BinaryWriter(File.Open(file, FileMode.Create));
                        wrt.Write(blk);
                        wrt.Close();
                    }
                }
                connection.Disconnect();
                Console.WriteLine("Finish");
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Go through all reasonable Configurations for S7 Connections, and return one that works
        /// </summary>
        /// <param name="plcConfig"></param>

        private void SearchCPUs(PLCConnectionConfiguration plcConfig)
        {
            //go through Slot 0 to 5 and return all found CPU's, this is because S7-400 may have several CPU's in different Slots in one rack
            for (int i = 0; i <= 5; i++)
            {
                PLCConnectionConfiguration Conf = new PLCConnectionConfiguration();
                Conf.ConnectionType = plcConfig.ConnectionType;
                Conf.CpuIP          = plcConfig.CpuIP;
                Conf.Port           = plcConfig.Port;
                Conf.CpuRack        = plcConfig.CpuRack;
                Conf.CpuSlot        = i;

                PLCConnection Con = new PLCConnection(Conf);
                try
                {
                    Con.Connect();

                    FoundPlc FoundPlc = new FoundPlc();
                    FoundPlc.S7ConnectionSettings = Conf;

                    //Read name of PLC
                    var HWInfos = Con.PLCGetSZL(0x1c, 0);

                    foreach (xy1CDataset HWInfo in HWInfos.SZLDaten)
                    {
                        switch (HWInfo.Index)
                        {
                        case 1:
                            FoundPlc.S7ConnectionSettings.ConnectionName = HWInfo.Text;
                            FoundPlc.PlcName = HWInfo.Text;
                            break;

                        case 2:
                            FoundPlc.ModuleName = HWInfo.Text;
                            break;

                        case 3:
                            FoundPlc.PlantIdentification = HWInfo.Text;
                            break;

                        case 4:
                            FoundPlc.Copyright = HWInfo.Text;
                            break;

                        case 5:
                            FoundPlc.ModuleSerialNumber = HWInfo.Text;
                            break;

                        case 6:
                            break;

                        case 7:
                            FoundPlc.ModuleTypeName = HWInfo.Text;
                            break;

                        case 8:
                            break;

                        case 9:
                            FoundPlc.Manufacturer = HWInfo.Text;
                            break;

                        case 10:
                            break;

                        case 11:
                            FoundPlc.Location = HWInfo.Text;
                            break;
                        }
                    }

                    //Check if we actually found an CPU
                    //This is because some S7-400 CPUs also accept connections to Modules other than CPU, such as CP or similiar. But
                    //these are not wat we are looking for.
                    if (!FoundPlc.ModuleTypeName.ToLower().Contains("cpu") && !FoundPlc.ModuleName.ToLower().Contains("cpu"))
                    {
                        Debug.WriteLine("Found an available interface that accepted the connection but apparently was not an CPU. The adress was {0} and the Slot was {1}", plcConfig.CpuIP, plcConfig.CpuSlot);
                        continue;
                    }

                    lock (_DiscoveredPLCs)
                    {
                        _DiscoveredPLCs.Add(FoundPlc);
                    }
                    NewPlcFound?.Invoke(this, new PlcFoundEventArgs {
                        FoundPlc = FoundPlc
                    });
                    System.Threading.Thread.Sleep(100); //Some CPUs, especially IBH Softec Simulatin CPUs dont like it when the request are coming to fast. IBH chrashes
                }
                catch (Exception ex)
                {
                    continue;//Ignore erorr and try next Slot
                }
                finally
                {
                    Con.Disconnect();
                }
            }
        }