Esempio n. 1
0
        public bool writeToPLCString(string sName, string sValue)
        {
            bool            bret       = true;
            TcAdsClient     tcClient   = new TcAdsClient();
            AdsStream       dataStream = new AdsStream(100);
            AdsBinaryReader binReader  = new AdsBinaryReader(dataStream);

            int iHandle = 0;

            tcClient.Connect(851);
            iHandle = tcClient.CreateVariableHandle(sName);

            try
            {
                tcClient.WriteAnyString(iHandle, sValue, sValue.Length, Encoding.Default);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                bret = false;
            }
            finally
            {
                tcClient.DeleteVariableHandle(iHandle);
                tcClient.Dispose();
            }

            return(bret);
        }
Esempio n. 2
0
 internal void Parse(AdsStream symbolStream, AdsStream dataTypeStream, TcAdsClient adsClient)
 {
     this._subSymbolFactory = new SubSymbolFactory(this);
     this._defaultTypes     = DataTypeInfoTable.GetDefaultTypes(this);
     this.OnTypesCreated(this._defaultTypes);
     object[] args = new object[] { adsClient.Address, symbolStream.Length, dataTypeStream.Length };
     Module.Trace.TraceInformation("Client: {0}, SymbolStream: {1} bytes, DataTypeStream: {2} bytes", args);
     this._adsClient = adsClient;
     using (AdsBinaryReader reader = new AdsBinaryReader(symbolStream))
     {
         using (AdsBinaryReader reader2 = new AdsBinaryReader(dataTypeStream))
         {
             uint[] numArray;
             uint[] numArray2;
             int    symbolCount = 0;
             symbolCount = this.countSymbols(reader);
             object[] objArray2 = new object[] { symbolCount };
             Module.Trace.TraceInformation("SymbolCount: {0}", objArray2);
             this._symbolTable = this.fillSymbolTables(reader, symbolCount, out numArray);
             int      dataTypeCount = this.countDataTypes(reader2);
             object[] objArray3     = new object[] { symbolCount };
             Module.Trace.TraceInformation("DataTypeCount: {0}", objArray3);
             Dictionary <string, int> dictionary = this.fillDataTypeTables(reader2, dataTypeCount, out numArray2);
             this._dataTypes = this.collectDataTypes(dataTypeCount, numArray2, reader2);
             this.expandDataTypes();
         }
     }
 }
Esempio n. 3
0
        public static object ReadDataType(string dataType, int bitSize, AdsBinaryReader binaryReader)
        {
            // standard data formats
            Func <AdsBinaryReader, int, object> dataTypeFunc;

            if (_dataTypeMapping.TryGetValue(dataType, out dataTypeFunc))
            {
                return(dataTypeFunc(binaryReader, bitSize));
            }

            // enum
            if (IsEnum(dataType, bitSize))
            {
                return(binaryReader.ReadInt16());
            }

            // any "STRING(14)" types with variable length
            if (dataType.StartsWith(IEC61131_3_DataTypes.String))
            {
                return(binaryReader.ReadPlcString(bitSize / 8));
            }

            // default to simply use the bit size
            Func <AdsBinaryReader, object> intFunc;

            if (_bitSizeMapping.TryGetValue(bitSize, out intFunc))
            {
                return(intFunc(binaryReader));
            }

            // cannot convert it, default to return null
            return(null);
        }
Esempio n. 4
0
        private void BtnRead_Click(object sender, EventArgs e)
        {
            stream = new AdsStream(4);
            reader = new AdsBinaryReader(stream);

            try
            {
                client.Read(htime1, stream);

                txtTime.Text    = (reader.ReadPlcTIME()).ToString();
                stream.Position = 0;

                client.Read(hdate1, stream);
                txtDate.Text    = reader.ReadPlcDATE().ToString();
                stream.Position = 0;

                client.Read(hdate2, stream);
                txtDate2.Text   = reader.ReadPlcDATE().ToString();
                stream.Position = 0;
            }
            catch (Exception err)
            {
                MessageBox.Show("BtnRead " + err.Message);
            }
        }
