private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                PLCConnection myConn = new PLCConnection(lstConnections.SelectedItem.ToString());
                myConn.Connect();

                int anz  = readBytes.Length / Convert.ToInt32(txtSize.Text);
                int olen = Convert.ToInt32(txtSize.Text);
                int len  = Convert.ToInt32(txtNewSize.Text);

                for (int n = 0; n < anz; n++)
                {
                    PLCTag plcTag = new PLCTag()
                    {
                        TagDataType = TagDataType.ByteArray, TagDataSource = MemoryArea.Datablock, DataBlockNumber = Convert.ToInt32(txtDB.Text), ByteAddress = Convert.ToInt32(txtStartByte.Text) + n * Convert.ToInt32(txtNewSize.Text), ArraySize = Convert.ToInt32(txtSize.Text)
                    };

                    byte[] ctrlV = new byte[len];
                    Array.Copy(readBytes, olen * n, ctrlV, 0, olen);
                    plcTag.Controlvalue = ctrlV;

                    myConn.WriteValue(plcTag);
                }
                lblState.Text = anz.ToString() + " Strukturen a " + len.ToString() + " Bytes geschrieben!";
            }
            catch (Exception ex)
            {
                lblState.Text = ex.Message;
            }
        }
Example #2
0
 static void Main(string[] args)
 {
     if (args.Length > 0)
     {
         if (args[0] == "/config" || args[0] == "-config" || args[0] == "--config")
         {
             Configuration.ShowConfiguration("CommandWhenBitSetConn", true);
         }
     }
     else
     {
         try
         {
             PLCConnection myConn = new PLCConnection("CommandWhenBitSetConn");
             myConn.Connect();
             PLCTag tag = new PLCTag(Settings.Default.PLCVar);
             myConn.ReadValue(tag);
             if ((bool)tag.Value == true)
             {
                 Process P = new Process();
                 P.StartInfo.FileName  = Settings.Default.CommandToRun;
                 P.StartInfo.Arguments = Settings.Default.CommandToRun;
                 P.Start();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
 }
Example #3
0
        private void button4_Click(object sender, EventArgs e)
        {
            myConn = new PLCConnection("SimpleCSharpDemonstrationConnection");
            myConn.Connect();


            //var _tags = new List<PLCTag>();
            //var j = 0;
            //for (var i = 0; i < 96; i++)
            //{
            //    Console.WriteLine("DB1.DBD" + j.ToString(CultureInfo.InvariantCulture));
            //    _tags.Add(new PLCTag("DB1.DBD" + j.ToString(CultureInfo.InvariantCulture))
            //        {
            //            TagDataType = TagDataType.Float
            //        });
            //    j += 4;
            //}
            //myConn.ReadValues(_tags, false);

            var tag = new PLCTag();

            tag.TagDataType       = TagDataType.Word;
            tag.SymbolicAccessKey = "8a0e000124134d054000000a";
            myConn.ReadValue(tag);

            /*tag.Controlvalue = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 88, 1, 2, 3, 4, 5, 6, 7, 8, 9, 77 };
             * myConn.WriteValue(tag);
             * var db = myConn.PLCGetBlockInMC7("DB99");
             * MessageBox.Show("DB:" + Encoding.ASCII.GetString(db));
             * myConn.PLCPutBlockFromMC7toPLC("DB98", db);*/
        }
Example #4
0
        /// <summary>
        /// Implementazione esecuzione comando di richiesta lista plctags sotoscritti
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetSubscribedPLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;
            var  tagslist = new List <PLCTag>();

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            // gestione subscriptions
            if (!_Subs.ContainsKey(Message.SourceApplicationName))
            {
                Logger.WarnFormat("[{0}] has no subscriptions", Message.SourceApplicationName);
                RetValue = false;
            }
            else
            {
                // costruisco la lista da inviare come risposta
                foreach (var sub in _Subs[Message.SourceApplicationName].ToList())
                {
                    var tag = new PLCTag()
                    {
                        PLCName = sub.PLCName, Address = sub.TagAddress, Validation = true
                    };
                    tagslist.Add(tag);
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.SubscribedPLCTags, new PLCTagsData()
            {
                MsgCode = MsgCodes.SubscribedPLCTags, Tags = tagslist
            }, RetValue));
        }
        private void ThreadProc()
        {
            PLCTag tag = new PLCTag(triggerBit);

            while (threadShouldRun)
            {
                myConn.ReadValue(tag);

                if ((bool)tag.Value == true)
                {
                    PLCTag writeData = new PLCTag();
                    writeData.TagDataType     = TagDataType.CharArray;
                    writeData.DataBlockNumber = writeDB;
                    writeData.ArraySize       = writeCharArraySize;

                    string writeDataString = "";
                    using (StreamReader sr = new StreamReader(csvFile))
                    {
                        writeDataString = sr.ReadToEnd();
                    }
                    writeData.Controlvalue = writeDataString;

                    //Reset the Bit
                    tag.Controlvalue = false;

                    myConn.WriteValues(new[] { writeData, tag });
                }

                Thread.Sleep(20);
            }
        }
Example #6
0
        /// <summary>
        /// Impostazione valore plctag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool SetPLCTag(PLCTag tag)
        {
            bool RetValue = true;

            /* verifico connessione/esistenza PLC interessato */
            if (!_PLCs.ContainsKey(tag.PLCName))
            {
                // log
                Logger.WarnFormat("PLC [{0}] not connected", tag.PLCName);

                RetValue = false;
            }
            else
            {
                try
                {
                    /* scrivo tag */
                    var plctag = new S7NetWrapper.Tag(tag.Address, tag.Value);
                    _PLCs[tag.PLCName].Write(plctag);
                }
                catch (Exception exc)
                {
                    // log
                    Logger.WarnFormat("PLC [{0}] error writing tag {1} : {2}", tag.PLCName, tag.Address, exc.Message);
                    RetValue = false;
                }
            }
            return(RetValue);
        }
Example #7
0
        /// <summary>
        /// Lettura valore plctag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetPLCTag(ref PLCTag tag)
        {
            bool RetValue = true;

            /* verifico connessione/esistenza PLC interessato */
            if (!_PLCs.ContainsKey(tag.PLCName))
            {
                // log
                Logger.WarnFormat("PLC [{0}] not connected", tag.PLCName);

                RetValue = false;
            }
            else
            {
                try
                {
                    /* leggo tag value*/
                    var plctag = _PLCs[tag.PLCName].Read(new S7NetWrapper.Tag(tag.Address));
                    if (plctag != null)
                    {
                        tag.Value = plctag.ItemValue;
                    }
                }
                catch (Exception exc)
                {
                    // log
                    Logger.WarnFormat("PLC [{0}] error reading tag {1} : {2}", tag.PLCName, tag.Address, exc.Message);
                    RetValue = false;
                }
            }

            return(RetValue);
        }
Example #8
0
        private void cmdReadValuesWithvarTab_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Achtung: Es können hier nur rund 200 Bytes gelesen werden, aber die länge wird noch nicht geprüft! Und es wird nur die Zeit zum lesen, nicht die zum starten der Anfrage gemessen!");
            try
            {
                txtWert.Text   = "";
                txtZeit.Text   = "";
                lblStatus.Text = "";

                if (myConn == null)
                {
                    cmdConnect_Click(sender, e);
                }

                PLCTag myTag = new PLCTag(txtTag.Text);

                List <PLCTag> tagList = new List <PLCTag>()
                {
                    myTag
                };

                var       read = myConn.ReadValuesWithVarTabFunctions(tagList, PLCTriggerVarTab.BeginOfCycle);
                Stopwatch sw   = new Stopwatch();
                sw.Start();
                read.RequestData();
                sw.Stop();

                txtZeit.Text = sw.ElapsedMilliseconds.ToString() + " ms";
                txtWert.Text = myTag.ValueAsString;
            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
            }
        }
Example #9
0
        private void cmdReadWithReadValues_Click(object sender, EventArgs e)
        {
            try
            {
                txtWert.Text   = "";
                txtZeit.Text   = "";
                lblStatus.Text = "";

                if (myConn == null)
                {
                    cmdConnect_Click(sender, e);
                }

                PLCTag myTag = new PLCTag(txtTag.Text);

                List <PLCTag> tagList = new List <PLCTag>()
                {
                    myTag
                };

                Stopwatch sw = new Stopwatch();
                sw.Start();
                myConn.ReadValues(tagList);
                sw.Stop();

                txtZeit.Text = sw.ElapsedMilliseconds.ToString() + " ms";
                txtWert.Text = myTag.ValueAsString;
            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
            }
        }
        public void ReadValue(PLCTag tag)
        {
            var telHead = new byte[] { (byte)'S', (byte)'5', 16, 1, 3, 5, 3, 8, PLCConnectionID, (byte)tag.DatablockNumber, 0, 0, 0, 0, 0xff, 2 };
            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ByteAddress);
            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ReadByteSize);

            tcp.SendData(telHead);
        }
        public void ReadValue(PLCTag tag)
        {
            var telHead = new byte[] { (byte)'S', (byte)'5', 16, 1, 3, 5, 3, 8, PLCConnectionID, (byte)tag.DatablockNumber, 0, 0, 0, 0, 0xff, 2 };

            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ByteAddress);
            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ReadByteSize);

            tcp.SendData(telHead);
        }
