//todo only use the networks structure!

        public static List<Network> GetNetworksList(S7FunctionBlock blk)
        {

            var retVal = new List<Network>();
            
            S7FunctionBlockNetwork nw = null;
            if (blk.AWLCode != null)
                foreach (S7FunctionBlockRow s7FunctionBlockRow in blk.AWLCode)
                {
                    if (s7FunctionBlockRow.Command == "NETWORK")
                    {
                        nw = new S7FunctionBlockNetwork();
                        nw.Parent = blk;
                        nw.AWLCode = new List<FunctionBlockRow>();
                        retVal.Add(nw);
                        nw.Name = s7FunctionBlockRow.NetworkName;
                        nw.Comment = s7FunctionBlockRow.Comment;
                    }
                    else
                    {
                        if (nw == null)
                        {
                           nw = new S7FunctionBlockNetwork();
                           nw.Parent = blk;
                           nw.AWLCode = new List<FunctionBlockRow>();
                           retVal.Add(nw);
                        }
                        nw.AWLCode.Add(s7FunctionBlockRow);
                    }

                }

            return retVal;
        }
Exemple #2
0
 //Todo: Check if Jump label is used in the Block!
 static public bool IsJumpTarget(S7FunctionBlockRow myCmd, S7FunctionBlock myBlk)
 {
     if (!string.IsNullOrEmpty(myCmd.Label))
     {
         return(true);
     }
     return(false);
 }
        public void ParseFunctionCodeBlocks()
        {
            //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 Simple Function-Code with some calls
            //An relatively simple block, a few segments ans calls to sub functions
            block = File.ReadAllBytes(dir + "FC1.bin");
            S7FunctionBlock FC = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.FC, FC.BlockType);
            Assert.AreEqual(1, FC.BlockNumber);
            Assert.AreEqual(434, FC.Length);             //Load memory Size
            Assert.AreEqual(342, FC.CodeSize);           //Code size of pure MC7
            Assert.AreEqual(6, FC.LocalDataSize);        //Actually there are no "Temp" but the local data is needed for the "Call"'s
            Assert.AreEqual(4, FC.Networks.Count);

            //Some of the called functions
            List <string> tmp = new List <string>(FC.CalledBlocks);

            Assert.AreEqual("FC96", tmp[2]);
            Assert.AreEqual("FC97", tmp[7]);
            Assert.AreEqual("FC16", tmp[11]);
            Assert.AreEqual("FC21", tmp[13]);

            Assert.AreEqual(File.ReadAllText(dir + "FC1.awl").Trim().Replace("\r\n", "\n"), FC.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read complex Function-code
            //Complex function with calls, Address-register manipulations, Indirect addressing of DB.
            //System functions, and lots of segments. AND indirect FC calls (Call FC[#tempvar])
            block = File.ReadAllBytes(dir + "FC100.bin");
            FC    = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.FC, FC.BlockType);
            Assert.AreEqual(100, FC.BlockNumber);
            Assert.AreEqual(4182, FC.Length);             //Load memory Size
            Assert.AreEqual(3882, FC.CodeSize);           //Code size of pure MC7
            Assert.AreEqual(58, FC.LocalDataSize);
            Assert.AreEqual(9, FC.Networks.Count);

            //Some of the called functions
            tmp = new List <string>(FC.CalledBlocks);
            Assert.AreEqual("SFC20", tmp[0]);
            Assert.AreEqual("FC6", tmp[6]);
            Assert.AreEqual("FC[LW16]", tmp[18]);
            Assert.AreEqual("SFC20", tmp[22]);

            Assert.AreEqual(File.ReadAllText(dir + "FC100.awl").Trim().Replace("\r\n", "\n"), FC.ToString().Trim().Replace("\r\n", "\n"));
        }
        public void ParseFunctionCodeBlocks()
        {
            byte[] block;

            //_____________________________________________________________________________
            //Read Simple Function-Code with some calls
            //An relatively simple block, a few segments ans calls to sub functions
            block = File.ReadAllBytes(dir + "FC1.bin");
            S7FunctionBlock FC = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.FC, FC.BlockType);
            Assert.AreEqual(1, FC.BlockNumber);
            Assert.AreEqual(434, FC.Length);             //Load memory Size
            Assert.AreEqual(342, FC.CodeSize);           //Code size of pure MC7
            Assert.AreEqual(6, FC.LocalDataSize);        //Actually there are no "Temp" but the local data is needed for the "Call"'s
            Assert.AreEqual(4, FC.Networks.Count);

            //Some of the called functions
            List <string> tmp = new List <string>(FC.CalledBlocks);

            Assert.AreEqual("FC96", tmp[2]);
            Assert.AreEqual("FC97", tmp[7]);
            Assert.AreEqual("FC16", tmp[11]);
            Assert.AreEqual("FC21", tmp[13]);

            Assert.AreEqual(File.ReadAllText(dir + "FC1.awl").Trim().Replace("\r\n", "\n"), FC.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read complex Function-code
            //Complex function with calls, Address-register manipulations, Indirect addressing of DB.
            //System functions, and lots of segments. AND indirect FC calls (Call FC[#tempvar])
            block = File.ReadAllBytes(dir + "FC100.bin");
            FC    = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.FC, FC.BlockType);
            Assert.AreEqual(100, FC.BlockNumber);
            Assert.AreEqual(4182, FC.Length);             //Load memory Size
            Assert.AreEqual(3882, FC.CodeSize);           //Code size of pure MC7
            Assert.AreEqual(58, FC.LocalDataSize);
            Assert.AreEqual(9, FC.Networks.Count);

            //Some of the called functions
            tmp = new List <string>(FC.CalledBlocks);
            Assert.AreEqual("SFC20", tmp[0]);
            Assert.AreEqual("FC6", tmp[6]);
            Assert.AreEqual("FC[LW16]", tmp[18]);
            Assert.AreEqual("SFC20", tmp[22]);

            Assert.AreEqual(File.ReadAllText(dir + "FC100.awl").Trim().Replace("\r\n", "\n"), FC.ToString().Trim().Replace("\r\n", "\n"));
        }