Esempio n. 5
0
        public void Read(string name, TcReadHandler handler, int length, int position = 0)
        {
            int handle = GetHandle(name);

            if (length < 1)
            {
                throw new Exception("Reading length must be over 0 in UlTcAdsClient::Read");
            }

            lock (criticalLock)
            {
                using (AdsStream stream = new AdsStream(length))
                {
                    using (AdsBinaryReader reader = new AdsBinaryReader(stream))
                    {
                        try
                        {
                            client.Read(handle, stream);
                            stream.Position = position;

                            handler(reader);
                        }
                        catch (Exception e)
                        {
                            string str = string.Format("Occurred exception({0}) in UlTcAdsClient::Read", e.ToString());
                            throw new Exception(str);
                        }
                    }
                }
            }
        }
Esempio n. 6
0
        //TcAdsClient tcClient = new TcAdsClient();
        //AdsStream dataStream = new AdsStream(4);
        //AdsBinaryReader binReader = new AdsBinaryReader(dataStream);

        public bool writeToPLCInt(string sName, int iValue)
        {
            TcAdsClient     tcClient   = new TcAdsClient();
            AdsStream       dataStream = new AdsStream(4);
            AdsBinaryReader binReader  = new AdsBinaryReader(dataStream);
            int             iHandle    = 0;

            tcClient.Connect(851);
            iHandle = tcClient.CreateVariableHandle(sName);

            try
            {
                tcClient.WriteAny(iHandle, iValue);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                tcClient.DeleteVariableHandle(iHandle);
                tcClient.Dispose();
            }

            return(true);
        }
Esempio n. 7
0
        public void Read(long parentEndPosition, Encoding encoding, AdsBinaryReader reader)
        {
            long position = reader.BaseStream.Position;

            this.entryLength = reader.ReadUInt32();
            long num2 = position + this.entryLength;

            this.size          = reader.ReadUInt32();
            this.alignSize     = reader.ReadUInt32();
            this.dataType      = (AdsDatatypeId)reader.ReadUInt32();
            this.flags         = (MethodParamFlags)reader.ReadUInt32();
            this.reserved      = reader.ReadUInt32();
            this.typeGuid      = reader.ReadGuid();
            this.lengthIsPara  = reader.ReadUInt16();
            this.nameLength    = reader.ReadUInt16();
            this.typeLength    = reader.ReadUInt16();
            this.commentLength = reader.ReadUInt16();
            this.name          = reader.ReadPlcString(this.nameLength + 1, encoding);
            this.type          = reader.ReadPlcString(this.typeLength + 1, encoding);
            this.comment       = reader.ReadPlcString(this.commentLength + 1, encoding);
            if (reader.BaseStream.Position <= num2)
            {
                byte[] buffer = reader.ReadBytes((int)(num2 - reader.BaseStream.Position));
            }
            else if (reader.BaseStream.Position > num2)
            {
                object[] args = new object[] { this.name };
                Module.Trace.TraceError("Reading MethodPara entry for '{0}' failed!", args);
                reader.BaseStream.Position = num2;
            }
        }
Esempio n. 8
0
        public double[] ReadDouble(string name, int length)
        {
            double[] value  = new double[length];
            int      handle = GetHandle(name);

            if (length < 2)
            {
                throw new Exception("Reading length must be over 1 in UlTcAdsClient::GetDouble");
            }

            lock (criticalLock)
            {
                using (AdsStream stream = new AdsStream(sizeof(double) * length))
                {
                    using (AdsBinaryReader reader = new AdsBinaryReader(stream))
                    {
                        client.Read(handle, stream);

                        for (int i = 0; i < length; i++)
                        {
                            value[i] = reader.ReadDouble();
                        }
                    }
                }
            }

            return(value);
        }