Example #12
0
        public void TestEnumTag2()
        {
            var t = new PLCTag <Test2>();

            t.GenericValue = Test2.a;
            var wr = t.GenericValue;

            t._setValueProp = 1;
            var wr2 = t.GenericValue;
        }
Example #13
0
        public void TestEnumTag3()
        {
            var t = new PLCTag <Test1>("MW10", TagDataType.Int);

            t.GenericValue = Test1.a;
            var wr = t.GenericValue;

            t._setValueProp = (short)1;
            var wr2 = t.GenericValue;
        }
        public void WriteValue(PLCTag tag)
        {
            var telHead = new byte[] { (byte)'S', (byte)'5', 16, 1, 3, 3, 3, 8, PLCConnectionID, (byte)tag.DatablockNumber, 0, 0, 0, 0, 0xff, 2 };
            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ByteAddress);
            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ReadByteSize);

            var tel = new byte[telHead.Length + tag.ReadByteSize];

            Array.Copy(telHead, 0, tel, 0, telHead.Length);
        }
        public void WriteValue(PLCTag tag)
        {
            var telHead = new byte[] { (byte)'S', (byte)'5', 16, 1, 3, 3, 3, 8, PLCConnectionID, (byte)tag.DatablockNumber, 0, 0, 0, 0, 0xff, 2 };

            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ByteAddress);
            LibNoDave.libnodave.putBCD16at(telHead, 10, tag.ReadByteSize);

            var tel = new byte[telHead.Length + tag.ReadByteSize];

            Array.Copy(telHead, 0, tel, 0, telHead.Length);
        }
        //This selects a Tag From a Step 7 Project
        public static PLCTag SelectTAG(string FileAndProjectInternalFolder, bool hideOpenProjectButton = true)
        {
            SelectProjectPartForm myFrm = new SelectProjectPartForm(FileAndProjectInternalFolder, hideOpenProjectButton);

            myFrm.SelectPart = SelectPartType.Tag;
            myFrm.ShowDialog();
            PLCTag retVal = (PLCTag)myFrm.retVal;

            myFrm.Close();
            myFrm.Dispose();
            return(retVal);
        }
        public PLCTagTriggerThread(IDBInterface dbInterface, DatasetConfig datasetConfig, Dictionary <ConnectionConfig, Object> activConnections, bool StartedAsService)
        {
            this.StartedAsService = StartedAsService;
            this.dbInterface      = dbInterface;
            this.datasetConfig    = datasetConfig;
            this.activConnections = activConnections;

            this.triggerConn = (PLCConnection)activConnections[datasetConfig.TriggerConnection];
            this.readBit     = datasetConfig.TriggerReadBit;
            this.quittBit    = datasetConfig.TriggerQuittBit;

            ak_interval = NoDataInterval;
        }
