private void AddDBValueNodes(DBTreeNode nd)
 {
     if (nd.Nodes.Count > 0 && nd.Nodes[0] is FakeNode)
     {
         nd.Nodes.RemoveAt(0);
         S7DataBlock blk = (S7DataBlock)nd.PLCBlockInfo.GetBlock();
         nd.s7datarow = blk.Structure;
         AddDBValueSubNodes(nd, blk.Structure);
     }
 }
Exemplo n.º 2
0
        public void ParseDatablockWithUDT()
        {
            byte[]      block = File.ReadAllBytes(dir + "DB3005.bin");
            S7DataBlock DB    = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            //General Structure must be the same
            string Test = DB.ToString().Trim().Replace("\r\n", "\n");

            Assert.AreEqual(File.ReadAllText(dir + "DB3005.awl").Trim().Replace("\r\n", "\n"), DB.ToString().Trim().Replace("\r\n", "\n"));
        }
        public void ParseDataBlocks()
        {
            //The bin files are plain dumps obtained via an call to "PLCConnection.PLCGetBlockInMC7(...)"
            //The Awl files are the parsed awl code files for the corresponding files. these files are compared to
            //default Simatic manager online only output, in order to ensure correctness of the parsing
            //Lengths values are taken from the Simatic Manager Properties dialog

            //Set up templates for parsing
            string dir = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "S7Blocks" + Path.DirectorySeparatorChar;

            byte[] block;

            //_____________________________________________________________________________
            //Read Data-block with lots of Structs and Structs in Arrays
            //This db has an complex combination of Structures, arrays and Structures in Arrays
            block = File.ReadAllBytes(dir + "DB121.bin");
            S7DataBlock DB = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.DB, DB.BlockType);
            Assert.AreEqual(121, DB.BlockNumber);
            Assert.AreEqual(21418, DB.Length);             //Load memory Size
            Assert.AreEqual(20824, DB.CodeSize);           //Data size, this is the relevant data length
            Assert.AreEqual(File.ReadAllText(dir + "DB121.awl").Trim().Replace("\r\n", "\n"), DB.Structure.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read Data-block With long Array of Structs
            //This is an really long data-block with an really long Array of structures
            block = File.ReadAllBytes(dir + "DB13.bin");
            DB    = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.DB, DB.BlockType);
            Assert.AreEqual(13, DB.BlockNumber);
            Assert.AreEqual(64214, DB.Length);             //Load memory Size
            Assert.AreEqual(64040, DB.CodeSize);           //Data size, this is the relevant data length
            Assert.AreEqual(File.ReadAllText(dir + "DB13.awl").Trim().Replace("\r\n", "\n"), DB.Structure.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read Data-block With array and single Static Reals
            //An relatively simple block, with an Array and some simple reals at the end
            block = File.ReadAllBytes(dir + "DB4.bin");
            DB    = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.DB, DB.BlockType);
            Assert.AreEqual(4, DB.BlockNumber);
            Assert.AreEqual(8094, DB.Length);             //Load memory Size
            Assert.AreEqual(6000, DB.CodeSize);           //Data size, this is the relevant data length
            Assert.AreEqual(File.ReadAllText(dir + "DB4.awl").Trim().Replace("\r\n", "\n"), DB.Structure.ToString().Trim().Replace("\r\n", "\n"));
        }
        public ContentWindowDataBlockEditor(object myBlock)
        {
            InitializeComponent();

            this.myBlock  = (Block)myBlock;
            myBlockString = this.myBlock.ToString();

            if (myBlock is S7DataBlock)
            {
                S7DataBlock blk = (S7DataBlock)myBlock;
                dtaViewControl.DataBlockRows = ((S7DataRow)blk.Structure);
            }
            else if (myBlock is S5DataBlock)
            {
                S5DataBlock blk = (S5DataBlock)myBlock;
                dtaViewControl.DataBlockRows = ((S7DataRow)blk.Structure);
            }
        }
        public void ParseDataBlocks()
        {
            byte[] block;

            //_____________________________________________________________________________
            //Read Data-block with lots of Structs and Structs in Arrays
            //This db has an complex combination of Structures, arrays and Structures in Arrays
            block = File.ReadAllBytes(dir + "DB121.bin");
            S7DataBlock DB = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.DB, DB.BlockType);
            Assert.AreEqual(121, DB.BlockNumber);
            Assert.AreEqual(21418, DB.Length);             //Load memory Size
            Assert.AreEqual(20824, DB.CodeSize);           //Data size, this is the relevant data length
            Assert.AreEqual(File.ReadAllText(dir + "DB121.awl").Trim().Replace("\r\n", "\n"), DB.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read Data-block With long Array of Structs
            //This is an really long data-block with an really long Array of structures
            block = File.ReadAllBytes(dir + "DB13.bin");
            DB    = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.DB, DB.BlockType);
            Assert.AreEqual(13, DB.BlockNumber);
            Assert.AreEqual(64214, DB.Length);             //Load memory Size
            Assert.AreEqual(64040, DB.CodeSize);           //Data size, this is the relevant data length
            Assert.AreEqual(File.ReadAllText(dir + "DB13.awl").Trim().Replace("\r\n", "\n"), DB.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read Data-block With array and single Static Reals
            //An relatively simple block, with an Array and some simple reals at the end
            block = File.ReadAllBytes(dir + "DB4.bin");
            DB    = (S7DataBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.DB, DB.BlockType);
            Assert.AreEqual(4, DB.BlockNumber);
            Assert.AreEqual(8094, DB.Length);             //Load memory Size
            Assert.AreEqual(6000, DB.CodeSize);           //Data size, this is the relevant data length
            Assert.AreEqual(File.ReadAllText(dir + "DB4.awl").Trim().Replace("\r\n", "\n"), DB.Structure.ToString().Trim().Replace("\r\n", "\n"));
        }
        private void cmdSelectStep7UDT_Click(object sender, EventArgs e)
        {
            S7DataBlock myDB = DotNetSiemensPLCToolBoxLibrary.Projectfiles.SelectProjectPart.SelectUDT();

            if (myDB != null)
            {
                var myLst = S7DataRow.GetChildrowsAsList(((S7DataRow)myDB.GetArrayExpandedStructure(new S7DataBlockExpandOptions()
                {
                    ExpandCharArrays = false
                })));

                dtaSendTabelle.Rows.Clear();
                dtaEmpfangstelegrammAufgeschluesselt.Rows.Clear();

                foreach (var itm in myLst)
                {
                    if (itm.DataType != S7DataRowType.STRUCT && itm.DataType != S7DataRowType.UDT)
                    {
                        dtaSendTabelle.Rows.Add(new object[] { itm.StructuredName, itm.ByteLength });
                        dtaEmpfangstelegrammAufgeschluesselt.Rows.Add(new object[] { itm.StructuredName, itm.ByteLength });
                    }
                }
            }
        }
        /// <summary>
        /// Reads an Block from the Project and returns the block data that is stored in the S7 Project
        /// </summary>
        /// <param name="blkInfo">The Block info object that identifies the block to read from Disk</param>
        /// <param name="myConvOpt">Defines options that determine how the Block will be converted</param>
        /// <returns></returns>
        public Block GetBlock(ProjectBlockInfo blkInfo, S7ConvertingOptions myConvOpt)
        {
            if (blkInfo._Block != null && ((blkInfo._Block) as S7Block).usedS7ConvertingOptions.Equals(myConvOpt))
            {
                return(blkInfo._Block);
            }


            ProjectPlcBlockInfo plcblkifo = (ProjectPlcBlockInfo)blkInfo;
            tmpBlock            myTmpBlk  = GetBlockBytes(blkInfo);

            List <Step7Attribute> step7Attributes = null;

            if (myTmpBlk != null)
            {
                if (myTmpBlk.uda != null)
                {
                    int uPos = 2;
                    if (myTmpBlk.uda != null && myTmpBlk.uda.Length > 0 && myTmpBlk.uda[0] > 0)
                    {
                        step7Attributes = new List <Step7Attribute>();
                        for (int j = 0; j < myTmpBlk.uda[0]; j++)
                        {
                            string t1 = Project.ProjectEncoding.GetString(myTmpBlk.uda, uPos + 1, myTmpBlk.uda[uPos]);
                            uPos += myTmpBlk.uda[uPos] + 1;
                            string t2 = Project.ProjectEncoding.GetString(myTmpBlk.uda, uPos + 1, myTmpBlk.uda[uPos]);
                            uPos += myTmpBlk.uda[uPos] + 1;
                            step7Attributes.Add(new Step7Attribute(t1, t2));
                        }
                    }
                }

                //Begin with the Block Reading...
                if (blkInfo.BlockType == PLCBlockType.VAT)
                {
                    S7VATBlock retValBlock = new S7VATBlock(myTmpBlk.mc7code, myTmpBlk.comments, plcblkifo.BlockNumber, Project.ProjectEncoding);
                    retValBlock.Attributes = step7Attributes;

                    retValBlock.LastCodeChange      = myTmpBlk.LastCodeChange;
                    retValBlock.LastInterfaceChange = myTmpBlk.LastInterfaceChange;

                    retValBlock.ParentFolder            = this;
                    retValBlock.usedS7ConvertingOptions = myConvOpt;
                    blkInfo._Block = retValBlock;

                    return(retValBlock);
                }
                else if (blkInfo.BlockType == PLCBlockType.DB || blkInfo.BlockType == PLCBlockType.UDT)
                {
                    List <string> tmpList = new List <string>();
                    S7DataBlock   retVal  = new S7DataBlock();
                    retVal.IsInstanceDB = myTmpBlk.IsInstanceDB;
                    retVal.FBNumber     = myTmpBlk.FBNumber;

                    //if this is an interface DB, then rather take the Interface declaration from the instance FB,
                    //instead of the data sotred in the project.
                    //The reason is that if you change the comment in an FB, the DB data is not actualized and my contain outdated
                    //Declarations. When you change the interface, Step7 tells you to "regenerate" the instance DB which only then would
                    //Actualize the comments. Simple Commentary changes do not change the Datablocks row.
                    if (retVal.IsInstanceDB && myConvOpt.UseFBDeclarationForInstanceDB)
                    {
                        //load the FB data from the Project
                        tmpBlock InstFB = GetBlockBytes((myTmpBlk.IsSFB ? "SFB" : "FB") + myTmpBlk.FBNumber);

                        //Resolve both interfaces
                        List <string> tmpPar = new List <string>();
                        if (InstFB != null)
                        {
                            S7DataRow InterfaceFB =
                                Parameter.GetInterfaceOrDBFromStep7ProjectString(InstFB.blkinterface, ref tmpPar,
                                                                                 PLCBlockType.FB, false, this, null);
                            S7DataRow InterfaceDB =
                                Parameter.GetInterfaceOrDBFromStep7ProjectString(myTmpBlk.blkinterface, ref tmpPar,
                                                                                 PLCBlockType.DB, false, this, null);

                            //Only use the FB interface Declaration if they are compatible
                            if (Parameter.IsInterfaceCompatible(InterfaceFB, InterfaceDB))
                            {
                                myTmpBlk.blkinterface = InstFB.blkinterface;
                            }
                        }
                    }

                    if (myTmpBlk.mc7code != null)
                    {
                        retVal.CodeSize = myTmpBlk.mc7code.Length;
                    }

                    retVal.StructureFromString = Parameter.GetInterfaceOrDBFromStep7ProjectString(myTmpBlk.blkinterface, ref tmpList, blkInfo.BlockType, false, this, retVal, myTmpBlk.mc7code);
                    if (myTmpBlk.blkinterfaceInMC5 != null)
                    {
                        //List<string> tmp = new List<string>();
                        //retVal.StructureFromMC7 = Parameter.GetInterface(myTmpBlk.blkinterfaceInMC5, myTmpBlk.mc7code, ref tmp, blkInfo.BlockType, myTmpBlk.IsInstanceDB, retVal);
                    }
                    retVal.BlockNumber = plcblkifo.BlockNumber;
                    retVal.BlockType   = blkInfo.BlockType;
                    retVal.Attributes  = step7Attributes;

                    retVal.LastCodeChange      = myTmpBlk.LastCodeChange;
                    retVal.LastInterfaceChange = myTmpBlk.LastInterfaceChange;

                    retVal.ParentFolder            = this;
                    retVal.usedS7ConvertingOptions = myConvOpt;
                    retVal.CheckSum = myTmpBlk.CheckSum;
                    blkInfo._Block  = retVal;

                    return(retVal);
                }
                else if (blkInfo.BlockType == PLCBlockType.FC || blkInfo.BlockType == PLCBlockType.FB || blkInfo.BlockType == PLCBlockType.OB || blkInfo.BlockType == PLCBlockType.SFB || blkInfo.BlockType == PLCBlockType.SFC)
                {
                    List <string> ParaList = new List <string>();

                    S7FunctionBlock retVal = new S7FunctionBlock();

                    retVal.LastCodeChange      = myTmpBlk.LastCodeChange;
                    retVal.LastInterfaceChange = myTmpBlk.LastInterfaceChange;

                    retVal.BlockNumber       = plcblkifo.BlockNumber;
                    retVal.BlockType         = blkInfo.BlockType;
                    retVal.Attributes        = step7Attributes;
                    retVal.KnowHowProtection = myTmpBlk.knowHowProtection;
                    retVal.MnemonicLanguage  = Project.ProjectLanguage;

                    retVal.Author  = myTmpBlk.username;
                    retVal.Version = myTmpBlk.version;

                    retVal.Parameter = Parameter.GetInterfaceOrDBFromStep7ProjectString(myTmpBlk.blkinterface, ref ParaList, blkInfo.BlockType, false, this, retVal);

                    if (myTmpBlk.blockdescription != null)
                    {
                        retVal.Title       = Project.ProjectEncoding.GetString(myTmpBlk.blockdescription, 3, myTmpBlk.blockdescription[1] - 4);
                        retVal.Description = Project.ProjectEncoding.GetString(myTmpBlk.blockdescription, myTmpBlk.blockdescription[1], myTmpBlk.blockdescription.Length - myTmpBlk.blockdescription[1] - 1).Replace("\n", Environment.NewLine);
                    }

                    if (blkInfo.BlockType == PLCBlockType.FC || blkInfo.BlockType == PLCBlockType.FB || blkInfo.BlockType == PLCBlockType.OB)
                    {
                        retVal.CodeSize = myTmpBlk.mc7code.Length;

                        int[] Networks;
                        Networks = NetWork.GetNetworks(0, myTmpBlk.nwinfo);

                        S7ProgrammFolder prgFld = null;
                        if (this.Parent is S7ProgrammFolder)
                        {
                            prgFld = (S7ProgrammFolder)this.Parent;
                        }

                        retVal.AWLCode = MC7toAWL.GetAWL(0, myTmpBlk.mc7code.Length - 2, (int)myConvOpt.Mnemonic, myTmpBlk.mc7code, Networks, ParaList, prgFld, retVal, retVal.Parameter);

                        retVal.AWLCode = JumpMarks.AddJumpmarks(retVal.AWLCode, myTmpBlk.jumpmarks, myTmpBlk.nwinfo, myConvOpt);

                        LocalDataConverter.ConvertLocaldataToSymbols(retVal, myConvOpt);

                        CallConverter.ConvertUCToCall(retVal, prgFld, this, myConvOpt, null);

                        FBStaticAccessConverter.ReplaceStaticAccess(retVal, prgFld, myConvOpt);

                        #region UseComments from Block
                        if (myConvOpt.UseComments)
                        {
                            List <FunctionBlockRow> newAwlCode = new List <FunctionBlockRow>();

                            int n = 0;
                            int akRowInAwlCode   = 0;
                            int lineNumberInCall = 0; //Counter wich line in Command (for Calls and UCs)

                            if (myTmpBlk.comments != null)
                            {
                                byte[] cmt = myTmpBlk.comments;

                                //string aa = System.Text.Encoding.GetEncoding("Windows-1251").GetString(cmt);
                                //string testaa = "";

                                while (n < myTmpBlk.comments.Length)
                                {
                                    int kommLen            = cmt[n + 0];
                                    int startNWKomm        = cmt[n + 1];
                                    int anzUebsprungZeilen = cmt[n + 2] + cmt[n + 3] * 0x100;
                                    int lenNWKommZeile     = cmt[n + 3] + cmt[n + 4] * 0x100;
                                    //Console.WriteLine(cmt[n + 5].ToString("X"));
                                    if (cmt[n + 5] == 0x06)
                                    {
                                        //NWKomentar:
                                        string tx1 = Project.ProjectEncoding.GetString(cmt, n + 6, startNWKomm - 7);
                                        string tx2 = Project.ProjectEncoding.GetString(cmt, n + startNWKomm, lenNWKommZeile - startNWKomm - 1).Replace("\n", Environment.NewLine);
                                        n += lenNWKommZeile;

                                        if (retVal.AWLCode.Count > akRowInAwlCode)
                                        {
                                            while (retVal.AWLCode.Count - 1 > akRowInAwlCode && retVal.AWLCode[akRowInAwlCode].Command != "NETWORK")
                                            {
                                                if (!newAwlCode.Contains(retVal.AWLCode[akRowInAwlCode]))
                                                {
                                                    //newAwlCode.Add(retVal.AWLCode[akRowInAwlCode]);
                                                    S7FunctionBlockRow akRw = (S7FunctionBlockRow)retVal.AWLCode[akRowInAwlCode];

                                                    if (akRw.CombineDBAccess)
                                                    {
                                                        S7FunctionBlockRow nRw = (S7FunctionBlockRow)retVal.AWLCode[akRowInAwlCode + 1];
                                                        if (!nRw.Parameter.Contains("["))
                                                        {
                                                            nRw.Parameter = akRw.Parameter + "." + nRw.Parameter;
                                                            nRw.MC7       = Helper.CombineByteArray(akRw.MC7, nRw.MC7);
                                                            nRw.Label     = akRw.Label ?? nRw.Label;
                                                            akRw          = nRw;
                                                            retVal.AWLCode.RemoveAt(akRowInAwlCode + 1);
                                                        }
                                                    }

                                                    if (!newAwlCode.Contains(akRw))
                                                    {
                                                        newAwlCode.Add(akRw);
                                                    }
                                                }
                                                akRowInAwlCode++;
                                            }
                                            ((S7FunctionBlockRow)retVal.AWLCode[akRowInAwlCode]).NetworkName = tx1;
                                            ((S7FunctionBlockRow)retVal.AWLCode[akRowInAwlCode]).Comment     = tx2;
                                            newAwlCode.Add(retVal.AWLCode[akRowInAwlCode]);
                                        }
                                        akRowInAwlCode++;

                                        lineNumberInCall = 0;
                                    }
                                    else
                                    {
                                        S7FunctionBlockRow lastRow = null;

                                        //Anzahl der Anweisungen vor diesem Kommentar (inklusive aktueller Zeile!)
                                        for (int q = 0; q < (anzUebsprungZeilen); q++)
                                        {
                                            if (retVal.AWLCode.Count > akRowInAwlCode)
                                            {
                                                S7FunctionBlockRow akRw = (S7FunctionBlockRow)retVal.AWLCode[akRowInAwlCode];

                                                if (cmt[n + 4] == 0xc0 && q == anzUebsprungZeilen - 1)
                                                {
                                                    akRw.CombineDBAccess = false;
                                                }

                                                //Db Zugriff zusammenfügen...
                                                if (akRw.CombineDBAccess)
                                                {
                                                    S7FunctionBlockRow nRw = (S7FunctionBlockRow)retVal.AWLCode[akRowInAwlCode + 1];
                                                    nRw.Parameter = akRw.Parameter + "." + nRw.Parameter;
                                                    nRw.MC7       = Helper.CombineByteArray(akRw.MC7, nRw.MC7);
                                                    nRw.Label     = akRw.Label ?? nRw.Label;
                                                    akRw          = nRw;
                                                    retVal.AWLCode.RemoveAt(akRowInAwlCode + 1);
                                                }

                                                if (!newAwlCode.Contains(akRw))
                                                {
                                                    newAwlCode.Add(akRw);
                                                }


                                                if (akRw.GetNumberOfLines() == 1)
                                                {
                                                    lineNumberInCall = 0;

                                                    lastRow = akRw;

                                                    //if (!newAwlCode.Contains(akRw))
                                                    //    newAwlCode.Add(akRw);

                                                    akRowInAwlCode++;
                                                }
                                                else
                                                {
                                                    lastRow = akRw;
                                                    if (lineNumberInCall == 0 && !(cmt[n + 4] != 0x80 && cmt[n + 4] != 0xc0))
                                                    {
                                                        //if (!newAwlCode.Contains(akRw))
                                                        //    newAwlCode.Add(akRw);
                                                    }

                                                    if (akRw.GetNumberOfLines() - 1 == lineNumberInCall)
                                                    {
                                                        akRowInAwlCode++;
                                                        lineNumberInCall = 0;
                                                        //subCnt++;    //The set to zero was wrong here, but maybe now comments on calls do not work, need to check!
                                                    }
                                                    else
                                                    {
                                                        lineNumberInCall++;
                                                    }
                                                }
                                            }
                                        }


                                        //if (lastRow == null || cmt[n + 4] != 0x80)
                                        if (lastRow == null || (cmt[n + 4] != 0x80 && cmt[n + 4] != 0xc0))
                                        {
                                            lastRow = new S7FunctionBlockRow()
                                            {
                                                Parent = retVal
                                            };
                                            newAwlCode.Add(lastRow);
                                            lineNumberInCall = 0;
                                        }

                                        string tx1 = Project.ProjectEncoding.GetString(cmt, n + 6, kommLen);
                                        if (lineNumberInCall == 0)
                                        {
                                            lastRow.Comment = tx1;
                                        }
                                        else
                                        if (lastRow.Command == "CALL")
                                        {
                                            if (lineNumberInCall == 1)
                                            {
                                                lastRow.Comment = tx1;
                                            }
                                            else
                                            {
                                                if (lastRow.CallParameter.Count >= lineNumberInCall - 2)
                                                {
                                                    lastRow.CallParameter[lineNumberInCall - 2].Comment = tx1;
                                                }
                                            }
                                        }
                                        n += kommLen + 6;

                                        //subCnt = 0;
                                    }
                                }
                            }
                            while (akRowInAwlCode < retVal.AWLCode.Count)
                            {
                                newAwlCode.Add(retVal.AWLCode[akRowInAwlCode]);
                                akRowInAwlCode++;
                            }
                            retVal.AWLCode = newAwlCode;
                        }
                        #endregion
                    }

                    retVal.Networks = NetWork.GetNetworksList(retVal);

                    retVal.ParentFolder            = this;
                    retVal.usedS7ConvertingOptions = myConvOpt;
                    retVal.CheckSum = myTmpBlk.CheckSum;
                    blkInfo._Block  = retVal;

                    return(retVal);
                }
            }
            return(null);
        }
        private static S7Block CreateBlock(string blockType, string blockNumber, string type)
        {
            S7Block akBlock = null;

            switch (blockType.ToUpper())
            {
            case ("TYPE"):
            {
                akBlock = new S7DataBlock()
                {
                    BlockType = DataTypes.PLCBlockType.UDT, BlockLanguage = PLCLanguage.DB
                };
            }
            break;

            case ("DATA_BLOCK"):
            {
                akBlock = new S7DataBlock()
                {
                    BlockType = DataTypes.PLCBlockType.DB, BlockLanguage = PLCLanguage.DB
                };
            }
            break;

            case ("FUNCTION"):
            {
                akBlock = new S7FunctionBlock()
                {
                    BlockType = DataTypes.PLCBlockType.FC, BlockLanguage = PLCLanguage.AWL
                };

                S7DataRow parameterRoot  = new S7DataRow("ROOTNODE", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterIN    = new S7DataRow("IN", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterOUT   = new S7DataRow("OUT", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterINOUT = new S7DataRow("IN_OUT", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterSTAT  = new S7DataRow("STATIC", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterTEMP  = new S7DataRow("TEMP", S7DataRowType.STRUCT, akBlock);

                parameterOUT.Add(new S7DataRow("RET_VAL", (S7DataRowType)Enum.Parse(typeof(S7DataRowType), type), akBlock));

                parameterRoot.Children.Add(parameterIN);
                parameterRoot.Children.Add(parameterOUT);
                parameterRoot.Children.Add(parameterINOUT);
                parameterRoot.Children.Add(parameterSTAT);
                parameterRoot.Children.Add(parameterTEMP);
            }
            break;

            case ("FUNCTION_BLOCK"):
            {
                akBlock = new S7FunctionBlock()
                {
                    BlockType = DataTypes.PLCBlockType.FB, BlockLanguage = PLCLanguage.AWL
                };

                S7DataRow parameterRoot  = new S7DataRow("ROOTNODE", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterIN    = new S7DataRow("IN", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterOUT   = new S7DataRow("OUT", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterINOUT = new S7DataRow("IN_OUT", S7DataRowType.STRUCT, akBlock);
                S7DataRow parameterTEMP  = new S7DataRow("TEMP", S7DataRowType.STRUCT, akBlock);

                parameterRoot.Children.Add(parameterIN);
                parameterRoot.Children.Add(parameterOUT);
                parameterRoot.Children.Add(parameterINOUT);
                parameterRoot.Children.Add(parameterTEMP);
            }
            break;
            }

            return(akBlock);
        }
Exemplo n.º 9
0
        private static Dictionary <String, S7DataBlock> ReadDBSource(List <String> fileContents)
        {
            Dictionary <String, S7DataBlock> returnBlocks = new Dictionary <String, S7DataBlock>();
            S7DataBlock   currentBlock  = new S7DataBlock();
            bool          startReading  = false;
            List <String> blockContents = new List <String>();

            String[] split;

            foreach (String line in fileContents)
            {
                if (line.ToUpper().Contains("DATA_BLOCK"))
                {
                    split = line.Split(' ');
                    if (split.Length > 1)
                    {
                        currentBlock.Name = split[1].Trim('\"');

                        if (split.Length > 2)
                        {
                            int number = 0;
                            Int32.TryParse(split[2].Trim('\"'), out number);
                            currentBlock.BlockNumber = number;
                        }
                    }
                }

                if (line.ToUpper().Contains("VERSION"))
                {
                    split = line.Split(':');
                    if (split.Length > 1)
                    {
                        currentBlock.BlockVersion = split[1].Trim();
                    }
                }

                if (startReading)
                {
                    if (line.ToUpper().Contains("BEGIN"))
                    {
                        blockContents = blockContents.Where(s => !String.IsNullOrWhiteSpace(s)).ToList();
                        currentBlock.StructureFromString = UdtSourceParser.ParseChildrenRowsFromText(blockContents, currentBlock.Name, "", currentBlock);

                        if (!returnBlocks.ContainsKey(currentBlock.Name))
                        {
                            returnBlocks.Add(currentBlock.Name, currentBlock);
                        }
                        currentBlock = new S7DataBlock();

                        startReading = false;
                    }
                    else
                    {
                        blockContents.Add(line);
                    }
                }
                else
                {
                    if (line.ToUpper().Contains("STRUCT"))
                    {
                        startReading = true;
                    }
                }
            }

            return(returnBlocks);
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string errors = "";
            string tags   = "";

            foreach (var projectBlockInfo in ConvertBlocks)
            {
                S7DataBlock myDB = (S7DataBlock)projectBlockInfo.GetBlock();

                int cnt = 0;

                if (myDB.Structure != null && myDB.Structure.Children != null)
                {
                    cnt = myDB.Structure.Children[myDB.Structure.Children.Count - 1].NextBlockAddress.ByteAddress;
                }

                string varname = "STOERUNGEN_DB" + myDB.BlockNumber;

                tags += varname + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBW 0;Int;;" +
                        ((cnt - 2) / 2).ToString() + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";

                int errNr = Convert.ToInt32(txtStartErrorNumber.Text);

                foreach (S7DataRow plcDataRow in S7DataRow.GetChildrowsAsList(myDB.Structure))
                // myDB.GetRowsAsList())
                {
                    if (plcDataRow.DataType == S7DataRowType.BOOL)
                    {
                        ByteBitAddress akAddr = plcDataRow.BlockAddress;

                        int bitnr = (akAddr.ByteAddress / 2) * 16 + akAddr.BitAddress; //akAddr.BitAddress;
                        if (akAddr.ByteAddress % 2 == 0)
                        {
                            bitnr += 8;
                        }

                        string stoeTxt   = "";
                        string stoeTxtEn = "";

                        stoeTxt = plcDataRow.Comment;
                        if (stoeTxt.Contains(";"))
                        {
                            stoeTxt = "Störort: " + stoeTxt.Split(';')[0] + ", " + stoeTxt.Split(';')[1];
                        }

                        if (chkFixedErrorNumber.IsChecked.Value)
                        {
                            errNr = Convert.ToInt32(txtStartErrorNumber.Text) + akAddr.ByteAddress * 8 + akAddr.BitAddress;
                        }
                        errors += "\"D\"\t\"" + errNr.ToString() + "\"\t\"Alarms\"\t\"" + varname + "\"\t\"" +
                                  bitnr.ToString() + "\"\t\t\t\t\t\t\"0\"\t\"de-DE=" + stoeTxt + "\"\t\"en-US=" +
                                  stoeTxtEn + "\"\t\"de-DE=\"" + "\r\n";
                        if (!chkFixedErrorNumber.IsChecked.Value)
                        {
                            errNr++;
                        }
                    }
                }
            }

            FolderBrowserDialog fldDlg = null;

            fldDlg             = new FolderBrowserDialog();
            fldDlg.Description = "Destination Diretory for Alarms.csv and Tags.csv!";
            if (fldDlg.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter swr;

                swr = new System.IO.StreamWriter(fldDlg.SelectedPath + "\\Alarms.csv");
                swr.Write(errors);
                swr.Close();

                swr = new System.IO.StreamWriter(fldDlg.SelectedPath + "\\Tags.csv");
                swr.Write(tags.Replace(";", "\t"));
                swr.Close();
            }
        }
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            HMIGENOBJECTSLib.HMIGO HMIGOObject = null;
            try
            {
                HMIGOObject = new HMIGENOBJECTSLib.HMIGO();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The WinCC Object could not be created!\n\n Error:" + ex.Message);
            }

            foreach (var projectBlockInfo in ConvertBlocks)
            {
                S7DataBlock myDB = (S7DataBlock)projectBlockInfo.GetBlock();

                List <S7DataRow> myLst = null;
                if (chkExpandArrays.IsChecked.Value)
                {
                    myLst =
                        S7DataRow.GetChildrowsAsList(myDB.GetArrayExpandedStructure(new S7DataBlockExpandOptions()));
                }
                // ) myDB.GetRowsAsArrayExpandedList(ne);
                else
                {
                    myLst = S7DataRow.GetChildrowsAsList(myDB.Structure); // myDB.GetRowsAsList();
                }
                int cnt = 0;

                try
                {
                    foreach (S7DataRow plcDataRow in myLst)
                    {
                        string tagName = txtTagsPrefix.Text +
                                         plcDataRow.StructuredName.Replace(".", "_").Replace("[", "_").Replace("]", "").
                                         Replace(" ", "").Replace(",", "_");
                        try
                        {
                            switch (plcDataRow.DataType)
                            {
                            case S7DataRowType.BOOL:
                                HMIGOObject.CreateTag(tagName, HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_BINARY_TAG,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",D" +
                                                      plcDataRow.BlockAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;

                            case S7DataRowType.INT:
                                HMIGOObject.CreateTag(tagName,
                                                      HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_SIGNED_16BIT_VALUE,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",DW" +
                                                      plcDataRow.BlockAddress.ByteAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;

                            case S7DataRowType.DINT:
                                HMIGOObject.CreateTag(tagName,
                                                      HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_SIGNED_32BIT_VALUE,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",DD" +
                                                      plcDataRow.BlockAddress.ByteAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;

                            case S7DataRowType.WORD:
                                HMIGOObject.CreateTag(tagName,
                                                      HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_UNSIGNED_16BIT_VALUE,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",DW" +
                                                      plcDataRow.BlockAddress.ByteAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;

                            case S7DataRowType.DWORD:
                                HMIGOObject.CreateTag(tagName,
                                                      HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_UNSIGNED_32BIT_VALUE,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",DD" +
                                                      plcDataRow.BlockAddress.ByteAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;

                            case S7DataRowType.BYTE:
                                HMIGOObject.CreateTag(tagName,
                                                      HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_UNSIGNED_8BIT_VALUE,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",DBB" +
                                                      plcDataRow.BlockAddress.ByteAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;

                            case S7DataRowType.REAL:
                                HMIGOObject.CreateTag(tagName,
                                                      HMIGENOBJECTSLib.HMIGO_TAG_TYPE.
                                                      TAG_FLOATINGPOINT_NUMBER_32BIT_IEEE_754,
                                                      txtConnectionName.Text,
                                                      "DB" + myDB.BlockNumber + ",DD" +
                                                      plcDataRow.BlockAddress.ByteAddress.ToString(),
                                                      "TAGS_DB" + myDB.BlockNumber);
                                break;
                            }
                        }
                        catch (System.Runtime.InteropServices.COMException ex)
                        {
                            if (ex.ErrorCode != -2147196408)
                            {
                                throw ex;
                            }
                            //Tag existiert schoin
                        }
                    }
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    if (ex.ErrorCode == -2147195889)
                    {
                        MessageBox.Show("Error: The Connection Name you specified does not exist!");
                    }
                    else
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                    return;
                }
            }
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            HMIGENOBJECTSLib.HMIGO HMIGOObject = null;
            try
            {
                HMIGOObject = new HMIGENOBJECTSLib.HMIGO();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The WinCC Object could not be created!\n\n Error:" + ex.Message);
            }

            try
            {
                foreach (var projectBlockInfo in ConvertBlocks)
                {
                    S7DataBlock myDB = (S7DataBlock)projectBlockInfo.GetBlock();


                    int cnt = 0;

                    if (myDB.Structure != null && myDB.Structure.Children != null)
                    {
                        cnt = myDB.Structure.Children[myDB.Structure.Children.Count - 1].NextBlockAddress.ByteAddress;
                    }

                    string varname = "STOERUNGEN_DB" + myDB.BlockNumber;

                    for (int n = 0; n < cnt / 2; n++)
                    {
                        try
                        {
                            HMIGOObject.CreateTag(varname + "_" + (n + 1).ToString(),
                                                  HMIGENOBJECTSLib.HMIGO_TAG_TYPE.TAG_UNSIGNED_16BIT_VALUE,
                                                  txtConnectionName.Text,
                                                  "DB" + myDB.BlockNumber + ",DD" + (n * 2).ToString(), "Stoerungen");
                        }
                        catch (COMException ex)
                        {
                            if (ex.ErrorCode != -2147196408)
                            {
                                throw ex;
                            }
                        }
                    }

                    string errors = "";

                    int errNr = Convert.ToInt32(txtStartErrorNumber.Text);

                    foreach (S7DataRow plcDataRow in S7DataRow.GetChildrowsAsList(myDB.Structure))
                    // myDB.GetRowsAsList())
                    {
                        if (plcDataRow.DataType == S7DataRowType.BOOL)
                        {
                            ByteBitAddress akAddr = plcDataRow.BlockAddress;
                            int            varnr  = (akAddr.ByteAddress / 2) + 1;

                            int bitnr = akAddr.BitAddress;
                            if (akAddr.ByteAddress % 2 == 0)
                            {
                                bitnr += 8;
                            }

                            string stoeTxt   = "";
                            string stoeOrt   = "";
                            string stoeTxtEn = "";

                            stoeTxt = plcDataRow.Comment;
                            if (stoeTxt.Contains(";"))
                            {
                                stoeTxt = stoeTxt.Split(';')[1];
                                stoeOrt = stoeTxt.Split(';')[0];
                            }

                            if (chkFixedErrorNumber.IsChecked.Value)
                            {
                                errNr = Convert.ToInt32(txtStartErrorNumber.Text) + akAddr.ByteAddress * 8 +
                                        akAddr.BitAddress;
                            }

                            try
                            {
                                HMIGOObject.CreateSingleAlarm(errNr,
                                                              HMIGENOBJECTSLib.HMIGO_SINGLE_ALARM_CLASS_ID.
                                                              SINGLE_ALARM_ERROR, 1, stoeTxt,
                                                              varname + "_" + varnr.ToString(), bitnr);
                                HMIGOObject.SingleAlarmInfoText = stoeTxt;
                                HMIGOObject.SingleAlarmText2ID  = stoeOrt;
                                HMIGOObject.CommitSingleAlarm();
                            }
                            catch (System.Runtime.InteropServices.COMException ex)
                            {
                                if (ex.ErrorCode != -2147467259)
                                {
                                    throw ex;
                                }
                            }

                            //errors += "\"D\"\t\"" + errNr.ToString() + "\"\t\"Alarms\"\t\"" + varname + "\"\t\"" + bitnr.ToString() + "\"\t\t\t\t\t\t\"0\"\t\"de-DE=" + stoeTxt + "\"\t\"en-US=" + stoeTxtEn + "\"\t\"de-DE=\"" + "\r\n";
                            if (!chkFixedErrorNumber.IsChecked.Value)
                            {
                                errNr++;
                            }
                        }
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                if (ex.ErrorCode == -2147195889)
                {
                    MessageBox.Show("Error: The Connection Name you specified does not exist!");
                }
                else
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
Exemplo n.º 13
0
        private static Dictionary <String, S7DataBlock> ReadUdtSource(List <String> fileContents, int addressOffset)
        {
            Dictionary <String, S7DataBlock> returnBlocks = new Dictionary <String, S7DataBlock>();
            S7DataBlock   currentBlock  = new S7DataBlock();
            bool          startReading  = false;
            List <String> blockContents = new List <String>();

            String[] split;

            foreach (String line in fileContents)
            {
                if (line.Contains("TYPE"))
                {
                    split = line.Split(' ');
                    if (split.Length > 1)
                    {
                        currentBlock.Name = split[1].Trim('\"');
                    }
                }

                if (line.ToUpper().Contains("VERSION"))
                {
                    split = line.Split(':');
                    if (split.Length > 1)
                    {
                        currentBlock.BlockVersion = split[1].Trim();
                    }
                }

                if (startReading)
                {
                    if (line.Contains("END_TYPE"))
                    {
                        blockContents = blockContents.Where(s => !String.IsNullOrWhiteSpace(s)).ToList();
                        currentBlock.StructureFromString         = ParseChildrenRowsFromText(blockContents, currentBlock.Name, "", currentBlock);
                        currentBlock.StructureFromString.Comment = currentBlock.Name;

                        if (!returnBlocks.ContainsKey(currentBlock.Name))
                        {
                            returnBlocks.Add(currentBlock.Name, currentBlock);
                            UdtReferenceBlocks.Add(currentBlock.Name, currentBlock);
                        }

                        currentBlock = new S7DataBlock();

                        startReading = false;
                    }
                    else
                    {
                        blockContents.Add(line);
                    }
                }
                else
                {
                    if (line.Contains("STRUCT"))
                    {
                        startReading = true;
                    }
                }
            }

            return(returnBlocks);
        }
Exemplo n.º 14
0
        /// <summary>
        /// With this Function you get the AWL Source of a Block, so that it can be imported into Step7
        /// </summary>
        /// <param name="blkInfo">The BlockInfo from the Block you wish to get the Source of!</param>
        /// <returns></returns>
        public string GetSourceBlock(ProjectBlockInfo blkInfo)
        {
            StringBuilder retVal = new StringBuilder();
            Block         blk    = GetBlock(blkInfo, new S7ConvertingOptions(Project.ProjectLanguage)
            {
                CombineDBOpenAndDBAccess = true, GenerateCallsfromUCs = true, ReplaceDBAccessesWithSymbolNames = false, ReplaceLokalDataAddressesWithSymbolNames = true, UseComments = true
            });


            S7Block         fblk  = (S7Block)blk;
            S7FunctionBlock fcblk = null;

            if (blk is S7FunctionBlock)
            {
                fcblk = (S7FunctionBlock)blk;
                if (fcblk.BlockType == PLCBlockType.FC)
                {
                    retVal.Append("FUNCTION " + blk.BlockName + " : VOID" + Environment.NewLine);
                }
                else
                {
                    retVal.Append("FUNCTION_BLOCK " + blk.BlockName + Environment.NewLine);
                }
            }
            else
            {
                retVal.Append("DATA_BLOCK " + blk.BlockName + Environment.NewLine);
            }
            retVal.Append("TITLE =" + fblk.Title + Environment.NewLine);
            if (blk is S7FunctionBlock)
            {
                if (!String.IsNullOrEmpty(fcblk.Description))
                {
                    retVal.Append("//" + fcblk.Description.Replace(Environment.NewLine, Environment.NewLine + "//") + Environment.NewLine);
                }
            }
            if (!string.IsNullOrEmpty(fblk.Author))
            {
                retVal.Append("AUTHOR : " + fblk.Author + Environment.NewLine);
            }
            if (!string.IsNullOrEmpty(fblk.Name))
            {
                retVal.Append("NAME : " + fblk.Name + Environment.NewLine);
            }
            if (!string.IsNullOrEmpty(fblk.Version))
            {
                retVal.Append("VERSION : " + fblk.Version + Environment.NewLine);
            }
            retVal.Append(Environment.NewLine);
            retVal.Append(Environment.NewLine);

            if (blk is S7DataBlock)
            {
                S7DataBlock dtaBlk = (S7DataBlock)fblk;
                if (dtaBlk.Structure.Children != null && !dtaBlk.IsInstanceDB)
                {
                    retVal.Append("  STRUCT" + Environment.NewLine);
                    retVal.Append(GetSubParas(dtaBlk.Structure, "    "));
                    retVal.Append("  END_STRUCT ;" + Environment.NewLine);
                }
                else if (dtaBlk.IsInstanceDB)
                {
                    retVal.Append(" FB " + dtaBlk.FBNumber + Environment.NewLine);
                }
                retVal.Append("BEGIN" + Environment.NewLine);
                retVal.Append("END_DATA_BLOCK" + Environment.NewLine);
            }
            else if (blk is S7FunctionBlock)
            {
                if (fcblk.Parameter.Children != null)
                {
                    foreach (S7DataRow s7DataRow in fcblk.Parameter.Children)
                    {
                        string parnm = s7DataRow.Name;
                        string ber   = "VAR_" + parnm;
                        if (parnm == "IN")
                        {
                            ber = "VAR_INPUT";
                        }
                        else if (parnm == "OUT")
                        {
                            ber = "VAR_OUTPUT";
                        }
                        else if (parnm == "STATIC")
                        {
                            ber = "VAR";
                        }
                        retVal.Append(ber + Environment.NewLine);
                        retVal.Append(GetSubParas(s7DataRow, "  "));
                        retVal.Append("END_VAR" + Environment.NewLine);
                    }
                }
                retVal.Append("BEGIN" + Environment.NewLine);
                foreach (Network network in fcblk.Networks)
                {
                    retVal.Append("NETWORK" + Environment.NewLine);
                    retVal.Append("TITLE = " + network.Name + Environment.NewLine);
                    if (!String.IsNullOrEmpty(network.Comment))
                    {
                        retVal.Append("//" + network.Comment.Replace(Environment.NewLine, Environment.NewLine + "//") + Environment.NewLine);
                    }
                    else
                    {
                        retVal.Append(Environment.NewLine);
                    }
                    foreach (S7FunctionBlockRow functionBlockRow in network.AWLCode)
                    {
                        if (functionBlockRow.ToString(false, false) == "")
                        {
                            retVal.Append(Environment.NewLine);
                        }
                        else
                        {
                            retVal.Append(functionBlockRow.ToString(false, true) + Environment.NewLine);
                        }
                    }
                }
                retVal.Append("END_FUNCTION");
            }

            return(retVal.ToString());
        }
Exemplo n.º 15
0
        public Block GetBlock(ProjectBlockInfo blkInfo, S7ConvertingOptions myConvOpt)
        {
            //Todo: Enable this, but then myConvOpt is only used the first time!
            //if (blkInfo._Block != null)
            //    return blkInfo._Block;


            ProjectPlcBlockInfo plcblkifo = (ProjectPlcBlockInfo)blkInfo;
            tmpBlock            myTmpBlk  = GetBlockBytes(blkInfo);

            List <Step7Attribute> step7Attributes = null;

            if (myTmpBlk != null)
            {
                if (myTmpBlk.uda != null)
                {
                    int uPos = 2;
                    if (myTmpBlk.uda != null && myTmpBlk.uda.Length > 0 && myTmpBlk.uda[0] > 0)
                    {
                        step7Attributes = new List <Step7Attribute>();
                        for (int j = 0; j < myTmpBlk.uda[0]; j++)
                        {
                            string t1 = Project.ProjectEncoding.GetString(myTmpBlk.uda, uPos + 1, myTmpBlk.uda[uPos]);
                            uPos += myTmpBlk.uda[uPos] + 1;
                            string t2 = Project.ProjectEncoding.GetString(myTmpBlk.uda, uPos + 1, myTmpBlk.uda[uPos]);
                            uPos += myTmpBlk.uda[uPos] + 1;
                            step7Attributes.Add(new Step7Attribute(t1, t2));
                        }
                    }
                }


                //Begin with the Block Reading...
                if (blkInfo.BlockType == PLCBlockType.VAT)
                {
                    S7VATBlock retValBlock = new S7VATBlock(myTmpBlk.mc7code, myTmpBlk.comments, plcblkifo.BlockNumber, Project.ProjectEncoding);
                    retValBlock.Attributes = step7Attributes;

                    retValBlock.LastCodeChange      = myTmpBlk.LastCodeChange;
                    retValBlock.LastInterfaceChange = myTmpBlk.LastInterfaceChange;

                    retValBlock.BlockLanguage = (PLCLanguage)myTmpBlk.Language;

                    return(retValBlock);
                }
                else if (blkInfo.BlockType == PLCBlockType.DB || blkInfo.BlockType == PLCBlockType.UDT)
                {
                    List <string> tmpList = new List <string>();
                    S7DataBlock   retVal  = new S7DataBlock();
                    retVal.IsInstanceDB        = myTmpBlk.IsInstanceDB;
                    retVal.FBNumber            = myTmpBlk.FBNumber;
                    retVal.StructureFromString = Parameter.GetInterfaceOrDBFromStep7ProjectString(myTmpBlk.blkinterface, ref tmpList, blkInfo.BlockType, false, this, retVal, myTmpBlk.mc7code);
                    if (myTmpBlk.blkinterfaceInMC5 != null)
                    {
                        //List<string> tmp = new List<string>();
                        //retVal.StructureFromMC7 = Parameter.GetInterface(myTmpBlk.blkinterfaceInMC5, myTmpBlk.mc7code, ref tmp, blkInfo.BlockType, myTmpBlk.IsInstanceDB, retVal);
                    }
                    retVal.BlockNumber = plcblkifo.BlockNumber;
                    retVal.BlockType   = blkInfo.BlockType;
                    retVal.Attributes  = step7Attributes;

                    retVal.LastCodeChange      = myTmpBlk.LastCodeChange;
                    retVal.LastInterfaceChange = myTmpBlk.LastInterfaceChange;
                    if (blkInfo.BlockType != PLCBlockType.UDT)
                    {
                        retVal.CodeSize = myTmpBlk.mc7code.Length + 36;
                    }

                    retVal.BlockLanguage = (PLCLanguage)myTmpBlk.Language;

                    return(retVal);
                }
                else if (blkInfo.BlockType == PLCBlockType.FC || blkInfo.BlockType == PLCBlockType.FB || blkInfo.BlockType == PLCBlockType.OB || blkInfo.BlockType == PLCBlockType.SFB || blkInfo.BlockType == PLCBlockType.SFC)
                {
                    List <string> ParaList = new List <string>();

                    S7FunctionBlock retVal = new S7FunctionBlock();
                    blkInfo._Block = retVal;

                    retVal.LastCodeChange      = myTmpBlk.LastCodeChange;
                    retVal.LastInterfaceChange = myTmpBlk.LastInterfaceChange;

                    retVal.BlockNumber       = plcblkifo.BlockNumber;
                    retVal.BlockType         = blkInfo.BlockType;
                    retVal.Attributes        = step7Attributes;
                    retVal.KnowHowProtection = myTmpBlk.knowHowProtection;
                    retVal.MnemonicLanguage  = Project.ProjectLanguage;
                    retVal.CodeSize          = myTmpBlk.mc7code.Length + 36;

                    retVal.Author  = myTmpBlk.username;
                    retVal.Version = myTmpBlk.version;

                    //  retVal.Parameter = Parameter.GetInterfaceOrDBFromStep7ProjectString(myTmpBlk.blkinterface, ref ParaList, blkInfo.BlockType, false, this, retVal);

                    if (myTmpBlk.blockdescription != null)
                    {
                        retVal.Title       = Project.ProjectEncoding.GetString(myTmpBlk.blockdescription, 3, myTmpBlk.blockdescription[1] - 4);
                        retVal.Description = Project.ProjectEncoding.GetString(myTmpBlk.blockdescription, myTmpBlk.blockdescription[1], myTmpBlk.blockdescription.Length - myTmpBlk.blockdescription[1] - 1).Replace("\n", Environment.NewLine);
                    }

                    retVal.BlockLanguage = (PLCLanguage)myTmpBlk.Language;

                    return(retVal);

                    if (blkInfo.BlockType == PLCBlockType.FC || blkInfo.BlockType == PLCBlockType.FB || blkInfo.BlockType == PLCBlockType.OB)
                    {
                        int[] Networks;
                        Networks = NetWork.GetNetworks(0, myTmpBlk.nwinfo);

                        S7ProgrammFolder prgFld = null;
                        if (this.Parent is S7ProgrammFolder)
                        {
                            prgFld = (S7ProgrammFolder)this.Parent;
                        }

                        retVal.AWLCode = MC7toAWL.GetAWL(0, myTmpBlk.mc7code.Length - 2, (int)myConvOpt.Mnemonic, myTmpBlk.mc7code, Networks, ParaList, prgFld);

                        retVal.AWLCode = JumpMarks.AddJumpmarks(retVal.AWLCode, myTmpBlk.jumpmarks, myTmpBlk.nwinfo);

                        LocalDataConverter.ConvertLocaldataToSymbols(retVal, myConvOpt);

                        FBStaticAccessConverter.ReplaceStaticAccess(retVal, prgFld, myConvOpt);

                        CallConverter.ConvertUCToCall(retVal, prgFld, this, myConvOpt, null);

                        #region UseComments from Block
                        if (myConvOpt.UseComments)
                        {
                            List <FunctionBlockRow> newAwlCode = new List <FunctionBlockRow>();

                            int n      = 0;
                            int j      = 0;
                            int subCnt = 0; //Counter wich line in Command (for Calls and UCs)

                            if (myTmpBlk.comments != null)
                            {
                                byte[] cmt = myTmpBlk.comments;

                                //string aa = System.Text.Encoding.GetEncoding("Windows-1251").GetString(cmt);
                                //string testaa = "";

                                while (n < myTmpBlk.comments.Length)
                                {
                                    int kommLen            = cmt[n + 0];
                                    int startNWKomm        = cmt[n + 1];
                                    int anzUebsprungZeilen = cmt[n + 2] + cmt[n + 3] * 0x100;
                                    int lenNWKommZeile     = cmt[n + 3] + cmt[n + 4] * 0x100;
                                    //Console.WriteLine(cmt[n + 5].ToString("X"));
                                    if (cmt[n + 5] == 0x06)
                                    {
                                        //NWKomentar:
                                        string tx1 = Project.ProjectEncoding.GetString(cmt, n + 6, startNWKomm - 7);
                                        string tx2 = Project.ProjectEncoding.GetString(cmt, n + startNWKomm, lenNWKommZeile - startNWKomm - 1).Replace("\n", Environment.NewLine);
                                        n += lenNWKommZeile;

                                        if (retVal.AWLCode.Count > j)
                                        {
                                            while (retVal.AWLCode.Count - 1 > j && retVal.AWLCode[j].Command != "NETWORK")
                                            {
                                                newAwlCode.Add(retVal.AWLCode[j]);
                                                j++;
                                            }
                                            ((S7FunctionBlockRow)retVal.AWLCode[j]).NetworkName = tx1;
                                            ((S7FunctionBlockRow)retVal.AWLCode[j]).Comment     = tx2;
                                            newAwlCode.Add(retVal.AWLCode[j]);
                                        }
                                        j++;

                                        subCnt = 0;
                                    }
                                    else
                                    {
                                        S7FunctionBlockRow lastRow = null;

                                        //Anzahl der Anweisungen vor diesem Kommentar (inklusive aktueller Zeile!)
                                        for (int q = 0; q < (anzUebsprungZeilen); q++)
                                        {
                                            if (retVal.AWLCode.Count > j)
                                            {
                                                S7FunctionBlockRow akRw = (S7FunctionBlockRow)retVal.AWLCode[j];

                                                if (cmt[n + 4] == 0xc0 && q == anzUebsprungZeilen - 1)
                                                {
                                                    akRw.CombineDBAccess = false;
                                                }

                                                //Db Zugriff zusammenfügen...
                                                if (akRw.CombineDBAccess)
                                                {
                                                    S7FunctionBlockRow nRw = (S7FunctionBlockRow)retVal.AWLCode[j + 1];
                                                    nRw.Parameter = akRw.Parameter + "." + nRw.Parameter;
                                                    nRw.MC7       = Helper.CombineByteArray(akRw.MC7, nRw.MC7);

                                                    akRw = nRw;
                                                    retVal.AWLCode.RemoveAt(j + 1);
                                                }


                                                if (akRw.GetNumberOfLines() == 1)
                                                {
                                                    subCnt = 0;

                                                    lastRow = akRw;

                                                    newAwlCode.Add(akRw);
                                                    j++;
                                                }
                                                else
                                                {
                                                    lastRow = akRw;
                                                    if (subCnt == 0)
                                                    {
                                                        newAwlCode.Add(akRw);
                                                    }

                                                    if (akRw.GetNumberOfLines() - 1 == subCnt)
                                                    {
                                                        j++;
                                                        //subCnt = 0;
                                                        subCnt++;
                                                    }
                                                    else
                                                    {
                                                        subCnt++;
                                                    }
                                                }
                                            }
                                        }


                                        //if (lastRow == null || cmt[n + 4] != 0x80)
                                        if (lastRow == null || (cmt[n + 4] != 0x80 && cmt[n + 4] != 0xc0))
                                        {
                                            lastRow = new S7FunctionBlockRow();
                                            newAwlCode.Add(lastRow);
                                            subCnt = 0;
                                        }

                                        string tx1 = Project.ProjectEncoding.GetString(cmt, n + 6, kommLen);
                                        if (subCnt == 0)
                                        {
                                            lastRow.Comment = tx1;
                                        }
                                        else
                                        if (lastRow.Command == "CALL")
                                        {
                                            if (subCnt == 1)
                                            {
                                                lastRow.Comment = tx1;
                                            }
                                            else
                                            {
                                                lastRow.CallParameter[subCnt - 2].Comment = tx1;
                                            }
                                        }
                                        n += kommLen + 6;

                                        //subCnt = 0;
                                    }
                                }
                            }
                            while (j < retVal.AWLCode.Count)
                            {
                                newAwlCode.Add(retVal.AWLCode[j]);
                                j++;
                            }
                            retVal.AWLCode = newAwlCode;
                        }
                        #endregion
                    }

                    retVal.Networks = NetWork.GetNetworksList(retVal);

                    retVal.ParentFolder = this;

                    return(retVal);
                }
            }
            return(null);
        }
Exemplo n.º 16
0
        private void cmdCreateWinCCFlexibleTags_Click(object sender, EventArgs e)
        {
            S7DataBlock myDB = (S7DataBlock)((BlocksOfflineFolder)blkFld).GetBlock((S7ProjectBlockInfo)lstListBox.SelectedItem);

            List <S7DataRow> myLst = null;

            if (chkExpandArrays.Checked)
            {
                myLst = S7DataRow.GetChildrowsAsList(myDB.GetArrayExpandedStructure(new S7DataBlockExpandOptions())); // ) myDB.GetRowsAsArrayExpandedList(ne);
            }
            else
            {
                myLst = S7DataRow.GetChildrowsAsList(myDB.Structure); // myDB.GetRowsAsList();
            }
            string tags = "";


            foreach (S7DataRow plcDataRow in myLst) // myDB.GetRowsAsList())
            {
                string tagName = txtTagsPrefix.Text + plcDataRow.StructuredName.Replace(".", "_").Replace("[", "_").Replace("]", "").Replace(" ", "").Replace(",", "_");

                switch (plcDataRow.DataType)
                {
                case S7DataRowType.BOOL:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBX " + plcDataRow.BlockAddress.ByteAddress.ToString() + "." + plcDataRow.BlockAddress.BitAddress.ToString() + ";Bool;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.INT:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBW " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Int;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.DINT:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBD " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";DInt;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.WORD:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBW " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Word;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.DWORD:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBD " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";DWord;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.BYTE:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBB " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Byte;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.REAL:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBD " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Real;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.CHAR:
                    if (plcDataRow.IsArray)
                    {
                        tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBB " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";StringChar;" + plcDataRow.GetArrayLines().ToString() + ";" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    }
                    else
                    {
                        tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBB " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Char;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    }
                    break;

                case S7DataRowType.COUNTER:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBW " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Counter;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.DATE:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBD " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Date;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.DATE_AND_TIME:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBB " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Date and Time;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.S5TIME:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBW " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Timer;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.STRING:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBB " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";String;" + plcDataRow.StringSize.ToString() + ";" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.TIME:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBD " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Time;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.TIME_OF_DAY:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBD " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Time of Day;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;

                case S7DataRowType.TIMER:
                    tags += tagName + ";" + txtConnectionName.Text + ";DB " + myDB.BlockNumber + " DBW " + plcDataRow.BlockAddress.ByteAddress.ToString() + ";Timer;;" + "1" + ";2;1 s;;;;;0;10;0;100;0;;0;\r\n";
                    break;
                }
            }

            FolderBrowserDialog fldDlg = null;

            fldDlg             = new FolderBrowserDialog();
            fldDlg.Description = "Destination Directory for Tags.csv!";
            if (fldDlg.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter swr;

                swr = new System.IO.StreamWriter(fldDlg.SelectedPath + "\\Tags.csv");
                swr.Write(tags.Replace(";", "\t"));
                swr.Close();
            }
        }