Esempio n. 9
0
        public bool IsHeartBeatAlive()
        {
            try
            {
                AdsStream       dataStream = new AdsStream(4);
                AdsBinaryReader binReader  = new AdsBinaryReader(dataStream);

                int iHandle = 0;
                int iValue  = 0;
                iHandle = _tcAds.CreateVariableHandle("TwinCAT_SystemInfoVarList._AppInfo.OnlineChangeCnt");

                _tcAds.Read(iHandle, dataStream);
                iValue = binReader.ReadInt32();
                dataStream.Position = 0;
                if (iValue != _onlineChangeCount)
                {
                    _onlineChangeCount = iValue;
                    isHierarchieLoaded = false;
                }
            }
            catch (Exception e)
            {
                DiagnosticWindow.AddToDebug(e.Message);
                return(false);
            }
            return(true);
        }
Esempio n. 10
0
 public AdsDataTypeEntry(bool rootEntry, Encoding encoding, AdsBinaryReader reader)
 {
     this.typeGuid   = Guid.Empty;
     this._id        = ++s_idCount;
     this._rootEntry = rootEntry;
     this.Read(-1L, encoding, reader);
 }
Esempio n. 11
0
 private void DoReadTcArgs(AdsBinaryReader reader)
 {
     for (int i = 0; i < 8; i++)
     {
         inst.Args.Bools[i] = reader.ReadBoolean();
     }
     for (int i = 0; i < 8; i++)
     {
         inst.Args.Bytes[i] = reader.ReadByte();
     }
     for (int i = 0; i < 8; i++)
     {
         inst.Args.Int16s[i] = reader.ReadInt16();
     }
     for (int i = 0; i < 8; i++)
     {
         inst.Args.Int32s[i] = reader.ReadInt32();
     }
     for (int i = 0; i < 8; i++)
     {
         inst.Args.Floats[i] = reader.ReadSingle();
     }
     for (int i = 0; i < 8; i++)
     {
         inst.Args.Doubles[i] = reader.ReadDouble();
     }
 }
Esempio n. 12
0
        private string ReadWString(AdsBinaryReader reader)
        {
            var len  = reader.ReadByte();
            var data = reader.ReadBytes(len * 2);

            return(Encoding.Unicode.GetString(data));
        }
Esempio n. 13
0
        private string ReadString(AdsBinaryReader reader)
        {
            var len  = reader.ReadByte();
            var data = reader.ReadBytes(len);

            return(Encoding.GetEncoding(1252).GetString(data));
        }
Esempio n. 14
0
        public void Read(long parentEndPosition, Encoding encoding, AdsBinaryReader reader)
        {
            byte num  = reader.ReadByte();
            byte num2 = reader.ReadByte();

            this._name  = reader.ReadPlcString(num + 1, encoding);
            this._value = reader.ReadPlcString(num2 + 1, encoding);
        }
Esempio n. 15
0
 private void DoReadTcInstructions(AdsBinaryReader reader)
 {
     inst.Handle = reader.ReadInt32();
     inst.Index  = reader.ReadInt16();
     inst.Step   = reader.ReadInt16();
     inst.Active = reader.ReadBoolean();
     inst.State  = reader.ReadInt16();
 }
Esempio n. 16
0
        static void Main(string[] args)
        {
            TcAdsClient     tcClient   = new TcAdsClient();
            AdsStream       dataStream = new AdsStream(4);
            AdsBinaryReader binReader  = new AdsBinaryReader(dataStream);

            int      handle = 0;
            int      iValue = 0;
            int      exValue = 0;
            string   variable, adres;
            DateTime now = DateTime.Now;

            Console.WriteLine("Podaj adres serwera ADS: ");
            adres = Console.ReadLine();
            Console.WriteLine("Podaj  nazwe zmienna do zapysywania w bazie danych: ");
            variable = Console.ReadLine();
            FileStream   File   = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter writer = new StreamWriter(File);

            writer.WriteLine(adres + "  801  " + variable + "    " + now.ToString("F"));

            try
            {
                tcClient.Connect(adres, 801);

                handle = tcClient.CreateVariableHandle(variable);

                Console.WriteLine("Czekam na znak");

                do
                {
                    tcClient.Read(handle, dataStream);
                    iValue = binReader.ReadInt32();
                    dataStream.Position = 0;
                    if (iValue != exValue)
                    {
                        writer.WriteLine(iValue + "    " + now.ToString("F"));
                    }

                    Console.WriteLine("Aktualna wartosc wynosi: " + iValue);

                    exValue = iValue;
                } while (Console.ReadKey().Key.Equals(ConsoleKey.Enter));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " xdddd");
            }
            finally
            {
                writer.Close();
                tcClient.DeleteVariableHandle(handle);
                tcClient.Dispose();
            }
            Console.ReadKey();
        }