Example #18
0
        /// <summary>
        /// invio messaggio di plctag changed value a tutti i susbscibers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">dati plctag</param>
        private void plc_TagChangedValue(object sender, TagChangedValueEventArgs e)
        {
            var tag = new PLCTag();

            /* cerco il subscriber associato al tag */
            foreach (var subscriber in _Subs.ToList())
            {
                /* lista di subscrictions del subscriber */
                var list = subscriber.Value;

                if (list.Contains(new Subscription(e.PLCName, e.Tag.ItemName)))
                {
                    // trovato il subscriber, invio messaggio di tag changed
                    tag.PLCName = e.PLCName;
                    tag.Address = e.Tag.ItemName;
                    tag.Value   = e.Tag.ItemValue;

                    //Create a DotNetMQ Message to send
                    var message = mdsClient.CreateMessage();

                    //Set destination application name
                    message.DestinationApplicationName = subscriber.Key;

                    //Create a message
                    var MsgData = new PLCTagData
                    {
                        MsgCode = MsgCodes.PLCTagChanged,
                        Tag     = tag
                    };

                    //Set message data
                    message.MessageData  = GeneralHelper.SerializeObject(MsgData);
                    message.TransmitRule = MessageTransmitRules.NonPersistent;

                    try
                    {
                        //Send message
                        message.Send();
                        Logger.InfoFormat("{1}/{2}-{3} : Inviato a {0}", message.DestinationApplicationName, tag.PLCName, tag.Address, tag.Value.ToString());
                    }
                    catch (Exception exc)
                    {
                        // non sono riuscito a inviare il messaggio
                        Logger.WarnFormat("Messaggio non inviato - {0}", exc.Message);
                    }
                }
            }
        }