Exemple #5
0
        public void viewBlockStatus()
        {
            App.clientForm.lblStatus.Text = "";

            //myLst.sc

            if (myBlock is S7FunctionBlock)
            {
                try
                {
                    var visRow = getFirstVisbleExpandedItem();

                    int bytepos = 0;

                    if (visRow != null)
                    {
                        foreach (var row in ((S7FunctionBlock)myBlock).AWLCode)
                        {
                            if (visRow == row)
                            {
                                break;
                            }
                            bytepos += ((S7FunctionBlockRow)row).ByteSize;
                        }
                    }


                    S7FunctionBlock myS7Blk = (S7FunctionBlock)myBlock;
                    MyDiagnosticData = App.clientForm.Connection.PLCstartRequestDiagnosticData(myS7Blk, bytepos, S7FunctionBlockRow.SelectedStatusValues.ALL);

                    if (diagTimer == null)
                    {
                        diagTimer          = new DispatcherTimer(); // DispatcherTimer();
                        diagTimer.Tick    += new EventHandler(diagTimer_Tick);
                        diagTimer.Interval = new TimeSpan(0, 0, 0, 0, 40);
                    }
                    diagTimer.Start();
                }
                catch (Exception ex)
                {
                    App.clientForm.lblStatus.Text = ex.Message;
                    if (diagTimer != null)
                    {
                        diagTimer.Stop();
                        diagTimer = null;
                    }
                }
                //diagTimer.Start();
            }
        }
        public void ParseFunctionBlocks()
        {
            //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 Simple Function-Block without Instance data
            block = File.ReadAllBytes(dir + "FB101.bin");
            S7FunctionBlock FB = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.FB, FB.BlockType);
            Assert.AreEqual(101, FB.BlockNumber);
            Assert.AreEqual(128, FB.Length);             //Load memory Size
            Assert.AreEqual(24, FB.CodeSize);            //Code size of pure MC7
            Assert.AreEqual(4, FB.LocalDataSize);
            Assert.AreEqual(3, FB.Networks.Count);

            //Some of the called functions
            List <string> tmp = new List <string>(FB.CalledBlocks);

            Assert.AreEqual("FC100", tmp[0]);

            Assert.AreEqual(File.ReadAllText(dir + "FB101.awl").Trim().Replace("\r\n", "\n"), FB.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read Function-Block with Instance data
            block = File.ReadAllBytes(dir + "FB1001.bin");
            FB    = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, 0);

            Assert.AreEqual(PLCBlockType.FB, FB.BlockType);
            Assert.AreEqual(1001, FB.BlockNumber);
            Assert.AreEqual(126, FB.Length);             //Load memory Size
            Assert.AreEqual(22, FB.CodeSize);            //Code size of pure MC7
            Assert.AreEqual(0, FB.LocalDataSize);        //No temp data, all data is in STAT
            Assert.AreEqual(1, FB.Networks.Count);

            string t = FB.ToString();

            Assert.AreEqual(File.ReadAllText(dir + "FB1001.awl").Trim().Replace("\r\n", "\n"), FB.ToString().Trim().Replace("\r\n", "\n"));
        }
        public static void OptimizeAWL(S7FunctionBlock myPLCBlock, int akMemnoic)
        {
            int MN = 0;
            List <S7FunctionBlockRow> delLst = new List <S7FunctionBlockRow>();

            string akdb = "";

            for (int n = 0; n < myPLCBlock.AWLCode.Count; n++)
            //foreach (var myAkVal in myPLCBlock.AWLCode)
            {
                S7FunctionBlockRow myAkVal = (S7FunctionBlockRow)myPLCBlock.AWLCode[n];

                if (myAkVal.Command == Mnemonic.opNOP[MN] || myAkVal.Command == Mnemonic.opBLD[MN])
                {
                    if (myAkVal.Label == "")
                    {
                        delLst.Add(myAkVal);
                    }
                    else if (myAkVal.Label != "" && n < myPLCBlock.AWLCode.Count - 1 && myPLCBlock.AWLCode[n + 1].Label == "")
                    {
                        myPLCBlock.AWLCode[n + 1].Label = myAkVal.Label;
                        delLst.Add(myAkVal);
                    }
                }
                else if (myAkVal.Command == Mnemonic.opAUF[MN] && myAkVal.Label == "")
                {
                    if (akdb == myAkVal.Parameter && !akdb.Contains("[") && myAkVal.Label == "")
                    {
                        delLst.Add(myAkVal);
                    }
                    else
                    {
                        akdb = myAkVal.Parameter;
                    }
                }
                else if (myAkVal.Label != "" || myAkVal.Command == Mnemonic.opUC[akMemnoic] || myAkVal.Command == Mnemonic.opCC[akMemnoic]) //If there is a Jump or Call, reset the actual DB!
                {
                    akdb = "";
                }
            }
            foreach (var myAkVal in delLst)
            {
                myPLCBlock.AWLCode.Remove(myAkVal);
            }
        }
        public void ParseFunctionBlocks()
        {
            byte[] block;

            //_____________________________________________________________________________
            //Read Simple Function-Block without Instance data
            block = File.ReadAllBytes(dir + "FB101.bin");
            S7FunctionBlock FB = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.FB, FB.BlockType);
            Assert.AreEqual(101, FB.BlockNumber);
            Assert.AreEqual(128, FB.Length);             //Load memory Size
            Assert.AreEqual(24, FB.CodeSize);            //Code size of pure MC7
            Assert.AreEqual(4, FB.LocalDataSize);
            Assert.AreEqual(3, FB.Networks.Count);

            //Some of the called functions
            List <string> tmp = new List <string>(FB.CalledBlocks);

            Assert.AreEqual("FC100", tmp[0]);

            Assert.AreEqual(File.ReadAllText(dir + "FB101.awl").Trim().Replace("\r\n", "\n"), FB.ToString().Trim().Replace("\r\n", "\n"));

            //_____________________________________________________________________________
            //Read Function-Block with Instance data
            block = File.ReadAllBytes(dir + "FB1001.bin");
            FB    = (S7FunctionBlock)DotNetSiemensPLCToolBoxLibrary.PLCs.S7_xxx.MC7.MC7Converter.GetAWLBlock(block, MnemonicLanguage.German);

            Assert.AreEqual(PLCBlockType.FB, FB.BlockType);
            Assert.AreEqual(1001, FB.BlockNumber);
            Assert.AreEqual(126, FB.Length);             //Load memory Size
            Assert.AreEqual(22, FB.CodeSize);            //Code size of pure MC7
            Assert.AreEqual(0, FB.LocalDataSize);        //No temp data, all data is in STAT
            Assert.AreEqual(1, FB.Networks.Count);

            string t = FB.ToString();

            Assert.AreEqual(File.ReadAllText(dir + "FB1001.awl").Trim().Replace("\r\n", "\n"), FB.ToString().Trim().Replace("\r\n", "\n"));
        }
        //In this Class a UC is converted to a Call and also backwards...
        public static void ConvertUCToCall(S7FunctionBlock myFct, S7ProgrammFolder myFld, BlocksOfflineFolder myblkFld, S7ConvertingOptions myOpt, byte[] addInfoFromBlock)
        {
            if (myOpt.GenerateCallsfromUCs)
            {
                int inBld = 0; //1=nach BLD 1
                S7FunctionBlockRow newRow = null;

                Dictionary <string, string> Parameters = new Dictionary <string, string>();
                List <FunctionBlockRow>     retVal     = new List <FunctionBlockRow>();
                List <FunctionBlockRow>     tempList   = new List <FunctionBlockRow>();


                string registerDi    = "DI";
                string registerDb    = "";
                string registerAkku1 = "";
                string registerAkku2 = "";
                string registerAR1   = "";
                string registerAR2   = "";



                string  diName              = "";
                string  akPar               = "";
                string  db                  = "";
                string  label               = "";
                string  akku                = "";
                bool    afterCall           = false;
                bool    multiInstance       = false;
                int     multiInstanceOffset = 0;
                Pointer ar2Addr             = new Pointer(0, 0);

                S7FunctionBlockRow callRow = null;

                for (int n = 0; n < myFct.AWLCode.Count; n++)
                {
                    S7FunctionBlockRow row = (S7FunctionBlockRow)myFct.AWLCode[n];
                    if (row.Command == Mnemonic.opBLD[(int)myOpt.Mnemonic] && (row.Parameter == "1" || row.Parameter == "7" || row.Parameter == "3" || row.Parameter == "16" || row.Parameter == "14") && inBld == 0)
                    {
                        retVal.AddRange(tempList);
                        tempList.Clear();

                        Parameters.Clear();
                        db = "";

                        label = row.Label;

                        inBld     = Convert.ToInt32(row.Parameter);
                        newRow    = null;
                        afterCall = false;
                        callRow   = null;
                        diName    = "";

                        multiInstance       = false;
                        multiInstanceOffset = 0;
                        ar2Addr             = new Pointer(0, 0);

                        tempList.Add(row);
                    }
                    else if (inBld == 1 || inBld == 7)
                    {
                        #region FC Aufruf
                        tempList.Add(row);
                        if (row.Command == "=" && n > 0 && myFct.AWLCode[n - 1].Command == Mnemonic.opBLD[(int)myOpt.Mnemonic])
                        {
                            //Do nothing, but this line needs to be there!
                        }
                        else if (row.Command == Mnemonic.opU[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opUN[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opO[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opON[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opO[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opON[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opX[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opXN[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opL[(int)myOpt.Mnemonic])
                        {
                            akPar = row.Parameter;
                        }
                        else if (row.Command == Mnemonic.opAUF[(int)myOpt.Mnemonic])
                        {
                            db = row.Parameter + ".";
                        }
                        else if (row.Command == Mnemonic.opCLR[(int)myOpt.Mnemonic])
                        {
                            akPar = "FALSE";
                        }
                        else if (row.Command == Mnemonic.opSET[(int)myOpt.Mnemonic])
                        {
                            akPar = "TRUE";
                        }
                        else if (row.Command == Mnemonic.opTAR2[(int)myOpt.Mnemonic])
                        {
                            //look what we need to do here!!!
                        }
                        else if (row.Command == Mnemonic.opPAR2[(int)myOpt.Mnemonic])
                        {
                            //look what we need to do here!!!
                        }
                        else if (row.Command == Mnemonic.opLAR2[(int)myOpt.Mnemonic])
                        {
                            //look what we need to do here!!!
                        }
                        else if (row.Command == Mnemonic.opLAR1[(int)myOpt.Mnemonic])
                        {
                            //look what we need to do here!!!
                        }
                        else if ((row.Command == "=") && akPar != "")
                        {
                            if (afterCall == false)
                            {
                                string key = row.Parameter.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key, db + akPar);
                                }
                            }
                            else
                            {
                                string key = akPar.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key, db + row.Parameter);
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opT[(int)myOpt.Mnemonic] && akPar != "")
                        {
                            if (afterCall == false)
                            {
                                string key = row.Parameter.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");

                                //Fix for replace db accesses with symbols
                                if (myOpt.ReplaceDBAccessesWithSymbolNames && db != "")
                                {
                                    string dbnr     = db.Substring(0, db.Length - 1);
                                    string dbSymbol = Helper.TryGetSymbolFromOperand(myblkFld, dbnr);
                                    db    = (dbSymbol != null ? "\"" + dbSymbol + "\"" : dbnr) + ".";
                                    akPar = Helper.TryGetStructuredName(myblkFld, dbnr, akPar);
                                }
                                //end fix
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key + ".0", db + akPar);
                                }
                            }
                            else
                            {
                                string key = akPar.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey("P#V " + key))
                                {
                                    Parameters.Add("P#V " + key, db + row.Parameter);
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opT[(int)myOpt.Mnemonic] && akPar == "")
                        {
                            //look what we need to do here!!!
                        }
                        else if (row.Command == Mnemonic.opUC[(int)myOpt.Mnemonic])
                        {
                            //Commands after a Call --> Out-Para
                            callRow   = row;
                            afterCall = true;
                        }
                        else if (row.Command == Mnemonic.opBLD[(int)myOpt.Mnemonic] && (row.Parameter == "2" || row.Parameter == "8"))
                        {
                            //Block Interface auslesen (von FC oder vom Programm)
                            S7DataRow para = myblkFld.GetInterface(callRow.Parameter);

                            newRow               = new S7FunctionBlockRow();
                            newRow.Command       = Mnemonic.opCALL[(int)myOpt.Mnemonic];
                            newRow.Parent        = callRow.Parent;
                            newRow.Parameter     = callRow.Parameter;
                            newRow.CallParameter = new List <S7FunctionBlockParameter>();

                            for (int i = 0; i < callRow.ExtParameter.Count; i++)
                            {
                                string s = callRow.ExtParameter[i];

                                string    parnm = "";
                                S7DataRow akRow = Parameter.GetFunctionParameterFromNumber(para, i);
                                if (akRow != null)
                                {
                                    parnm = akRow.Name + "";
                                }
                                else
                                {
                                    parnm = "$$undef";
                                }


                                S7FunctionBlockParameter newPar = new S7FunctionBlockParameter(newRow);
                                newPar.Name = parnm;
                                if (akRow != null)
                                {
                                    newPar.ParameterDataType = akRow.DataType;
                                    if (akRow.Parent.Name == "OUT")
                                    {
                                        newPar.ParameterType = S7FunctionBlockParameterDirection.OUT;
                                    }
                                    else if (akRow.Parent.Name == "IN_OUT")
                                    {
                                        newPar.ParameterType = S7FunctionBlockParameterDirection.IN_OUT;
                                    }
                                    else
                                    {
                                        newPar.ParameterType = S7FunctionBlockParameterDirection.IN;
                                    }
                                }

                                if (akRow != null)
                                {
                                    int posL       = s.IndexOf(' ');
                                    int ak_address = 0;
                                    if (posL >= 0)
                                    {
                                        ak_address = Convert.ToInt32(s.Substring(posL + 1).Split('.')[0]);
                                    }
                                    else
                                    {
                                        ak_address = Convert.ToInt32(s.Substring(2).Split('.')[0]) * 8 +
                                                     Convert.ToInt32(s.Substring(2).Split('.')[1]);
                                    }

                                    int lokaldata_address = -1;
                                    if (s.Substring(0, 3) == "P#V")
                                    {
                                        lokaldata_address = Convert.ToInt32(s.Substring(4).Split('.')[0]);
                                    }

                                    if (akRow.DataType == S7DataRowType.STRING || akRow.DataType == S7DataRowType.DATE_AND_TIME ||
                                        akRow.DataType == S7DataRowType.STRUCT || akRow.DataType == S7DataRowType.UDT ||
                                        akRow.DataType == S7DataRowType.POINTER || akRow.IsArray)
                                    {
                                        string p1 = "";
                                        string p2 = "";
                                        Parameters.TryGetValue("P#V " + (lokaldata_address + 0).ToString() + ".0", out p1);
                                        Parameters.TryGetValue("P#V " + (lokaldata_address + 2).ToString() + ".0", out p2);


                                        string tmp = "";
                                        if (p1 != "" && p1 != "0")
                                        {
                                            tmp += "P#DB" + p1 + "." + (p2 == null ? "0" : p2.Substring(2));
                                        }
                                        else
                                        {
                                            tmp += p2;
                                        }
                                        newPar.Value = tmp;
                                        newRow.CallParameter.Add(newPar);
                                    }
                                    else if (akRow.DataType == S7DataRowType.ANY)
                                    {
                                        string tmp = s;
                                        if (Parameters.ContainsKey("P#V " + (lokaldata_address + 0).ToString() + ".0") &&
                                            Parameters.ContainsKey("P#V " + (lokaldata_address + 2).ToString() + ".0") &&
                                            Parameters.ContainsKey("P#V " + (lokaldata_address + 4).ToString() + ".0") &&
                                            Parameters.ContainsKey("P#V " + (lokaldata_address + 6).ToString() + ".0"))
                                        {
                                            string p1 = Parameters["P#V " + (lokaldata_address + 0).ToString() + ".0"];
                                            string p2 = Parameters["P#V " + (lokaldata_address + 2).ToString() + ".0"];
                                            string p3 = Parameters["P#V " + (lokaldata_address + 4).ToString() + ".0"];
                                            string p4 = Parameters["P#V " + (lokaldata_address + 6).ToString() + ".0"];

                                            //Fix for wrong construction of any pointers
                                            var anyPtr = new S7AnyPointer(p1, p2, p3, p4);
                                            if (myOpt.ReplaceDBAccessesWithSymbolNames)
                                            {
                                                //TODO: make the any pointer symbolic.
                                                tmp = "" + anyPtr.ToString();
                                            }
                                            else
                                            {
                                                tmp = anyPtr.ToString();
                                            }

                                            //end fix
                                            //tmp = "P#";
                                            //if (p3 != "0")
                                            //    tmp += "DB" + p3 + ".";
                                            //tmp += p4.Substring(2);
                                            //tmp += " BYTE "; //Todo Parse Byte 1 if the Type is Byte!
                                            //tmp += p2;
                                        }
                                        newPar.Value = tmp;
                                        newRow.CallParameter.Add(newPar);
                                    }
                                    else
                                    {
                                        if (Parameters.ContainsKey(s))
                                        {
                                            string par = Parameters[s];
                                            if (akRow.DataType == S7DataRowType.S5TIME && par[0] >= '0' && par[0] <= '9')
                                            {
                                                newPar.Value = Helper.GetS5Time(
                                                    BitConverter.GetBytes(Convert.ToInt32(par))[1],
                                                    BitConverter.GetBytes(Convert.ToInt32(par))[0]);
                                            }
                                            else if (akRow.DataType == S7DataRowType.TIME && par[0] >= '0' && par[0] <= '9')
                                            {
                                                newPar.Value = Helper.GetDTime(BitConverter.GetBytes(Convert.ToInt32(par)), 0);
                                            }
                                            else if (akRow.DataType == S7DataRowType.CHAR && par[0] == 'B')
                                            {
                                                newPar.Value = (char)Int32.Parse(par.Substring(5), System.Globalization.NumberStyles.AllowHexSpecifier) + "'";
                                            }
                                            else if (akRow.DataType == S7DataRowType.REAL)
                                            {
                                                var bt = new byte[4];
                                                libnodave.putS32at(bt, 0, Int32.Parse(par.Substring(2)));
                                                var real = libnodave.getFloatfrom(bt, 0);
                                                newPar.Value = real.ToString("e6", CultureInfo.InvariantCulture);
                                            }
                                            else
                                            {
                                                newPar.Value = Parameters[s];
                                            }
                                        }
                                        else
                                        {
                                            if (akRow.DataType == S7DataRowType.BOOL)
                                            {
                                                newPar.Value = s.Substring(2).Replace('V', 'L');
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_DB)
                                            {
                                                newPar.Value = "DB" + ak_address.ToString();
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_FB)
                                            {
                                                newPar.Value = "FB" + ak_address.ToString();
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_FC)
                                            {
                                                newPar.Value = "FC" + ak_address.ToString();
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_SDB)
                                            {
                                                newPar.Value = "SDB" + ak_address.ToString();
                                            }
                                            else if (akRow.DataType == S7DataRowType.TIMER)
                                            {
                                                newPar.Value = Mnemonic.adT[(int)myOpt.Mnemonic] + ak_address.ToString();
                                            }
                                            else if (akRow.DataType == S7DataRowType.COUNTER)
                                            {
                                                newPar.Value = Mnemonic.adZ[(int)myOpt.Mnemonic] + ak_address.ToString();
                                            }
                                            else
                                            {
                                                string ber = "";
                                                if (s.Substring(0, 5) == "P#DBX")
                                                {
                                                    ber = "DB";
                                                }
                                                else if (s.Substring(0, 5) == "P#DIX")
                                                {
                                                    ber = "DI";
                                                }
                                                else
                                                {
                                                    ber = s.Substring(2, 1);
                                                }

                                                if (akRow.ByteLength == 1)
                                                {
                                                    ber += "B";
                                                }
                                                else if (akRow.ByteLength == 2)
                                                {
                                                    ber += "W";
                                                }
                                                else if (akRow.ByteLength == 4)
                                                {
                                                    ber += "D";
                                                }

                                                var access = ber.Replace('V', 'L') + ak_address;

                                                //fix for temporary area not replaced with symbolnames
                                                if (myOpt.ReplaceLokalDataAddressesWithSymbolNames)
                                                {
                                                    var tempSymbol = S7DataRow.GetDataRowWithAddress(myFct.Parameter, new ByteBitAddress(ak_address, 0));
                                                    if (tempSymbol != null)
                                                    {
                                                        access = "#" + tempSymbol.StructuredName.Replace("TEMP.", "");
                                                    }
                                                }
                                                newPar.Value = access;
                                            }
                                        }

                                        newRow.CallParameter.Add(newPar);
                                    }
                                }
                            }

                            newRow.CombinedCommands = tempList;
                            newRow.Label            = label;

                            int sz = 0;
                            foreach (var functionBlockRow in newRow.CombinedCommands)
                            {
                                sz += ((S7FunctionBlockRow)functionBlockRow).ByteSize;
                            }
                            byte[] mcges = new byte[sz];
                            sz = 0;
                            foreach (var functionBlockRow in newRow.CombinedCommands)
                            {
                                Array.Copy(((S7FunctionBlockRow)functionBlockRow).MC7, 0, mcges, sz, ((S7FunctionBlockRow)functionBlockRow).ByteSize);
                                sz += ((S7FunctionBlockRow)functionBlockRow).ByteSize;
                            }
                            newRow.MC7 = mcges;

                            retVal.Add(newRow);
                            Parameters.Clear();
                            tempList = new List <FunctionBlockRow>();
                            inBld    = 0;

                            newRow = null;
                        }
                        else
                        {
                            retVal.AddRange(tempList);
                            tempList.Clear();

                            inBld = 0;
                        }
                        #endregion
                    }
                    else if (inBld == 3 || inBld == 16 || inBld == 14)
                    {
                        #region FB Aufruf
                        tempList.Add(row);
                        if (row.Command == "=" && n > 0 && myFct.AWLCode[n - 1].Command == Mnemonic.opBLD[(int)myOpt.Mnemonic])
                        {
                            //Do nothing, but this line needs to be there!
                        }
                        else if (row.Command == Mnemonic.opTDB[(int)myOpt.Mnemonic])
                        {
                            //Do nothing, but this line needs to be there!
                        }
                        else if (row.Command == Mnemonic.opBLD[(int)myOpt.Mnemonic] && row.Parameter == "11")
                        {
                            //whatever this BLD 11 in the FB Calls means...
                        }
                        else if (row.Command == Mnemonic.opTAR2[(int)myOpt.Mnemonic])
                        {
                            if (ar2Addr.MemoryArea == MemoryArea.None)
                            {
                                akPar = "P#DIX " + ar2Addr.ToString();
                            }
                            else
                            {
                                akPar = ar2Addr.ToString(myOpt.Mnemonic);
                            }
                        }
                        else if (row.Command == Mnemonic.opLAR2[(int)myOpt.Mnemonic])
                        {
                            if (row.Parameter.StartsWith("P#"))
                            {
                                ar2Addr = new Pointer(row.Parameter.Substring(2));
                            }
                            else
                            {
                                ar2Addr.ByteAddress = 0;
                                ar2Addr.BitAddress  = 0;
                            }
                        }
                        else if (row.Command == Mnemonic.opPAR2[(int)myOpt.Mnemonic])
                        {
                            ar2Addr += new Pointer(row.Parameter);
                        }
                        else if (row.Command == Mnemonic.opAUF[(int)myOpt.Mnemonic] && (tempList.Count == 4))
                        {
                            diName = row.Parameter;
                        }
                        else if (row.Command == Mnemonic.opAUF[(int)myOpt.Mnemonic] && row.Parameter.Contains("[") && (tempList.Count == 6))
                        {
                            multiInstance = true;

                            diName = "";
                        }
                        else if (row.Command == Mnemonic.opU[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opUN[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opO[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opON[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opO[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opON[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opX[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opXN[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opL[(int)myOpt.Mnemonic])
                        {
                            akPar = db + row.Parameter;
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opAUF[(int)myOpt.Mnemonic])
                        {
                            db = row.Parameter + ".";
                        }
                        else if (row.Command == "CLR")
                        {
                            akPar = "FALSE";
                        }
                        else if (row.Command == "SET")
                        {
                            akPar = "TRUE";
                        }
                        else if ((row.Command == "=") && akPar != "")
                        {
                            if (afterCall == false)
                            {
                                if (!Parameters.ContainsKey(row.Parameter))
                                {
                                    Parameters.Add(row.Parameter, akPar);
                                }
                            }
                            else
                            {
                                if (!Parameters.ContainsKey(akPar))
                                {
                                    Parameters.Add(akPar, row.Parameter);
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opT[(int)myOpt.Mnemonic] && akPar != "")
                        {
                            if (afterCall == false)
                            {
                                if (!Parameters.ContainsKey(row.Parameter))
                                {
                                    Parameters.Add(row.Parameter, akPar);
                                }
                            }
                            else
                            {
                                if (!Parameters.ContainsKey(akPar))
                                {
                                    Parameters.Add(akPar, row.Parameter);
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opT[(int)myOpt.Mnemonic])
                        {
                            if (afterCall == false)
                            {
                                if (!Parameters.ContainsKey(row.Parameter))
                                {
                                    Parameters.Add(row.Parameter, "");
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opUC[(int)myOpt.Mnemonic])
                        {
                            multiInstanceOffset = 0;
                            for (int j = tempList.Count - 2; j > -1; j--)
                            {
                                if (tempList[j].Command == Mnemonic.opPAR2[(int)myOpt.Mnemonic])
                                {
                                    multiInstanceOffset += (int)double.Parse((((S7FunctionBlockRow)tempList[j]).Parameter.Substring(2)), CultureInfo.InvariantCulture);
                                }
                                break;
                            }

                            //Commands after a Call --> Out-Para
                            callRow   = row;
                            afterCall = true;
                        }
                        else if (row.Command == Mnemonic.opBLD[(int)myOpt.Mnemonic] && (row.Parameter == "4" || row.Parameter == "17" || row.Parameter == "15"))
                        {
                            //Block Interface auslesen (von FC oder vom Programm)
                            S7DataRow para = myblkFld.GetInterface(callRow.Parameter);

                            newRow           = new S7FunctionBlockRow();
                            newRow.Parent    = callRow.Parent;
                            newRow.Command   = Mnemonic.opCALL[(int)myOpt.Mnemonic];
                            newRow.Parameter = callRow.Parameter;
                            if (diName.Length > 2 && !diName.StartsWith("#"))
                            {
                                newRow.DiName = "DI" + int.Parse(diName.Substring(2));
                            }
                            else if (diName.StartsWith("#"))
                            {
                                newRow.DiName = diName;
                            }
                            newRow.CallParameter = new List <S7FunctionBlockParameter>();


                            if (para != null)
                            {
                                var allPar = para.Children.Where(itm => itm.Name == "IN" || itm.Name == "IN_OUT" || itm.Name == "OUT");
                                foreach (var s7DataRowMain in allPar)
                                {
                                    foreach (var s7DataRow in s7DataRowMain.Children)
                                    {
                                        S7FunctionBlockParameter newPar = new S7FunctionBlockParameter(newRow);
                                        newPar.Name = s7DataRow.Name;

                                        string par = null;
                                        if (!multiInstance)
                                        {
                                            Parameters.TryGetValue(((S7DataRow)s7DataRow).BlockAddressInDbFormat.Replace("DB", "DI"), out par);
                                        }
                                        else if (((S7DataRow)s7DataRow).DataType == S7DataRowType.ANY)
                                        {
                                            var anySizeAddr = ((S7DataRow)s7DataRow).BlockAddress.ByteAddress + multiInstanceOffset + 2;
                                            var anyPosAddr  = ((S7DataRow)s7DataRow).BlockAddress.ByteAddress + multiInstanceOffset + 6;

                                            string anySize = "";
                                            string anyPos  = "";
                                            Parameters.TryGetValue("DIW[AR2,P#" + anySizeAddr + ".0]", out anySize);
                                            Parameters.TryGetValue("DID[AR2,P#" + anyPosAddr + ".0]", out anyPos);
                                            par = anyPos + " BYTE " + anySize;
                                        }
                                        else
                                        {
                                            var addr = ((S7DataRow)s7DataRow).BlockAddressInDbFormat;
                                            if (!string.IsNullOrEmpty(addr))
                                            {
                                                var    addrTp  = addr.Substring(0, 3).Replace("DB", "DI");
                                                double bytepos = double.Parse(addr.Substring(3), CultureInfo.InvariantCulture) + multiInstanceOffset;
                                                Parameters.TryGetValue(addrTp + "[AR2,P#" + bytepos.ToString("0.0", CultureInfo.InvariantCulture) + "]", out par);
                                            }
                                        }

                                        if (par != null && par.Contains("[AR2"))
                                        {
                                            newPar.Value = par;
                                            var addr = par.Substring(10);
                                            addr = addr.Substring(0, addr.Length - 1);
                                            var pRow = S7DataRow.GetDataRowWithAddress(myFct.Parameter.Children.Where(itm => itm.Name != "TEMP").Cast <S7DataRow>(), new ByteBitAddress(addr));
                                            if (pRow != null)
                                            {
                                                newPar.Value = ((S7DataRow)pRow).StructuredName.Substring(((S7DataRow)pRow).StructuredName.IndexOf('.') + 1);
                                            }
                                        }
                                        else
                                        {
                                            switch (((S7DataRow)s7DataRow).DataType)
                                            {
                                            case S7DataRowType.BLOCK_DB:
                                                newPar.Value = "DB" + par;
                                                break;

                                            case S7DataRowType.BLOCK_FC:
                                                newPar.Value = "FC" + par;
                                                break;

                                            case S7DataRowType.BLOCK_FB:
                                                newPar.Value = "FB" + par;
                                                break;

                                            case S7DataRowType.TIMER:
                                                newPar.Value = Mnemonic.adT[(int)myOpt.Mnemonic] + par.ToString();
                                                break;

                                            case S7DataRowType.COUNTER:
                                                newPar.Value = Mnemonic.adZ[(int)myOpt.Mnemonic] + par.ToString();
                                                break;

                                            case S7DataRowType.TIME:
                                                if (par != null && par.StartsWith("L#"))
                                                {
                                                    var arr = BitConverter.GetBytes(Convert.ToInt32(par.Substring(2)));
                                                    Array.Reverse(arr);
                                                    newPar.Value = Helper.GetDTime(arr, 0);
                                                }
                                                else
                                                {
                                                    newPar.Value = par;
                                                }
                                                break;

                                            default:
                                                newPar.Value = par;
                                                break;
                                            }
                                        }

                                        newRow.CallParameter.Add(newPar);
                                    }
                                }
                            }


                            newRow.CombinedCommands = tempList;
                            newRow.Label            = label;

                            int sz = 0;
                            foreach (var functionBlockRow in newRow.CombinedCommands)
                            {
                                sz += ((S7FunctionBlockRow)functionBlockRow).ByteSize;
                            }
                            byte[] mcges = new byte[sz];
                            sz = 0;
                            foreach (var functionBlockRow in newRow.CombinedCommands)
                            {
                                Array.Copy(((S7FunctionBlockRow)functionBlockRow).MC7, 0, mcges, sz, ((S7FunctionBlockRow)functionBlockRow).ByteSize);
                                sz += ((S7FunctionBlockRow)functionBlockRow).ByteSize;
                            }
                            newRow.MC7 = mcges;

                            retVal.Add(newRow);
                            Parameters.Clear();
                            tempList = new List <FunctionBlockRow>();
                            inBld    = 0;

                            newRow = null;
                        }
                        else
                        {
                            retVal.AddRange(tempList);
                            tempList.Clear();

                            inBld = 0;
                        }
                        #endregion
                    }
                    else
                    {
                        retVal.Add(row);
                    }
                }
                myFct.AWLCode = retVal;
            }
        }
        public static void ReplaceStaticAccess(S7FunctionBlock myFct, S7ProgrammFolder myFld, S7ConvertingOptions myOpt)
        {
            if (myOpt.ReplaceDIAccessesWithSymbolNames && myFct.BlockType == PLCBlockType.FB)
            {
                List <FunctionBlockRow> retVal   = new List <FunctionBlockRow>();
                List <FunctionBlockRow> tempList = new List <FunctionBlockRow>();

                bool LargeAccess = false;
                int  add_adresse = 0;

                foreach (var functionBlockRow in myFct.AWLCode)
                {
                    if (functionBlockRow.Command == "TAR2")
                    {
                        tempList.Add(functionBlockRow);
                        LargeAccess = true;
                    }
                    else if (functionBlockRow.Command == "+AR2" && LargeAccess)
                    {
                        tempList.Add(functionBlockRow);
                        add_adresse += Convert.ToInt32(Convert.ToDouble(((S7FunctionBlockRow)functionBlockRow).Parameter.Substring(2), new NumberFormatInfo()
                        {
                            NumberDecimalSeparator = "."
                        }));
                    }
                    else if (((S7FunctionBlockRow)functionBlockRow).Parameter.Contains("[AR2,P#") && ((S7FunctionBlockRow)functionBlockRow).Parameter.Substring(0, 2) == "DI" && !LargeAccess)
                    {
                        string         para   = ((S7FunctionBlockRow)functionBlockRow).Parameter;
                        ByteBitAddress adr    = new ByteBitAddress(para.Substring(10, para.Length - 11));
                        var            parRow = S7DataRow.GetDataRowWithAddress(myFct.Parameter, adr, true);
                        if (parRow != null)
                        {
                            byte[] tmp = ((S7FunctionBlockRow)functionBlockRow).MC7;
                            ((S7FunctionBlockRow)functionBlockRow).Parameter = "#" + parRow.StructuredName.Substring(parRow.StructuredName.IndexOf('.') + 1);
                            ((S7FunctionBlockRow)functionBlockRow).MC7       = tmp;
                        }
                        retVal.Add(functionBlockRow);
                    }
                    else if (((S7FunctionBlockRow)functionBlockRow).Parameter.Contains("[AR2,P#") && ((S7FunctionBlockRow)functionBlockRow).Parameter.Substring(0, 2) == "DI" && LargeAccess)
                    {
                        /*
                         * string para = ((S7FunctionBlockRow)functionBlockRow).Parameter;
                         * ByteBitAddress adr = new ByteBitAddress(para.Substring(10, para.Length - 11));
                         * adr.ByteAddress += add_adresse;
                         * var parRow = S7DataRow.GetDataRowWithAddress(myFct.Parameter, adr);
                         * if (parRow != null)
                         * {
                         *  byte[] tmp = ((S7FunctionBlockRow)functionBlockRow).MC7;
                         *  ((S7FunctionBlockRow)functionBlockRow).Parameter = "#" + parRow.StructuredName;
                         *  ((S7FunctionBlockRow)functionBlockRow).MC7 = tmp;
                         * }
                         * retVal.Add(functionBlockRow);
                         */
                        LargeAccess = false;
                    }
                    else if (functionBlockRow.Command == "LAR2")
                    {
                    }
                    else
                    {
                        LargeAccess = false;
                        retVal.AddRange(tempList);
                        tempList.Clear();
                        retVal.Add(functionBlockRow);
                    }
                }

                myFct.AWLCode = retVal;
            }
        }
Exemple #11
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());
        }
Exemple #12
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);
        }
        /// <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);
        }
Exemple #15
0
        //In this Class a UC is converted to a Call and also backwards...
        public static void ConvertUCToCall(S7FunctionBlock myFct, S7ProgrammFolder myFld, BlocksOfflineFolder myblkFld, S7ConvertingOptions myOpt, byte[] addInfoFromBlock)
        {
            if (myOpt.GenerateCallsfromUCs)
            {
                int inBld = 0; //1=nach BLD 1
                S7FunctionBlockRow newRow = null;

                Dictionary <string, string> Parameters = new Dictionary <string, string>();
                List <FunctionBlockRow>     retVal     = new List <FunctionBlockRow>();
                List <FunctionBlockRow>     tempList   = new List <FunctionBlockRow>();

                string             akPar     = "";
                string             db        = "";
                string             label     = "";
                bool               afterCall = false;
                S7FunctionBlockRow callRow   = null;

                for (int n = 0; n < myFct.AWLCode.Count; n++)
                {
                    S7FunctionBlockRow row = (S7FunctionBlockRow)myFct.AWLCode[n];
                    if (row.Command == Mnemonic.opBLD[(int)myOpt.Mnemonic] && (row.Parameter == "1" || row.Parameter == "7") && inBld == 0)
                    {
                        retVal.AddRange(tempList);
                        tempList.Clear();

                        Parameters.Clear();
                        db = "";

                        label = row.Label;

                        inBld     = Convert.ToInt32(row.Parameter);
                        newRow    = null;
                        afterCall = false;
                        callRow   = null;
                        tempList.Add(row);
                    }
                    else if (inBld > 0)
                    {
                        tempList.Add(row);
                        if (row.Command == "=" && n > 0 && myFct.AWLCode[n - 1].Command == Mnemonic.opBLD[(int)myOpt.Mnemonic])
                        {
                            //Do nothing, but this line needs to be there!
                        }
                        else if (row.Command == Mnemonic.opU[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opUN[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opO[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opON[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opO[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opON[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opX[(int)myOpt.Mnemonic] || row.Command == Mnemonic.opXN[(int)myOpt.Mnemonic] ||
                                 row.Command == Mnemonic.opL[(int)myOpt.Mnemonic])
                        {
                            akPar = row.Parameter;
                        }
                        else if (row.Command == "AUF")
                        {
                            db = row.Parameter + ".";
                        }
                        else if (row.Command == "CLR")
                        {
                            akPar = "FALSE";
                        }
                        else if (row.Command == "SET")
                        {
                            akPar = "TRUE";
                        }
                        else if ((row.Command == "=") && akPar != "")
                        {
                            if (afterCall == false)
                            {
                                string key = row.Parameter.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key, db + akPar);
                                }
                            }
                            else
                            {
                                string key = akPar.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key, db + row.Parameter);
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opT[(int)myOpt.Mnemonic] && akPar != "")
                        {
                            if (afterCall == false)
                            {
                                string key = row.Parameter.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key + ".0", db + akPar);
                                }
                            }
                            else
                            {
                                string key = akPar.Replace("L", "").Replace("W", "").Replace("B", "").Replace("D", "");
                                if (!Parameters.ContainsKey(key))
                                {
                                    Parameters.Add("P#V " + key, db + row.Parameter);
                                }
                            }
                            akPar = "";
                            db    = "";
                        }
                        else if (row.Command == Mnemonic.opUC[(int)myOpt.Mnemonic])
                        {
                            //Commands after a Call --> Out-Para
                            callRow   = row;
                            afterCall = true;
                        }
                        else if (row.Command == Mnemonic.opBLD[(int)myOpt.Mnemonic] && (row.Parameter == "2" || row.Parameter == "8"))
                        {
                            //Block Interface auslesen (von FC oder vom Programm)
                            //myFld.BlocksOfflineFolder.GetBlock()
                            S7DataRow para = myblkFld.GetInterface(callRow.Parameter);

                            newRow           = new S7FunctionBlockRow();
                            newRow.Command   = Mnemonic.opCALL[(int)myOpt.Mnemonic];
                            newRow.Parameter = callRow.Parameter;
                            //newRow.ExtParameter = new List<string>();
                            newRow.CallParameter = new List <S7FunctionBlockParameter>();

                            for (int i = 0; i < callRow.ExtParameter.Count; i++)
                            {
                                string s = callRow.ExtParameter[i];

                                string    parnm = "";
                                S7DataRow akRow = Parameter.GetFunctionParameterFromNumber(para, i);
                                if (akRow != null)
                                {
                                    parnm = akRow.Name + "";
                                }
                                else
                                {
                                    parnm = "$$undef";
                                }


                                S7FunctionBlockParameter newPar = new S7FunctionBlockParameter();
                                newPar.Name = parnm;
                                if (akRow != null)
                                {
                                    newPar.ParameterDataType = akRow.DataType;
                                    if (akRow.Parent.Name == "OUT")
                                    {
                                        newPar.ParameterType = S7FunctionBlockParameterDirection.OUT;
                                    }
                                    else if (akRow.Parent.Name == "IN_OUT")
                                    {
                                        newPar.ParameterType = S7FunctionBlockParameterDirection.IN_OUT;
                                    }
                                    else
                                    {
                                        newPar.ParameterType = S7FunctionBlockParameterDirection.IN;
                                    }
                                    //newPar.ParameterType
                                }

                                if (akRow != null)
                                {
                                    int posL       = s.IndexOf(' ');
                                    int ak_address = 0;
                                    if (posL >= 0)
                                    {
                                        ak_address = Convert.ToInt32(s.Substring(posL + 1).Split('.')[0]);
                                    }
                                    else
                                    {
                                        ak_address = Convert.ToInt32(s.Substring(2).Split('.')[0]) * 8 +
                                                     Convert.ToInt32(s.Substring(2).Split('.')[1]);
                                    }

                                    int lokaldata_address = -1;
                                    if (s.Substring(0, 3) == "P#V")
                                    {
                                        lokaldata_address = Convert.ToInt32(s.Substring(4).Split('.')[0]);
                                    }

                                    if (akRow.DataType == S7DataRowType.STRING || akRow.DataType == S7DataRowType.DATE_AND_TIME ||
                                        akRow.DataType == S7DataRowType.STRUCT || akRow.DataType == S7DataRowType.UDT ||
                                        akRow.DataType == S7DataRowType.POINTER || akRow.IsArray)
                                    {
                                        string p1 = Parameters["P#V " + (lokaldata_address + 0).ToString() + ".0"];
                                        string p2 = Parameters["P#V " + (lokaldata_address + 2).ToString() + ".0"];


                                        string tmp = "";
                                        if (p1 != "" && p1 != "0")
                                        {
                                            tmp += "P#DB" + p1 + "." + p2.Substring(2);
                                        }
                                        else
                                        {
                                            tmp += p2;
                                        }
                                        newPar.Value = tmp;
                                        newRow.CallParameter.Add(newPar);
                                        //newRow.ExtParameter.Add(parnm + tmp);
                                    }
                                    else if (akRow.DataType == S7DataRowType.ANY)
                                    {
                                        string tmp = s;
                                        if (Parameters.ContainsKey("P#V " + (lokaldata_address + 0).ToString() + ".0") &&
                                            Parameters.ContainsKey("P#V " + (lokaldata_address + 2).ToString() + ".0") &&
                                            Parameters.ContainsKey("P#V " + (lokaldata_address + 4).ToString() + ".0") &&
                                            Parameters.ContainsKey("P#V " + (lokaldata_address + 6).ToString() + ".0"))
                                        {
                                            string p1 = Parameters["P#V " + (lokaldata_address + 0).ToString() + ".0"];
                                            string p2 = Parameters["P#V " + (lokaldata_address + 2).ToString() + ".0"];
                                            string p3 = Parameters["P#V " + (lokaldata_address + 4).ToString() + ".0"];
                                            string p4 = Parameters["P#V " + (lokaldata_address + 6).ToString() + ".0"];

                                            tmp = "P#";
                                            if (p3 != "0")
                                            {
                                                tmp += "DB" + p3 + ".";
                                            }
                                            tmp += p4.Substring(2);
                                            tmp += " BYTE "; //Todo Parse Byte 1 if the Type is Byte!
                                            tmp += p2;
                                        }
                                        newPar.Value = tmp;
                                        newRow.CallParameter.Add(newPar);
                                        //newRow.ExtParameter.Add(parnm + tmp);
                                    }
                                    else
                                    {
                                        if (Parameters.ContainsKey(s))
                                        {
                                            string par = Parameters[s];
                                            if (akRow.DataType == S7DataRowType.S5TIME && par[0] >= '0' && par[0] <= '9')
                                            {
                                                newPar.Value = Helper.GetS5Time(
                                                    BitConverter.GetBytes(Convert.ToInt32(par))[1],
                                                    BitConverter.GetBytes(Convert.ToInt32(par))[0]);
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm +
                                                //                        Helper.GetS5Time(
                                                //                            BitConverter.GetBytes(Convert.ToInt32(par))[1],
                                                //                            BitConverter.GetBytes(Convert.ToInt32(par))[0]));
                                            }
                                            else if (akRow.DataType == S7DataRowType.TIME && par[0] >= '0' && par[0] <= '9')
                                            {
                                                newPar.Value = Helper.GetDTime(BitConverter.GetBytes(Convert.ToInt32(par)), 0);
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm +
                                                //                        Helper.GetDTime(BitConverter.GetBytes(Convert.ToInt32(par)),0));
                                            }
                                            else if (akRow.DataType == S7DataRowType.CHAR && par[0] == 'B')
                                            {
                                                newPar.Value =
                                                    (char)
                                                    Int32.Parse(par.Substring(5),
                                                                System.Globalization.NumberStyles.AllowHexSpecifier) +
                                                    "'";
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm + "'" +
                                                //                        (char)Int32.Parse(par.Substring(5), System.Globalization.NumberStyles.AllowHexSpecifier) + "'");
                                            }
                                            else
                                            {
                                                newPar.Value = Parameters[s];
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm + Parameters[s]);
                                            }
                                        }
                                        else
                                        {
                                            if (akRow.DataType == S7DataRowType.BOOL)
                                            {
                                                newPar.Value = s.Substring(2).Replace('V', 'L');
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm + s.Substring(2).Replace('V', 'L'));
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_DB)
                                            {
                                                newPar.Value = "DB" + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm + "DB" + ak_address.ToString());
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_FB)
                                            {
                                                newPar.Value = "FB" + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm + "FB" + ak_address.ToString());
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_FC)
                                            {
                                                newPar.Value = "FC" + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                            }
                                            else if (akRow.DataType == S7DataRowType.BLOCK_SDB)
                                            {
                                                newPar.Value = "SDB" + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                            }
                                            else if (akRow.DataType == S7DataRowType.TIMER)
                                            {
                                                newPar.Value = Mnemonic.adT[(int)myOpt.Mnemonic] + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                            }
                                            else if (akRow.DataType == S7DataRowType.COUNTER)
                                            {
                                                newPar.Value = Mnemonic.adZ[(int)myOpt.Mnemonic] + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                            }
                                            else
                                            {
                                                string ber = "";
                                                if (s.Substring(0, 5) == "P#DBX")
                                                {
                                                    ber = "DB";
                                                }
                                                else if (s.Substring(0, 5) == "P#DIX")
                                                {
                                                    ber = "DI";
                                                }
                                                else
                                                {
                                                    ber = s.Substring(2, 1);
                                                }

                                                if (akRow.ByteLength == 1)
                                                {
                                                    ber += "B";
                                                }
                                                else if (akRow.ByteLength == 2)
                                                {
                                                    ber += "W";
                                                }
                                                else if (akRow.ByteLength == 4)
                                                {
                                                    ber += "D";
                                                }

                                                newPar.Value = ber.Replace('V', 'L') + ak_address.ToString();
                                                newRow.CallParameter.Add(newPar);
                                                //newRow.ExtParameter.Add(parnm +
                                                //                        ber.Replace('V', 'L') +
                                                //                        ak_address.ToString());
                                            }
                                        }
                                    }
                                }
                            }

                            newRow.CombinedCommands = tempList;
                            newRow.Label            = label;

                            int sz = 0;
                            foreach (var functionBlockRow in newRow.CombinedCommands)
                            {
                                sz += ((S7FunctionBlockRow)functionBlockRow).ByteSize;
                            }
                            byte[] mcges = new byte[sz];
                            sz = 0;
                            foreach (var functionBlockRow in newRow.CombinedCommands)
                            {
                                Array.Copy(((S7FunctionBlockRow)functionBlockRow).MC7, 0, mcges, sz, ((S7FunctionBlockRow)functionBlockRow).ByteSize);
                                sz += ((S7FunctionBlockRow)functionBlockRow).ByteSize;
                            }
                            newRow.MC7 = mcges;

                            retVal.Add(newRow);
                            Parameters.Clear();
                            tempList = new List <FunctionBlockRow>();
                            inBld    = 0;
                        }
                        else
                        {
                            retVal.AddRange(tempList);
                            tempList.Clear();

                            inBld = 0;
                        }
                    }
                    else
                    {
                        retVal.Add(row);
                    }
                }
                myFct.AWLCode = retVal;
            }
        }
        public static void ConvertLocaldataToSymbols(S7FunctionBlock myFct, S7ConvertingOptions myOpt)
        {
            if (myOpt.ReplaceLokalDataAddressesWithSymbolNames)
            {
                List <S7DataRow>            rows   = null;
                Dictionary <String, String> parLst = new Dictionary <string, string>();

                if (myFct.Parameter != null && myFct.Parameter.Children != null)
                {
                    foreach (var plcDataRow in myFct.Parameter.Children)
                    {
                        if (plcDataRow.Name == "TEMP")
                        {
                            S7DataRow tmpRw = ((S7DataRow)plcDataRow)._GetExpandedChlidren(new S7DataBlockExpandOptions()
                            {
                                ExpandCharArrays = true, ExpandSubChildInINOUT = false
                            })[0];
                            rows = S7DataRow.GetChildrowsAsList(tmpRw);
                            break;
                        }
                    }
                }

                if (rows != null)
                {
                    foreach (var plcDataRow in rows)
                    {
                        if (plcDataRow.DataType != S7DataRowType.STRUCT && plcDataRow.DataType != S7DataRowType.UDT && plcDataRow.DataType != S7DataRowType.FB)
                        {
                            parLst.Add("P#L" + plcDataRow.BlockAddress.ToString(), "P##" + plcDataRow.StructuredName);
                        }
                        string tmp = plcDataRow.GetSymbolicAddress();
                        if (tmp != null)
                        {
                            parLst.Add("L" + tmp.Replace("X", ""), "#" + plcDataRow.StructuredName);
                        }
                    }
                }
                foreach (S7FunctionBlockRow plcFunctionBlockRow in myFct.AWLCode)
                {
                    if (!plcFunctionBlockRow.Parameter.Contains("'") && !plcFunctionBlockRow.Parameter.Contains("[AR") && plcFunctionBlockRow.Parameter.Contains("["))
                    {
                        int    pos1 = plcFunctionBlockRow.Parameter.IndexOf("[") + 1;
                        int    pos2 = plcFunctionBlockRow.Parameter.IndexOf("]");
                        string par  = plcFunctionBlockRow.Parameter.Substring(pos1, pos2 - pos1);
                        if (parLst.ContainsKey(par))
                        {
                            byte[] tmp = plcFunctionBlockRow.MC7;
                            plcFunctionBlockRow.Parameter = plcFunctionBlockRow.Parameter.Substring(0, pos1) + parLst[par] + "]";
                            plcFunctionBlockRow.MC7       = tmp;
                        }
                    }
                    else
                    {
                        string par = plcFunctionBlockRow.Parameter.Replace(" ", "");
                        if (parLst.ContainsKey(par))
                        {
                            byte[] tmp = plcFunctionBlockRow.MC7;
                            plcFunctionBlockRow.Parameter = "";

                            plcFunctionBlockRow.Parameter = parLst[par];

                            plcFunctionBlockRow.MC7 = tmp;
                        }
                    }
                }
            }
        }
Exemple #17
0
        static public List <S7FunctionBlockRow> GenerateFBParameterUsesFromAR2Calls(S7FunctionBlock myBlk, int Memnoic)
        {
            List <S7FunctionBlockRow> retVal = new List <S7FunctionBlockRow>();

            //In this list the Values are stored when we try to combine them,
            //when we are succesfull, this list is cleard, when not, it is added to the retVal
            List <S7FunctionBlockRow> tmpVal = new List <S7FunctionBlockRow>();

            //if the command is a TAR xx this will be set!
            int combineStep = 0;

            int byteaddr = 0;
            int bitaddr  = 0;

            string TarLdTarget = "";

            /* Todo: Converting FB Commands to Access to Static Data
             *
             * Like:
             *
             *   TAR2  LD1           This is done, wehen the static address gets to high!
             +AR2  P#4090.0      so the ar2 is saved, then increased and the it loads the data.
             +AR2  P#4090.0      later ar2 is saved back!
             *   L     DID[AR2,P#1840.0]
             *   LAR2  LD1
             *
             *
             * or:
             *   TAR2  LD1
             +AR2  P#4090.0
             +AR2  P#4090.0
             *   U     DIX[AR2,P#1838.0]
             *   LAR2  LD1
             * or a simple one:
             * L     DID[AR2,P#294.0]   should be:  L #blabla (wher blabla is static data at 294)
             */

            //Check if Command is a TAR to LokalData, wich is not defined in the Interface
            //If next command is a + stor the address
            //if next command contains [ar2,xx) add the stored vakue to xx
            //and change the whole command to the parameter if there is a matching one
            //check if command is a lar2 from the lokaldata used before
            //if not role back!

            foreach (S7FunctionBlockRow plcFunctionBlockRow in myBlk.AWLCode)
            {
                if (plcFunctionBlockRow.Command == MC7.Mnemonic.opTAR2[Memnoic] && plcFunctionBlockRow.Parameter.Contains("LD"))
                {
                    retVal.AddRange(tmpVal);
                    tmpVal.Clear();
                    tmpVal.Add(plcFunctionBlockRow);
                    combineStep = 1;
                    byteaddr    = 0;
                    bitaddr     = 0;
                    TarLdTarget = plcFunctionBlockRow.Parameter;
                }
                else if (combineStep == 1 && plcFunctionBlockRow.Command == MC7.Mnemonic.opPAR2[Memnoic])
                {
                    tmpVal.Add(plcFunctionBlockRow);
                    byteaddr = Convert.ToInt32(plcFunctionBlockRow.Parameter.Split(new char[] { '#' })[1]);
                }
                else if (combineStep == 1 && plcFunctionBlockRow.Parameter.Contains("[AR2,P#"))
                {
                    tmpVal.Add(plcFunctionBlockRow);
                    combineStep = 2;
                }
                else if (
                    (combineStep == 2 && plcFunctionBlockRow.Command == MC7.Mnemonic.opLAR2[Memnoic] && plcFunctionBlockRow.Parameter == TarLdTarget) ||
                    (combineStep == 0 && plcFunctionBlockRow.Parameter.Contains("[AR2,P#"))
                    )
                {
                    //OK we commbined the command sucessfully, add the new command, delete the old ones...
                    //And add the Byte Sequence from the old commands to the new.
                    List <byte> bytes = new List <byte>();

                    foreach (S7FunctionBlockRow tmpFunctionBlockRow in tmpVal)
                    {
                        bytes.AddRange(tmpFunctionBlockRow.MC7);
                    }

                    retVal.Add(new S7FunctionBlockRow()
                    {
                        MC7 = bytes.ToArray()
                    });

                    tmpVal.Clear();
                    combineStep = 0;
                }
                else
                {
                    retVal.AddRange(tmpVal);
                    tmpVal.Clear();
                    retVal.Add(plcFunctionBlockRow);
                    combineStep = 0;
                }
            }

            return(retVal);
        }