Esempio n. 17
0
        public void WhenEnumDataTypeWithWrongNamingConvention_ShouldNotCrash()
        {
            var buffer       = new byte[] { 1, 2, 3 };
            var stream       = new AdsStream(buffer);
            var binaryReader = new AdsBinaryReader(stream);

            var act = new Action(() => BeckhoffHelper.ReadDataType("MyTestEnumDoesNotFollowNamingConvention", 16, binaryReader));

            act.ShouldNotThrow();
        }
Esempio n. 18
0
        public void GivenNestedTag_WhenDefaultEnumDataType_ShouldRead()
        {
            var buffer       = new byte[] { 1, 2 };
            var stream       = new AdsStream(buffer);
            var binaryReader = new AdsBinaryReader(stream);

            var result = BeckhoffHelper.ReadDataType("MAIN.FB_1.E_MyTestEnum", 16, binaryReader);

            result.GetType().Should().Be(typeof(Int16), "int16 is TwinCat 3 default for enumerations, negative values are allowed");
        }
Esempio n. 19
0
        public void WhenBooleanDataType_ShouldReadBool()
        {
            var buffer       = new byte[] { 1 };
            var stream       = new AdsStream(buffer);
            var binaryReader = new AdsBinaryReader(stream);

            var result = BeckhoffHelper.ReadDataType("BOOL", 8, binaryReader);

            result.GetType().Should().Be(typeof(bool));
            ((bool)result).Should().BeTrue();
        }
Esempio n. 20
0
        public AdsErrorCode TryGetSymbol(string symbolPath, bool bLookup, out ITcAdsSymbol symbol)
        {
            if (string.IsNullOrEmpty(symbolPath))
            {
                throw new ArgumentOutOfRangeException("name");
            }
            symbol = null;
            SymbolInfoTable table = this;

            lock (table)
            {
                if (bLookup)
                {
                    TcAdsSymbol symbol2 = null;
                    if (this._symbolTable.TryGetValue(symbolPath, out symbol2))
                    {
                        symbol = symbol2;
                        return(AdsErrorCode.NoError);
                    }
                }
            }
            AdsErrorCode deviceSymbolNotFound = AdsErrorCode.DeviceSymbolNotFound;
            AdsStream    stream = new AdsStream(symbolPath.Length + 1);

            using (AdsBinaryWriter writer = new AdsBinaryWriter(stream))
            {
                writer.WritePlcAnsiString(symbolPath, symbolPath.Length + 1);
                AdsStream rdDataStream = new AdsStream(0xffff);
                int       readBytes    = 0;
                deviceSymbolNotFound = this._adsClient.TryReadWrite(0xf009, 0, rdDataStream, 0, (int)rdDataStream.Length, stream, 0, (int)stream.Length, out readBytes);
                if (deviceSymbolNotFound == AdsErrorCode.NoError)
                {
                    using (AdsBinaryReader reader = new AdsBinaryReader(rdDataStream))
                    {
                        AdsSymbolEntry symbolEntry = new AdsSymbolEntry(-1L, this._encoding, reader);
                        bool           flag2       = true;
                        flag2  = StringComparer.OrdinalIgnoreCase.Compare(symbolPath, symbolEntry.name) == 0;
                        symbol = new TcAdsSymbol(symbolEntry, (TcAdsDataType)this._datatypeTable.ResolveDataType(symbolEntry.type));
                        SymbolInfoTable table2 = this;
                        lock (table2)
                        {
                            this._symbolTable[symbolPath] = (TcAdsSymbol)symbol;
                            if (!flag2 && !this._symbolTable.ContainsKey(symbol.Name))
                            {
                                this._symbolTable[symbol.Name] = (TcAdsSymbol)symbol;
                                string message = $"InstancePath Ambiguity '{symbolPath}' and '{symbol.Name}'!";
                                TwinCAT.Ads.Module.Trace.TraceWarning(message);
                            }
                        }
                    }
                }
            }
            return(deviceSymbolNotFound);
        }