Example #19
0
        /// <summary>
        /// Implementazione esecuzione comando di sottoscrizione di un plctag
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool SubscribePLCTag(string subscriber, PLCTag tag)
        {
            bool RetValue = true;

            if (!_Subs.ContainsKey(subscriber))
            {
                Logger.WarnFormat("[{0}] not subscribed", subscriber);
                RetValue = false;
            }

            if (RetValue == true)
            {
                // verifico esistenza PLC interessato
                if (!_PLCs.ContainsKey(tag.PLCName))
                {
                    // log
                    Logger.WarnFormat("PLC [{0}] non presente", tag.PLCName);

                    RetValue = false;
                }
                else
                {
                    try
                    {
                        // aggiungo tag
                        _PLCs[tag.PLCName].AddTag(tag.Address);

                        // gestione subscriptions
                        if (!_Subs.ContainsKey(subscriber))
                        {
                            _Subs.Add(subscriber, new HashSet <Subscription>());
                        }

                        _Subs[subscriber].Add(new Subscription(tag.PLCName, tag.Address));
                    }
                    catch (Exception exc)
                    {
                        // log
                        Logger.WarnFormat("PLC [{0}] error adding tag {1} : {2}", tag.PLCName, tag.Address, exc.Message);
                        RetValue = false;
                    }
                }
            }

            return(RetValue);
        }
Example #20
0
 private void listBox1_DoubleClick(object sender, EventArgs e)
 {
     if (listBox1.SelectedIndex >= 0 && timer1.Enabled == false)
     {
         PLCTag myAkValue = myValues[listBox1.SelectedIndex];
         String newVal    = myAkValue.Value.ToString();
         System.Windows.Forms.DialogResult ret = Form1.InputBox("SPS Wert ändern", "Neuer Wert:", ref newVal);
         if (ret == DialogResult.OK)
         {
             myAkValue.Controlvalue = newVal;
             listBox1.Items.Clear();
             listBox1.Items.AddRange(myValues.ToArray());
             button9.Visible = true;
             //myConn.WriteValue(myAkValue);
         }
         //timer1_Tick(sender, e);
     }
 }
Example #21
0
        /// <summary>
        /// Implementazione esecuzione comando di rimozione di un plctag
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool RemovePLCTag(string subscriber, PLCTag tag)
        {
            bool RetValue = true;

            Logger.InfoFormat("{1}/{2} da {0}", subscriber, tag.PLCName, tag.Address);

            if (!_Subs.ContainsKey(subscriber))
            {
                Logger.WarnFormat("[{0}] not subscribed", subscriber);
                RetValue = false;
            }

            if (RetValue == true)
            {
                // verifico esistenza PLC interessato
                if (!_PLCs.ContainsKey(tag.PLCName))
                {
                    Logger.WarnFormat("PLC [{0}] not present", tag.PLCName);

                    RetValue = false;
                }
                else
                {
                    try
                    {
                        // rimuovo tag
                        _PLCs[tag.PLCName].RemoveTag(tag.Address);

                        // gestione subscriptions
                        if (_Subs.ContainsKey(subscriber))
                        {
                            _Subs[subscriber].Remove(new Subscription(tag.PLCName, tag.Address));
                        }
                    }
                    catch (Exception exc)
                    {
                        // log
                        Logger.WarnFormat("PLC [{0}] error removing tag {1} : {2}", tag.PLCName, tag.Address, exc.Message);
                        RetValue = false;
                    }
                }
            }
            return(RetValue);
        }
        public bool SetStop()
        {
            if (!IsPlcConnected())
            {
                return(false);
            }

            var tag = new PLCTag("DB10.DBX0.1", TagDataType.Bool)
            {
                Value = 1
            };

            lock (_lockObject)
            {
                _plcConnection.WriteValue(tag);
            }

            return(true);
        }
        public bool SetSetPoint(int value)
        {
            if (!IsPlcConnected())
            {
                return(false);
            }

            var tag = new PLCTag("DB10.DBW2", TagDataType.Int)
            {
                Value = value
            };

            lock (_lockObject)
            {
                _plcConnection.WriteValue(tag);
            }

            return(true);
        }
Example #24
0
        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog saveDataDir = new FolderBrowserDialog();

            if (saveDataDir.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (string db in listBox1.SelectedItems)
                {
                    var size = myConn.PLCGetDataBlockSize(db);
                    var Tag  = new PLCTag(db + ".DBX0.0");
                    Tag.TagDataType = TagDataType.ByteArray;
                    Tag.ArraySize   = size;
                    myConn.ReadValue(Tag);

                    BinaryWriter wrt = new BinaryWriter(File.Open(Path.Combine(saveDataDir.SelectedPath, db + ".data"), FileMode.Create));
                    wrt.Write((byte[])Tag.Value);
                    wrt.Close();
                }
            }
        }
        public virtual string GetDefaultDatabaseFieldTypeForLibNoDaveTag(PLCTag tag)
        {
            switch (tag.TagDataType.ToString().ToLower().Trim())
            {
            case "float":
                return("float");

                break;

            case "int":
                return("int");

                break;

            case "word":
                return("word");

                break;

            case "date":
                return("date");

                break;

            case "datetime":
                return("datetime");

                break;

            case "time":
                return("time");

                break;

            case "dint":
                return("bigint");

                break;
            }
            return("");
        }
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         PLCConnection myConn = new PLCConnection(lstConnections.SelectedItem.ToString());
         myConn.Connect();
         PLCTag plcTag = new PLCTag()
         {
             TagDataType = TagDataType.ByteArray, TagDataSource = MemoryArea.Datablock, DataBlockNumber = Convert.ToInt32(txtDB.Text), ByteAddress = Convert.ToInt32(txtStartByte.Text), ArraySize = Convert.ToInt32(txtBytes.Text)
         };
         myConn.ReadValue(plcTag);
         readBytes = (byte[])plcTag.Value;
         myConn.Disconnect();
         lblState.Text = readBytes.Length.ToString() + " Bytes gelesen";
         MessageBox.Show("So nun den neuen DB übertragen....");
     }
     catch (Exception ex)
     {
         lblState.Text = ex.Message;
     }
 }
Example #27
0
        private void cmdReadWithLibnodave_Click(object sender, EventArgs e)
        {
            try
            {
                txtWert.Text   = "";
                txtZeit.Text   = "";
                lblStatus.Text = "";

                if (myConn == null)
                {
                    cmdConnect_Click(sender, e);
                }

                PLCTag myTag = new PLCTag(txtTag.Text);

                byte[] tmp = new byte[myTag.ArraySize];

                Stopwatch sw = new Stopwatch();
                sw.Start();
                int res = myConn._dc.readManyBytes(DotNetSiemensPLCToolBoxLibrary.Communication.LibNoDave.libnodave.daveDB, myTag.DatablockNumber, myTag.ByteAddress, myTag.ArraySize, ref tmp);
                sw.Stop();
                if (res != 0)
                {
                    MessageBox.Show("Error using libnodave, readmaybytes! Code:" + res.ToString());
                    return;
                }

                txtZeit.Text = sw.ElapsedMilliseconds.ToString() + " ms";
                string tmp2 = "{";
                foreach (byte b in tmp)
                {
                    tmp2 += b.ToString() + ",";
                }
                txtWert.Text = tmp2 + "}";
            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
            }
        }
Example #28
0
        private void cmdReadStruct_Click(object sender, EventArgs e)
        {
            myConn = new PLCConnection("SimpleCSharpDemonstrationConnection");
            myConn.Connect();
            //PLCTagGeneric
            PLCTag <TestStruct> tst = new PLCTag <TestStruct>()
            {
                DatablockNumber = 97, ByteAddress = 0
            };

            myConn.ReadValue(tst);
            TestStruct read = tst.GenericValue;

            TestStruct wrt = new TestStruct();

            wrt.aa           = 11;
            wrt.bb           = 12;
            wrt.cc           = 13;
            wrt.ee           = 14;
            wrt.ff           = 15;
            wrt.test         = "Bin da!";
            tst.Controlvalue = wrt;
            myConn.WriteValue(tst);
        }
Example #29
0
        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter      = "*.data|*.data";
            dlg.Multiselect = true;

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (var fileName in dlg.FileNames)
                {
                    var rd    = new BinaryReader(File.Open(fileName, FileMode.Open));
                    var bytes = rd.ReadBytes(Convert.ToInt32(rd.BaseStream.Length));

                    var fn = Path.GetFileName(fileName);
                    fn = fn.Substring(0, fn.Length - 5);
                    var Tag = new PLCTag(fn + ".DBX0.0");
                    Tag.TagDataType  = TagDataType.ByteArray;
                    Tag.ArraySize    = bytes.Length;
                    Tag.Controlvalue = bytes;
                    myConn.WriteValue(Tag);
                }
            }
        }