Esempio n. 21
0
        public void WhenStringDataType_ShouldReadString()
        {
            var buffer       = new[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
            var stream       = new AdsStream(buffer);
            var binaryReader = new AdsBinaryReader(stream);

            var result = BeckhoffHelper.ReadDataType("STRING", 81, binaryReader);

            result.GetType().Should().Be(typeof(string));
            ((string)result).Should().Be("hello");
        }
Esempio n. 22
0
        internal int InitializeStruct(IList <ITcAdsSubItem> subItems, Type type, AdsBinaryReader reader, int readerOffset, out object value)
        {
            int    num  = 0;
            object obj2 = type.InvokeMember(null, BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, null, null);

            FieldInfo[] fields = type.GetFields();
            if (fields.Length != subItems.Count)
            {
                throw new ArgumentException($"Cannot convert data type of symbol to this type.Expected number of fields {subItems.Count}, actual number is {fields.Length}", "type");
            }
            for (int i = 0; i < fields.Length; i++)
            {
                TcAdsSubItem item = (TcAdsSubItem)subItems[i];
                if ((item.BaseType.Category == DataTypeCategory.Primitive) || (item.BaseType.Category == DataTypeCategory.String))
                {
                    if (fields[i].FieldType != ((TcAdsDataType)item.BaseType).ManagedType)
                    {
                        throw new ArgumentException("Cannot convert data type of symbol to this type.", "type");
                    }
                    object obj3 = null;
                    num += this.InitializePrimitiveType(item.BaseType.Name, fields[i].FieldType, item.DataTypeId, item.Size, reader, readerOffset + item.Offset, out obj3);
                    fields[i].SetValue(obj2, obj3);
                }
                else if (item.BaseType.Category == DataTypeCategory.Enum)
                {
                    if (fields[i].FieldType != ((TcAdsDataType)item.BaseType).ManagedType)
                    {
                        throw new ArgumentException("Cannot convert data type of symbol to this type.", "type");
                    }
                    object obj4 = null;
                    num += this.InitializeEnum(item.BaseType.Name, fields[i].FieldType, item.DataTypeId, item.Size, reader, readerOffset + item.Offset, out obj4);
                    fields[i].SetValue(obj2, obj4);
                }
                else if (item.BaseType.Category == DataTypeCategory.Struct)
                {
                    object obj5 = null;
                    num += this.InitializeStruct(item.BaseType.SubItems, fields[i].FieldType, reader, readerOffset + item.Offset, out obj5);
                    fields[i].SetValue(obj2, obj5);
                }
                else
                {
                    if (item.BaseType.Category != DataTypeCategory.Array)
                    {
                        throw new ArgumentException($"Cannot convert data type of symbol to this type. ADS Data type '{item.BaseType.Name}' of subitem '{item.SubItemName}' not supported.", "type");
                    }
                    object obj6 = null;
                    num += this.InitializeArray(fields[i].FieldType, (TcAdsDataType)item.BaseType, reader, readerOffset + item.Offset, -1, out obj6);
                    fields[i].SetValue(obj2, obj6);
                }
            }
            value = obj2;
            return(num);
        }
Esempio n. 23
0
        private int countDataTypes(AdsBinaryReader dataTypeReader)
        {
            int       num        = 0;
            AdsStream baseStream = (AdsStream)dataTypeReader.BaseStream;

            for (uint i = 0; i < baseStream.Length; i += dataTypeReader.ReadUInt32())
            {
                baseStream.Position = i;
                num++;
            }
            return(num);
        }
Esempio n. 24
0
        private DateTime ReadFiletime(AdsBinaryReader reader)
        {
            var filetime = reader.ReadInt64();

            try
            {
                return(DateTime.FromFileTime(filetime));
            }
            catch (ArgumentException)
            {
                return(new DateTime(0));
            }
        }
Esempio n. 25
0
        public void Read(long parentEndPosition, Encoding encoding, AdsBinaryReader reader)
        {
            long position = reader.BaseStream.Position;

            this.entryLength = reader.ReadUInt32();
            long num2 = position + this.entryLength;

            this.indexGroup  = reader.ReadUInt32();
            this.indexOffset = reader.ReadUInt32();
            this.size        = reader.ReadUInt32();
            this.dataType    = reader.ReadUInt32();
            ushort num3 = reader.ReadUInt16();

            this.flags         = (AdsSymbolFlags)num3;
            this.arrayDim      = reader.ReadUInt16();
            this.nameLength    = reader.ReadUInt16();
            this.typeLength    = reader.ReadUInt16();
            this.commentLength = reader.ReadUInt16();
            this.name          = reader.ReadPlcString(this.nameLength + 1, encoding);
            this.type          = reader.ReadPlcString(this.typeLength + 1, encoding);
            this.comment       = reader.ReadPlcString(this.commentLength + 1, encoding);
            this.array         = SubStructureReader <AdsDatatypeArrayInfo> .Read(this.arrayDim, num2, encoding, reader);

            if (this.flags.HasFlag(AdsSymbolFlags.None | AdsSymbolFlags.TypeGuid))
            {
                this.typeGuid = new Guid(reader.ReadBytes(0x10));
            }
            if (this.flags.HasFlag(AdsSymbolFlags.Attributes))
            {
                this.attributeCount = reader.ReadUInt16();
                this.attributes     = SubStructureReader <AdsAttributeEntry> .Read(this.attributeCount, num2, encoding, reader);
            }
            if (this.flags.HasFlag(AdsSymbolFlags.ExtendedFlags))
            {
                this.extendedFlags = reader.ReadUInt32();
            }
            if (reader.BaseStream.Position != num2)
            {
                if (reader.BaseStream.Position <= num2)
                {
                    this.reserved = reader.ReadBytes((int)(num2 - reader.BaseStream.Position));
                }
                else
                {
                    object[] args = new object[] { this.name, this.type };
                    Module.Trace.TraceError("Reading Symbol entry for '{0}:{1}' failed!", args);
                    reader.BaseStream.Position = num2;
                }
            }
        }
Esempio n. 26
0
        private int countSymbols(AdsBinaryReader symbolReader)
        {
            int       num        = 0;
            uint      num2       = 0;
            AdsStream baseStream = (AdsStream)symbolReader.BaseStream;

            while (num2 < baseStream.Length)
            {
                baseStream.Position = num2;
                num++;
                num2 += symbolReader.ReadUInt32();
            }
            return(num);
        }
        static public tcFunctionResult tcGetAxisFeedback(int index, ref Axis_PlcToHmi RESULT)
        {
            if (!tcClient.IsConnected)
            {
                return(tcFunctionResult.TC_NOT_CONNECTED);
            }
            if (Axis_MaxAxes <= 0)
            {
                return(tcFunctionResult.TC_NO_AXIS);
            }
            if (index < 0 || index > Axis_MaxAxes - 1)
            {
                return(tcFunctionResult.TC_AXIS_OUTOFBOUND);
            }

            AdsStream       _DataStream = new AdsStream(tcAxFeedback[index].size);
            AdsBinaryReader _DataReader = new AdsBinaryReader(_DataStream);

            try
            {
                tcClient.Read(tcAxFeedback[index].handle, _DataStream);

                RESULT.actualPosition      = _DataReader.ReadDouble();
                RESULT.actualVelocity      = _DataReader.ReadDouble();
                RESULT.setPosition         = _DataReader.ReadDouble();
                RESULT.setVelocity         = _DataReader.ReadDouble();
                RESULT.controlleroverride  = _DataReader.ReadDouble();
                RESULT.ErrorID             = _DataReader.ReadUInt32();
                RESULT.hasError            = _DataReader.ReadBoolean();
                RESULT.isDisabled          = _DataReader.ReadBoolean();
                RESULT.isFwDisabled        = _DataReader.ReadBoolean();
                RESULT.isBwDisabled        = _DataReader.ReadBoolean();
                RESULT.isCalibrated        = _DataReader.ReadBoolean();
                RESULT.hasJob              = _DataReader.ReadBoolean();
                RESULT.isNotMoving         = _DataReader.ReadBoolean();
                RESULT.isPositiveDirection = _DataReader.ReadBoolean();
                RESULT.isNegativeDirection = _DataReader.ReadBoolean();
                RESULT.isInTarget          = _DataReader.ReadBoolean();
                RESULT.isInRange           = _DataReader.ReadBoolean();
            }
            catch (Exception ex)
            {
                LogMessage(string.Format("{0}\t: {1}", "Error", "Failed to read PlcToHmi" + ex.Message));
                _DataReader.Close();
                return(tcFunctionResult.TC_FAIL_TO_READ_AXIS_FEEDBACK);
            }

            _DataReader.Close();
            return(tcFunctionResult.TC_SUCCESS);
        }
Esempio n. 28
0
        private LogEntry ReadLogEntryV1(AdsBinaryReader reader)
        {
            var logEntry = new LogEntry
            {
                Message           = ReadString(reader),
                Logger            = ReadString(reader),
                Level             = ReadLogLevel(reader),
                PlcTimestamp      = ReadFiletime(reader),
                ClockTimestamp    = ReadFiletime(reader),
                TaskIndex         = reader.ReadInt32(),
                TaskName          = ReadString(reader),
                TaskCycleCounter  = reader.ReadUInt32(),
                AppName           = ReadString(reader),
                ProjectName       = ReadString(reader),
                OnlineChangeCount = reader.ReadUInt32(),
            };

            var end = false;

            while (!end)
            {
                var type = reader.ReadByte();
                switch (type)
                {
                case 1:
                    var argIdx   = (int)reader.ReadByte();
                    var argValue = ReadObject(reader);
                    logEntry.Arguments.Add(argIdx, argValue);
                    break;

                case 2:
                    // context
                    var ctxScope = reader.ReadByte();     // TODO
                    var ctxName  = ReadString(reader);
                    var ctxValue = ReadObject(reader);
                    logEntry.Context[ctxName] = ctxValue;
                    break;

                case 255:
                    end = true;
                    break;

                default:
                    throw new NotImplementedException($"Type {type}");
                }
            }

            return(logEntry);
        }
Esempio n. 29
0
        /// <summary>
        /// Parses an PLC array of type T. Supports pointered arrays (POINTER TO ...).
        /// In case of pointered array it will skipp NULL pointers and import only valid instances.
        /// </summary>
        /// <typeparam name="T">
        /// Marshall type representation in .NET. See Beckhoff TwinCat 3 manual for an example.
        /// </typeparam>
        /// <param name="plcPath">The path in PLC to the array.</param>
        /// <param name="symbolLoader">The symbol loader instance.</param>
        /// <param name="twinCatClient">The adsClient instance.</param>
        /// <returns>
        /// Dictionary of imported and converted (.NET type) array elements and their pathes.
        /// </returns>
        public static IDictionary <string, T> GetArrayElementsWithPathes <T>(this TcAdsClient twinCatClient, TcAdsSymbolInfoLoader symbolLoader, string plcPath)
        {
            IDictionary <string, T> array = new Dictionary <string, T>();

            TcAdsSymbolInfo arraySymbol = symbolLoader.FindSymbol(plcPath);

            if (arraySymbol == null)
            {
                return(array);
            }

            var stream = new AdsStream(8);
            var reader = new AdsBinaryReader(stream);

            TcAdsSymbolInfo elementSymbol = arraySymbol.FirstSubSymbol;

            while (elementSymbol != null)
            {
                stream.Position = 0;
                twinCatClient.Read(elementSymbol.IndexGroup, elementSymbol.IndexOffset, stream);

                var pointerValue = PlcSystem.IsX64Mode ? reader.ReadInt64() : reader.ReadInt32();

                if (pointerValue != 0)
                {
                    string plcArrayElementPath = elementSymbol.Name;

                    if (elementSymbol.IsPointer)
                    {
                        plcArrayElementPath = string.Format("{0}^", plcArrayElementPath);
                    }

                    var handle = twinCatClient.CreateVariableHandle(plcArrayElementPath);

                    try
                    {
                        var element = (T)twinCatClient.ReadAny(handle, typeof(T));
                        array.Add(plcArrayElementPath, element);
                    }
                    finally
                    {
                        twinCatClient.DeleteVariableHandle(handle);
                    }
                }
                elementSymbol = elementSymbol.NextSymbol;
            }

            return(array);
        }
Esempio n. 30
0
        /// <summary>
        /// Parses an PLC array of type T. Supports pointered arrays (POINTER TO ...).
        /// In case of pointered array it will skipp NULL pointers and import only valid instances.
        /// </summary>
        /// <param name="plcPath">The path in PLC to the array.</param>
        /// <param name="twinCatClient">The adsClient instance.</param>
        /// <param name="typeOfElements">Marshall type representation in .NET. See Beckhoff TwinCat 3 manual for an example.</param>
        /// <returns>
        /// Dictionary of imported and converted (.NET type) array elements and their pathes.
        /// </returns>
        public static IEnumerable GetArrayElements(this TcAdsClient twinCatClient, string plcPath, Type typeOfElements)
        {
            var elements = new ArrayList();
            TcAdsSymbolInfoLoader symbolLoader = twinCatClient.CreateSymbolInfoLoader();
            TcAdsSymbolInfo       arraySymbol  = symbolLoader.FindSymbol(plcPath);

            if (arraySymbol == null)
            {
                return(elements);
            }

            var stream = new AdsStream(8);
            var reader = new AdsBinaryReader(stream);

            TcAdsSymbolInfo elementSymbol = arraySymbol.FirstSubSymbol;

            while (elementSymbol != null)
            {
                stream.Position = 0;
                twinCatClient.Read(elementSymbol.IndexGroup, elementSymbol.IndexOffset, stream);

                var pointerValue = PlcSystem.IsX64Mode ? reader.ReadInt64() : reader.ReadInt32();

                if (pointerValue != 0)
                {
                    string plcArrayElementPath = elementSymbol.Name;

                    if (elementSymbol.IsPointer)
                    {
                        plcArrayElementPath = string.Format("{0}^", plcArrayElementPath);
                    }

                    var handle = twinCatClient.CreateVariableHandle(plcArrayElementPath);

                    try
                    {
                        object element = twinCatClient.ReadAny(handle, typeOfElements);
                        elements.Add(element);
                    }
                    finally
                    {
                        twinCatClient.DeleteVariableHandle(handle);
                    }
                }
                elementSymbol = elementSymbol.NextSymbol;
            }

            return(elements);
        }
Esempio n. 31
0
        public bool IsHeartBeatAlive()
        {
            try
            {
                AdsStream dataStream = new AdsStream(4);
                AdsBinaryReader binReader = new AdsBinaryReader(dataStream);

                int iHandle = 0;
                int iValue = 0;
                iHandle = _tcAds.CreateVariableHandle("TwinCAT_SystemInfoVarList._AppInfo.OnlineChangeCnt");

                _tcAds.Read(iHandle, dataStream);
                iValue = binReader.ReadInt32();
                dataStream.Position = 0;
                if(iValue != _onlineChangeCount)
                {
                    _onlineChangeCount = iValue;
                    isHierarchieLoaded = false;
                }
            }
            catch(Exception e)
            {
                DiagnosticWindow.AddToDebug(e.Message);
                return false;
            }
            return true;
        }