Example #30
0
        public S7VATBlock(byte[] hexCode, byte[] comments, int blocknumber, Encoding projEncoding)
        {
            BlockType = PLCBlockType.VAT;
            //BlockLanguage=
            BlockNumber = blocknumber;
            //Every Vats starts with:
            //0001 31 20 32 20 30 20 32 20 31 20 31 30 20 30 20 32    1 2 0 2 1 10 0 2
            //0010 30 20 31 20 33 30 20 31 20 34 30 20 31 20 35 30    0 1 30 1 40 1 50
            //0020 20 36 30 00 32 20 33 20 38 38 20 30 20 30 20 30     60.

            Rows    = new List <PLCTag>();
            VATRows = new List <S7VATRow>();

            int akAddr = 36;

            while (akAddr < hexCode.Length)
            {
                if (hexCode[akAddr] != 0x00)
                {
                    PLCTag tmp        = new PLCTag();
                    string var        = "";
                    string type       = "";
                    string addr       = "";
                    string controlval = "";
                    string db         = "";
                    string showtype   = "";
                    bool   bit        = false;

                    switch (hexCode[akAddr])
                    {
                    case 0x32:
                        var = "E";
                        tmp.TagDataSource = MemoryArea.Inputs;
                        break;

                    case 0x33:
                        var = "A";
                        tmp.TagDataSource = MemoryArea.Outputs;
                        break;

                    case 0x34:
                        tmp.TagDataSource = MemoryArea.Flags;
                        var = "M";
                        break;

                    case 0x35:
                        tmp.TagDataSource = MemoryArea.Datablock;
                        var = "DB";
                        db  = "DB";
                        break;

                    case 0x38:
                        tmp.TagDataSource = MemoryArea.Timer;
                        var = "T";
                        break;

                    case 0x39:
                        tmp.TagDataSource = MemoryArea.Counter;
                        var = "Z";
                        break;

                    default:
                        var = "  0x" + hexCode[akAddr].ToString("X") + "  ";
                        break;
                    }
                    akAddr++;
                    akAddr++;
                    switch (hexCode[akAddr])
                    {
                    case 0x31:
                        if (db != "")
                        {
                            var += "X";
                        }
                        tmp.TagDataType = TagDataType.Bool;
                        bit             = true;
                        break;

                    case 0x32:
                        var            += "B";
                        tmp.TagDataType = TagDataType.Byte;
                        break;

                    case 0x33:
                        tmp.TagDataType = TagDataType.Word;
                        var            += "W";
                        break;

                    case 0x34:
                        tmp.TagDataType = TagDataType.Dword;
                        var            += "D";
                        break;

                    default:
                        var = "  0x" + hexCode[akAddr].ToString("X") + "  ";
                        break;
                    }
                    akAddr++;
                    akAddr++;
                    while (hexCode[akAddr] != 0x20)
                    {
                        addr += hexCode[akAddr] - 0x30;
                        akAddr++;
                    }
                    tmp.ByteAddress = Convert.ToInt32(addr);
                    akAddr++;
                    if (bit == true)
                    {
                        tmp.BitAddress = Convert.ToInt32(hexCode[akAddr] - 0x30);
                    }
                    akAddr++;
                    akAddr++;
                    if (db != "")
                    {
                        addr = "";
                        while (hexCode[akAddr] != 0x20)
                        {
                            addr += hexCode[akAddr] - 0x30;
                            akAddr++;
                        }
                        tmp.DataBlockNumber = Convert.ToInt32(addr);
                    }
                    akAddr++;
                    akAddr++;
                    //0x30
                    akAddr++;
                    akAddr++;
                    //again
                    akAddr++;
                    akAddr++;
                    //again size
                    akAddr++;
                    akAddr++;
                    //0x30
                    akAddr++;
                    akAddr++;
                    //0x31
                    akAddr++;
                    akAddr++;
                    akAddr++;
                    akAddr++;
                    akAddr++;
                    //View Sign
                    switch (hexCode[akAddr])
                    {
                    case 0x30:
                        if (hexCode[akAddr - 1] == 0x31)
                        {
                            //showtype = "ZAEHLER";
                            tmp.TagDataType          = TagDataType.BCDWord;
                            tmp.DataTypeStringFormat = TagDisplayDataType.Decimal;
                        }
                        else
                        {
                            //showtype = "BIN";
                            tmp.DataTypeStringFormat = TagDisplayDataType.Binary;
                        }
                        break;

                    case 0x31:
                        if (hexCode[akAddr - 1] == 0x31)
                        {
                            //showtype = "ZEIGER";
                            tmp.DataTypeStringFormat = TagDisplayDataType.Pointer;
                        }
                        else
                        {
                            //showtype = "HEX";
                            tmp.DataTypeStringFormat = TagDisplayDataType.Hexadecimal;
                        }
                        break;

                    case 0x32:
                        //showtype = "DEZ";
                        tmp.DataTypeStringFormat = TagDisplayDataType.Decimal;
                        break;

                    case 0x33:
                        //showtype = "GLEITPUNKT";
                        tmp.TagDataType          = TagDataType.Float;
                        tmp.DataTypeStringFormat = TagDisplayDataType.Float;
                        break;

                    case 0x34:
                        //showtype = "ZEICHEN";
                        tmp.TagDataType          = TagDataType.Byte;
                        tmp.DataTypeStringFormat = TagDisplayDataType.String;
                        break;

                    case 0x35:
                        //showtype = "BOOL";
                        tmp.DataTypeStringFormat = TagDisplayDataType.Bool;
                        break;

                    case 0x36:
                        //showtype = "ZEIT";
                        tmp.TagDataType          = TagDataType.Time;
                        tmp.DataTypeStringFormat = TagDisplayDataType.Time;
                        break;

                    case 0x37:
                        //showtype = "DATUM";
                        tmp.TagDataType          = TagDataType.Date;
                        tmp.DataTypeStringFormat = TagDisplayDataType.S7Date;
                        break;

                    case 0x38:
                        tmp.TagDataType          = TagDataType.S5Time;
                        tmp.DataTypeStringFormat = TagDisplayDataType.S5Time;
                        //showtype = "SIMATIC_ZEIT";
                        break;

                    case 0x39:
                        tmp.TagDataType          = TagDataType.TimeOfDay;
                        tmp.DataTypeStringFormat = TagDisplayDataType.S7TimeOfDay;
                        //showtype = "TAGESZEIT";
                        break;

                    default:
                        var = "  0x" + hexCode[akAddr].ToString("X") + "  ";
                        break;
                    }
                    akAddr++;
                    while (hexCode[akAddr] != 0x00)
                    {
                        controlval += System.Text.Encoding.ASCII.GetString(new byte[] { hexCode[akAddr] });
                        akAddr++;
                    }
                    tmp.ParseControlValueFromString(controlval);

                    akAddr++;
                    Rows.Add(tmp);
                    VATRows.Add(new S7VATRow()
                    {
                        LibNoDaveValue = tmp
                    });
                }
                else
                {
                    akAddr++;
                    VATRows.Add(new S7VATRow()
                    {
                    });
                }
            }

            //string aa = System.Text.Encoding.ASCII.GetString(comments);

            int commentsRow = 12;
            int akLine      = -1;

            while (commentsRow < comments.Length)
            {
                int akLen      = comments[commentsRow] + comments[commentsRow + 1] * 0x100;
                int akLinePlus = comments[commentsRow + 2] + comments[commentsRow + 3] * 0x100;
                akLine += akLinePlus;

                if (commentsRow + 6 + akLen > comments.Length)
                {
                    akLen = comments.Length - commentsRow - 6;
                }

                if (akLine < VATRows.Count)
                {
                    VATRows[akLine].Comment = projEncoding.GetString(comments, commentsRow + 6, akLen);
                }

                commentsRow += 6 + akLen;
                akLine++;
            }
        }
Example #31
0
        public void ReadValue(PLCTag tag)
        {
            if (_connected)
            {
                var rqHeader = new RequestHeader();
                rqHeader.system_id     = new[] { 'S', '5' };
                rqHeader.header_length = (byte)Marshal.SizeOf(typeof(RequestHeader));
                rqHeader.opcode_id     = 1;
                rqHeader.opcode_length = 3;
                rqHeader.opcode        = (byte)OperationCode.Fetch;
                rqHeader.org           = 3;
                rqHeader.org_length    = 8;
                switch (tag.TagDataSource)
                {
                case MemoryArea.Datablock:
                case MemoryArea.InstanceDatablock:
                    rqHeader.org_id = (byte)OrgTypes.DB;
                    break;

                case MemoryArea.Inputs:
                    rqHeader.org_id = (byte)OrgTypes.Inputs;
                    break;

                case MemoryArea.Outputs:
                    rqHeader.org_id = (byte)OrgTypes.Outputs;
                    break;

                case MemoryArea.S5_DX:
                    rqHeader.org_id = (byte)OrgTypes.DBx;
                    break;

                case MemoryArea.Flags:
                    rqHeader.org_id = (byte)OrgTypes.Flags;
                    break;

                case MemoryArea.Counter:
                    rqHeader.org_id = (byte)OrgTypes.Counters;
                    break;

                case MemoryArea.Timer:
                    rqHeader.org_id = (byte)OrgTypes.Timer;
                    break;
                }
                rqHeader.dbnr           = (byte)tag.DataBlockNumber;
                rqHeader.start_address1 = (byte)(((tag.ByteAddress / 2) & 0xff00) >> 8);
                rqHeader.start_address2 = (byte)(((tag.ByteAddress / 2) & 0x00ff));

                var sz = tag.ReadByteSize;
                if (sz % 2 > 0)
                {
                    sz++;
                }

                rqHeader.length1          = (byte)(((sz / 2) & 0xff00) >> 8);
                rqHeader.length2          = (byte)(((sz / 2) & 0x00ff));
                rqHeader.req_empty        = 0xff;
                rqHeader.req_empty_length = 2;

                var bytes = getBytes(rqHeader);

                _tcp.SendData(bytes);

                var header    = new byte[Marshal.SizeOf(typeof(ResponseHeader))];
                var readBytes = 0;
                while (readBytes < header.Length)
                {
                    readBytes += _tcp.NetworkStream.Read(header, readBytes, header.Length - readBytes);
                }
                var response = fromBytes <ResponseHeader>(header);

                var data = new byte[sz];
                readBytes = 0;
                while (readBytes < sz)
                {
                    readBytes += _tcp.NetworkStream.Read(data, readBytes, sz - readBytes);
                }

                tag.ParseValueFromByteArray(data, tag.ByteAddress % 2 > 0 ? 1 : 0);
            }
        }
Example #32
0
        public void WriteValue(PLCTag tag)
        {
            if (_connectedWrite)
            {
                var rqHeader = new RequestHeader();
                rqHeader.system_id     = new[] { 'S', '5' };
                rqHeader.header_length = (byte)Marshal.SizeOf(typeof(RequestHeader));
                rqHeader.opcode_id     = 1;
                rqHeader.opcode_length = 3;
                rqHeader.opcode        = (byte)OperationCode.Write;
                rqHeader.org           = 3;
                rqHeader.org_length    = 8;
                switch (tag.TagDataSource)
                {
                case MemoryArea.Datablock:
                case MemoryArea.InstanceDatablock:
                    rqHeader.org_id = (byte)OrgTypes.DB;
                    break;

                case MemoryArea.Inputs:
                    rqHeader.org_id = (byte)OrgTypes.Inputs;
                    break;

                case MemoryArea.Outputs:
                    rqHeader.org_id = (byte)OrgTypes.Outputs;
                    break;

                case MemoryArea.S5_DX:
                    rqHeader.org_id = (byte)OrgTypes.DBx;
                    break;

                case MemoryArea.Flags:
                    rqHeader.org_id = (byte)OrgTypes.Flags;
                    break;

                case MemoryArea.Counter:
                    rqHeader.org_id = (byte)OrgTypes.Counters;
                    break;

                case MemoryArea.Timer:
                    rqHeader.org_id = (byte)OrgTypes.Timer;
                    break;
                }
                rqHeader.dbnr           = (byte)tag.DataBlockNumber;
                rqHeader.start_address1 = (byte)(((tag.ByteAddress / 2) & 0xff00) >> 8);
                rqHeader.start_address2 = (byte)(((tag.ByteAddress / 2) & 0x00ff));

                var sz = tag.ReadByteSize;
                if (sz % 2 > 0)
                {
                    sz++;
                }

                rqHeader.length1          = (byte)(((sz / 2) & 0xff00) >> 8);
                rqHeader.length2          = (byte)(((sz / 2) & 0x00ff));
                rqHeader.req_empty        = 0xff;
                rqHeader.req_empty_length = 2;

                var bytes = getBytes(rqHeader);

                var writeByte = new byte[bytes.Length + sz];
                Array.Copy(bytes, 0, writeByte, 0, bytes.Length);

                var putPos = bytes.Length;
                if (tag.ReadByteSize % 2 > 0)
                {
                    putPos++;
                }

                if (tag.TagDataType == TagDataType.Bool)
                {
                    if (object.Equals(tag.Controlvalue, true))
                    {
                        writeByte[putPos] = (byte)(Math.Pow(2, (tag.BitAddress)));
                    }
                    else
                    {
                        writeByte[putPos] = 0;
                    }
                }
                else
                {
                    tag._putControlValueIntoBuffer(writeByte, putPos);
                }


                _tcpWrite.SendData(writeByte);
                var data      = new byte[Marshal.SizeOf(typeof(ResponseHeader))];
                var readBytes = 0;
                while (readBytes < data.Length)
                {
                    readBytes += _tcpWrite.NetworkStream.Read(data, readBytes, data.Length - readBytes);
                }

                var response = fromBytes <ResponseHeader>(data);
            }
        }