Пример #1
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();
         }
     }
 }
        ///////////////////////////////////////////////////////////////////////////

        public void AñadirRedireccion()
        {
            int tamaño = 0;

            notifications.Clear();

            foreach (IO_Parameter IO in IOparameters.Out.Values)
            {
                tamaño += getTypeSize(Type.GetType(IO.TypeStr));
            }

            stream = new AdsStream(tamaño);
            reader = new BinaryReader(stream, Encoding.ASCII);

            string asd = "";

            tamaño = 0;
            try
            {
                tcAds.AdsNotification -= new AdsNotificationEventHandler(OnNotification);

                foreach (IO_Parameter IO in IOparameters.Out.Values)
                {
                    asd = IO.Name;
                    notifications.Add(tcAds.AddDeviceNotification(IO.Name, stream, tamaño, getTypeSize(Type.GetType(IO.TypeStr)), AdsTransMode.OnChange, 1, 1, IO.Value), IO.Name);
                    tamaño += getTypeSize(Type.GetType(IO.TypeStr));
                }
            }
            catch (Exception e)
            {
                parent.UBSMod.Error("Error al añadir la redirección. " + e.Message, true, false);
            }

            tcAds.AdsNotification += new AdsNotificationEventHandler(OnNotification);
        }
Пример #3
0
        private void buttonFalse_Click(object sender, RoutedEventArgs e)
        {
            using (var client = new TwinCAT.Ads.TcAdsClient())
            {
                try
                {
                    client.Connect(851);

                    // creates a stream with a length of 4 byte
                    AdsStream    ds = new AdsStream(4);
                    BinaryWriter bw = new BinaryWriter(ds);

                    ds.Position = 0;

                    bw.Write(Convert.ToInt32(textBox.Text));

                    // writes a DINT to PLC
                    client.Write(0x4020, 0x0001, ds);

                    //client.WriteSymbol("MyGVL.MyBoolVar", false, reloadSymbolInfo: true);
                    client.WriteSymbol("P_Motion2.ati_xStart", false, reloadSymbolInfo: true);

                    client.Dispose();
                }
                catch (TwinCAT.Ads.AdsErrorException ex)
                {
                    MessageBox.Show("PLC Control Error: \r\n\r\n" + ex.Message);
                }
                catch (System.FormatException ex)
                {
                    textBoxPLCSetPosition.Text = "0";
                    MessageBox.Show("Invalid float value for Position. ErrMsg: \r\n\r\n" + ex.Message);
                }
            }
        }
Пример #4
0
        public static Coordinate[] CoordinateArrayRead(int ArraySize, string VarAdress)
        {
            Coordinate[] ReadedCoordinate = new Coordinate[ArraySize];
            try
            {
                hVar = TwinCat3Client.CreateVariableHandle(VarAdress);
                AdsStream    ADSdataStream = new AdsStream(8 * 4 * ArraySize);
                BinaryReader binRead       = new BinaryReader(ADSdataStream);
                TwinCat3Client.Read(hVar, ADSdataStream);

                ADSdataStream.Position = 0;
                for (int i = 0; i < ArraySize; i++)
                {
                    ReadedCoordinate[i].X = binRead.ReadDouble();
                    ReadedCoordinate[i].Y = binRead.ReadDouble();
                    ReadedCoordinate[i].Z = binRead.ReadDouble();
                    ReadedCoordinate[i].C = binRead.ReadDouble();
                }

                TwinCat3Client.DeleteVariableHandle(hVar);
                hVar = 0;
                ADSdataStream.Dispose();
                binRead.Dispose();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
            return(ReadedCoordinate);
        }
Пример #5
0
        public PLCSymbols()
        {
            m_dataStream = new AdsStream(31);
            m_binRead    = new BinaryReader(m_dataStream, System.Text.Encoding.ASCII);

            m_adsClient.AdsNotification += new AdsNotificationEventHandler(OnNotification);
        }
Пример #6
0
        public static Coordinate CoordinateRead(string VarAdress)
        {
            Coordinate ReadedCoordinate = new Coordinate();

            try
            {
                hVar = TwinCat3Client.CreateVariableHandle(VarAdress);
                AdsStream    ADSdataStream = new AdsStream(8 * 4);
                BinaryReader binRead       = new BinaryReader(ADSdataStream);
                TwinCat3Client.Read(hVar, ADSdataStream);

                ADSdataStream.Position = 0;

                ReadedCoordinate.X = binRead.ReadDouble();
                ReadedCoordinate.Y = binRead.ReadDouble();
                ReadedCoordinate.Z = binRead.ReadDouble();
                ReadedCoordinate.C = binRead.ReadDouble();

                TwinCat3Client.DeleteVariableHandle(hVar);
                hVar = 0;
                ADSdataStream.Dispose();
                binRead.Dispose();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
            return(ReadedCoordinate);
        }
Пример #7
0
        private static AdsStream BatchRead(TcAdsClient adsClient, IList <IAddressable> variables)
        {
            if (!variables.Any())
            {
                throw new InvalidOperationException("Variables should not be empty");
            }

            // Allocate memory
            int rdLength = variables.Count * ErrorSize;
            int wrLength = (SymbolValueByHandleSize + VariableHandleSize + BitSizeSize) * variables.Count;

            // Write data for handles into the ADS Stream
            using (var writer = new BinaryWriter(new AdsStream(wrLength)))
            {
                // Byt till Immutable list!
                foreach (var readableAddress in variables)
                {
                    writer.Write((int)AdsReservedIndexGroups.SymbolValueByHandle);
                    writer.Write(readableAddress.Address.VariableHandle);
                    writer.Write(readableAddress.Address.BitSize);
                    rdLength += readableAddress.Address.BitSize;
                }

                // Sum command to read variables from the PLC
                AdsStream dataAndErrorStream = new AdsStream(rdLength);
                adsClient.ReadWrite(0xF080, variables.Count, dataAndErrorStream, (AdsStream)writer.BaseStream);

                // Return the ADS error codes
                return(dataAndErrorStream);
            }
        }
Пример #8
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);
        }
Пример #9
0
        private void btnAutoMode_Click(object sender, EventArgs e)
        {
            try
            {
                //lenght of the stream = length of string + 1
                //1,先有adsstream,
                //2,再有binarywriter.write
                //3,再有clien.write()
                //---------把字符串分解成char 在写入plc -------
                //modeWrite = new BinaryWriter(modeStream);
                //modeWrite.Write(strMode.ToCharArray());
                //client.Write(hModeUI, modeStream);
                //---------把字符串分解成char 在写入plc


                //From version 1.0.0.10 and higher the classes AdsBinaryReader and AdsBinaryWriter
                // can be used to read and write strings
                //---------用字符串的方式写入---------------
                strMode    = "Auto";
                modeStream = new AdsStream(30);
                adsWriter  = new AdsBinaryWriter(modeStream);
                adsWriter.WritePlcString(strMode, 30, Encoding.ASCII);
                client.Write(hModeUI, modeStream);
                //-----------可以使用的------------
                //---------用字符串的方式写入---------------
            }
            catch (Exception err)
            {
                MessageBox.Show("set Auto to PLC: " + err.Message);
            }
            btnAutoMode.BackColor    = Color.Green;
            btnCalibMode.BackColor   = Color.Empty;
            btnManualMode.BackColor  = Color.Empty;
            btnSettingMode.BackColor = Color.Empty;
        }
Пример #10
0
        /**
         * Reads one variable from the PLC. The variable must be declared as a REAL.
         *
         * Input:
         * tcAds - TwinCat ADS client object
         * var - The variable name (as a string) to be read from the PLC. E.g "MAIN.var1"
         * vartype - The variable type as declared in the PLC. REAL is the only supported variable type.
         * More types can be added by making changes where appropriate.
         *
         * Output: Floating value representing the value in the PLC.
         *
         **/
        static float readByString(TcAdsClient tcAds, string var, string vartype)
        {
            int hVar = 0;

            try
            {
                hVar = tcAds.CreateVariableHandle(var);
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }
            if (vartype == "REAL")
            {
                // creates a stream with a length of 4 byte
                AdsStream    ds = new AdsStream(4);
                BinaryReader br = new BinaryReader(ds);
                tcAds.Read(hVar, ds);
                try
                {
                    tcAds.DeleteVariableHandle(hVar);
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }

                return(br.ReadSingle());
            }
            else
            {
                Console.WriteLine("Error: Variable type not implemented!");
                return(0.0F);
            }
        }
Пример #11
0
        public void InitializeInterface()
        {
            dataStream = new AdsStream(255);
            //Encoding wird auf ASCII gesetzt, um Strings lesen zu können
            binRead = new BinaryReader(dataStream, System.Text.Encoding.ASCII);
            // Instanz der Klasse TcAdsClient erzeugen
            tcClient = new TcAdsClient();
            // Verbindung mit Port 851 auf dem lokalen Computer herstellen
            tcClient.Connect(851);

            hConnect = new int[7];
            aiData   = new int[7];

            try
            {
                hConnect[0] = tcClient.AddDeviceNotification(m_sVariabelName, dataStream, 0, 255, AdsTransMode.OnChange, 500, 0, aiData);
                //hConnect[1] = tcClient.AddDeviceNotification("MAIN.intVal", dataStream, 1, 2, AdsTransMode.OnChange, 100, 0, tbInt);
            }
            catch (Exception err)
            {
                bool b = true;
                while (b)
                {
                    string message = "Connection to PLC-Variables failed. Please Run TwinCat or check declared variables and retry";
                    string caption = "Connection failed!";
                }
            }

            tcClient.AdsNotification += new AdsNotificationEventHandler(OnNotification);
        }
Пример #12
0
        //0xF081指令,将Stream写入PLC的内存地址,注意方法名为ReadWrite
        private AdsStream BlockWrite(VariableInfo variables, double[,] joint_states)
        {
            //分配内存
            int rdLength = 4;
            int wrLength = 12 + 48 * 5000;

            BinaryWriter writer = new BinaryWriter(new AdsStream(wrLength));

            // Write data for handles into the ADS stream
            writer.Write(variables.indexGroup);
            writer.Write(variables.indexOffset);
            writer.Write(variables.length);


            // Write data to send to PLC behind the structure
            for (int i = 0; i < 5000; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    writer.Write(joint_states[i, j]);
                }
            }

            // Sum command to write the data into the PLC
            AdsStream rdStream = new AdsStream(rdLength);

            tcclient.ReadWrite(0xF081, 1, rdStream, (AdsStream)writer.BaseStream);
            return(rdStream);
        }
Пример #13
0
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            // luodaan AdsClient-olio yhteyttä varten
            adsClient = new TcAdsClient();
            // otetaan yhteys TwinCAT PLC:hen portin 851 kautta
            adsClient.Connect(851);

            // luodaan PLC:n muuttujiin viittaavat "osoittimet"
            startHandle = adsClient.CreateVariableHandle("MAIN.start");
            stopHandle  = adsClient.CreateVariableHandle("MAIN.reset");

            // Luodaan tapahtumankäsittelijä. Parametrina näyttöä päivittävän metodin nimi
            adsClient.AdsNotification += new AdsNotificationEventHandler(UpdateVariables);

            // avataan Ads-stream (luettava byte-määrä pitänee antaa parametrina
            this.adsStream = new AdsStream(24);
            binReader      = new BinaryReader(this.adsStream);

            /*
             *  timeHi: UDINT;      // aika
             *  timeLo: UDINT;	        // aika
             *  measurement1: REAL;	// mittaus 1
             *  measurement2: REAL;	// mittaus 2
             *  measurement3: REAL;	// mittaus 3
             *  counter: INT;			// juokseva numero
             *  arrayValue: INT;		// jotain
             * */
            measurementDataHandle = adsClient.AddDeviceNotification("MAIN.measurementData", this.adsStream, 0, 24,
                                                                    AdsTransMode.Cyclic, 100, 0, null);


            buttonConnect.Enabled  = false;
            buttonSetSR1.Enabled   = true;
            buttonResetSR1.Enabled = false;
        }
Пример #14
0
        //protected virtual void OnNotification(AdsNotificationEventArgs e)
        //{
        //    ADSNotification?.Invoke(this, e);
        //}

        public TC_Communicator(ArrayList tcwritestructvariables)
        {
            this.TCWriteStructVariables = tcwritestructvariables;
            ads        = new TcAdsClient();
            datastream = new AdsStream(31);
            binread    = new BinaryReader(datastream, System.Text.Encoding.ASCII);
        }
Пример #15
0
        public static void WriteBusQueue(List <string> list)
        {
            try
            {
                WriteTwincat("GVL.EraseTable", true);

                TcAdsClient client = new TcAdsClient();
                client.Connect(amsnetid, Convert.ToInt32(amsnetport));
                int handle = client.CreateVariableHandle("GVL.DataFromBus");

                foreach (string el in list)
                {
                    AdsStream       stream = new AdsStream(500);
                    AdsBinaryWriter writer = new AdsBinaryWriter(stream);
                    writer.WritePlcString(el, 500, Encoding.Unicode);
                    client.Write(handle, stream);
                    stream.Dispose();
                    writer.Dispose();
                    Thread.Sleep(10);
                }

                client.DeleteVariableHandle(handle);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine("BusWrite: " + ex.Message);
            }
        }
Пример #16
0
 private void Form1_Load(object sender, EventArgs e)
 {
     // create a new TcClient instance
     _tcClient      = new TcAdsClient();
     adsReadStream  = new AdsStream(4);
     adsWriteStream = new AdsStream(4);
 }
Пример #17
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);
            }
        }
Пример #18
0
 //Camera initialization
 public void initCamera()
 {
     try
     {
         myCamera = new Camera();
         myCamera.cameraInit(cameraType);
         Camera.dataDelegate dd = new Camera.dataDelegate(onNewData);
         myCamera.startFrameGrab(0x8888, 0, dd, cameraType);
         cameraStatus = 1;
     }
     catch (System.Threading.ThreadAbortException) { }
     catch (Exception ex)
     {
         cameraStatus = 0;
         //Camera status bit
         ds = new AdsStream(4);
         BinaryWriter bw = new BinaryWriter(ds);
         bw.Write(cameraStatus);
         if (twinCatBool)
         {
             tcAds.Write(0x4020, 40, ds);
         }
         EmailError.emailAlert(ex);
         throw (ex);
     }
 }
        /*
         * public static string ReadStruct(int varHandle, List<string> types, int[] size, ref TcAdsClient tcClient, out List<List<object>> output)
         * {
         *  output = new List<List<object>>();
         *  try
         *  {
         *      string message = "";
         *      int streamLength = 0;
         *      for (int i = 0; i < size.Length; i++) streamLength += StreamLength(types[i]) * size[i];
         *
         *      AdsStream dataStream = new AdsStream(streamLength);
         *      AdsBinaryReader reader = new AdsBinaryReader(dataStream);
         *      for (int i = 0; i < size.Length; i++)
         *      {
         *          List<object> o = new List<object>();
         *          for (int j = 0; j < size[i]; j++)
         *          {
         *              object obj = new object();
         *              if (!ReadObject(reader, types[i], out obj))
         *                  message = String.Format("Error while reading " + types[i] + " at struct position (i, j): (" + i + ", " + j + ")");
         *              o.Add(obj);
         *          }
         *          output.Add(o);
         *      }
         *
         *      return message;
         *  }
         *  catch (Exception e)
         *  {
         *      return e.ToString();
         *  }
         *
         * }
         */


        public void WriteStruct(string structName, string[] types, object[][] values)
        {
            int dataStreamLength = 0;

            for (int i = 0; i < values.Length; i++)
            {
                dataStreamLength += StreamLength(types[i]) * values[i].Length;
            }

            using (AdsStream dataStream = new AdsStream(dataStreamLength))
                using (AdsBinaryWriter writer = new AdsBinaryWriter(dataStream))
                {
                    int varHandle = TcClient.CreateVariableHandle(structName);
                    dataStream.Position = 0;

                    for (int i = 0; i < values.Length; i++)
                    {
                        foreach (object obj in values[i])
                        {
                            WriteObjectToWriter(writer, types[i], obj);
                            if (types[i] == "string")
                            {
                                dataStream.Position += 81 - obj.ToString().Length;
                            }
                        }
                    }

                    TcClient.Write(varHandle, dataStream);
                    writer.Flush();
                }
        }
Пример #20
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);
                        }
                    }
                }
            }
        }
Пример #21
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);
        }
        public DisposableNotificationHandleBag(IAdsConnection client, IEnumerable <ISymbol> symbols, NotificationSettings settings, object userData) : base(client)
        {
            if (symbols == null)
            {
                throw new ArgumentNullException("dict");
            }
            int length = Enumerable.Sum <ISymbol>(symbols, s => s.ByteSize);

            this._stream           = new AdsStream(length);
            base.handleDict        = new SumHandleList();
            this._handleSymbolDict = new Dictionary <uint, ISymbol>();
            base.validHandleDict   = new Dictionary <string, uint>();
            int offset = 0;

            foreach (ISymbol symbol in symbols)
            {
                uint         handle    = 0;
                int          byteSize  = symbol.ByteSize;
                AdsErrorCode errorCode = client.TryAddDeviceNotification(symbol.InstancePath, this._stream, offset, byteSize, settings, userData, out handle);
                base.handleDict.Add(new SumHandleInstancePathEntry(symbol.InstancePath, handle, errorCode));
                if (errorCode == AdsErrorCode.NoError)
                {
                    base.validHandleDict.Add(symbol.InstancePath, handle);
                    this._handleSymbolDict.Add(handle, symbol);
                }
                offset += byteSize;
            }
        }
Пример #23
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);
        }
Пример #24
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);
        }
Пример #25
0
 public MainWindow()
 {
     InitializeComponent();
     _tcClient      = new TcAdsClient();
     adsReadStream  = new AdsStream(4);
     adsWriteStream = new AdsStream(4);
     DataContext    = this;
 }
 public override void VarSize(int arraySize, int arrayTypeSize)
 {
     m_arraySize  = arraySize;
     m_size       = arraySize * arrayTypeSize;
     m_dataStream = new AdsStream(m_size);
     m_binRead    = new BinaryReader(m_dataStream);
     m_binWrite   = new BinaryWriter(m_dataStream);
 }
Пример #27
0
 public PLCAny(PLC plc, string Name)
 {
     m_plc        = plc;
     m_hVar       = plc.AdsClient.CreateVariableHandle(Name);
     m_varName    = Name;
     m_dataStream = new AdsStream(31);
     m_binRead    = new BinaryReader(m_dataStream, System.Text.Encoding.ASCII);
 }
Пример #28
0
 private void Form1_Load_1(object sender, EventArgs e)
 {
     _tcClient      = new TcAdsClient();
     adsReadStream  = new AdsStream(100);
     adsWriteStream = new AdsStream(100);
     tabPage1.Text  = "通讯";
     tabPage2.Text  = "控制";
     tabPage3.Text  = "机械臂";
 }
Пример #29
0
        public override int AddNotification(string variableName, AdsStream data, int offset, int length, int transMode, int cycleTime, int maxDelay, object userData, out AdsErrorCode result)
        {
            int clientHandle = 0;

            result = base._symbolTable.TryCreateVariableHandle(variableName, out clientHandle);
            if (result != AdsErrorCode.NoError)
            {
                return(0);
            }
            uint serverHandle = base._symbolTable.GetServerHandle(clientHandle, out result);

            if (result != AdsErrorCode.NoError)
            {
                return(0);
            }
            result = AdsErrorCode.NoError;
            if (!base._bInitialized)
            {
                this.Init();
            }
            cycleTime /= 0x2710;
            if (cycleTime <= 50)
            {
                cycleTime = 50;
            }
            int nextHandle          = this.GetNextHandle();
            NotificationEntry entry = base.AddNotification(nextHandle, nextHandle, clientHandle, data, offset, length, userData);
            ITimer            timer = this._timer;

            lock (timer)
            {
                CycleTableEntry entry2;
                if (!this._cycleTable.TryGetValue(cycleTime, out entry2))
                {
                    entry2 = new CycleTableEntry {
                        lastRead   = NativeMethods.GetTickCount(),
                        timerCount = 0,
                        cycleList  = new List <CycleListEntry>()
                    };
                    this._cycleTable.Add(cycleTime, entry2);
                }
                CycleListEntry item = new CycleListEntry {
                    handle   = nextHandle,
                    variable =
                    {
                        indexGroup  =       0xf005,
                        indexOffset = serverHandle,
                        length      = entry.length
                    },
                    transMode = transMode,
                    data      = new byte[entry.length]
                };
                entry2.cycleList.Add(item);
                this._initialNotes.Add(item);
            }
            return(nextHandle);
        }
Пример #30
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();
        }
Пример #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;
        }
Пример #32
0
        /**
         * Reads one variable from the PLC. The variable must be declared as a REAL.
         *
         * Input:
         * tcAds - TwinCat ADS client object
         * var - The variable name (as a string) to be read from the PLC. E.g "MAIN.var1"
         * vartype - The variable type as declared in the PLC. REAL is the only supported variable type.
         * More types can be added by making changes where appropriate.
         *
         * Output: Floating value representing the value in the PLC.
         *
        **/
        static float readByString(TcAdsClient tcAds,string var,string vartype)
        {
            int hVar = 0;
            try
            {
                hVar = tcAds.CreateVariableHandle(var);
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }
            if (vartype == "REAL")
            {
                // creates a stream with a length of 4 byte
                AdsStream ds = new AdsStream(4);
                BinaryReader br = new BinaryReader(ds);
                tcAds.Read(hVar, ds);
                try
                {
                    tcAds.DeleteVariableHandle(hVar);
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }

                return br.ReadSingle();
            }
            else {
                Console.WriteLine("Error: Variable type not implemented!");
                return 0.0F;
            }
        }
Пример #33
0
        public void WriteAdsValue(IWoopsaProperty property, IWoopsaValue value)
        {
            WoopsaAdsProperty adsProperty = (WoopsaAdsProperty)property;
            AdsStream stream = new AdsStream();

            switch (property.Type)
            {
                case WoopsaValueType.Integer:
                    if (adsProperty.AdsInfo.Type == BeckhoffValueType.WORD ||
                        adsProperty.AdsInfo.Type == BeckhoffValueType.UINT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToUInt16()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.DWORD ||
                            adsProperty.AdsInfo.Type == BeckhoffValueType.UDINT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToUInt32()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.SINT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToSByte()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.INT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToInt16()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.DINT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToInt32()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.LINT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToInt64()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.USINT ||
                             adsProperty.AdsInfo.Type == BeckhoffValueType.BYTE)
                    {
                        stream = new AdsStream(1);
                        stream.WriteByte(value.ToByte());
                    }
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.ULINT)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToUInt64()));
                    else
                        throw new WoopsaException("Ads type not compatible with Woopsa Integer");
                    break;
                case WoopsaValueType.Logical:
                    stream = new AdsStream(BitConverter.GetBytes(value.ToBool()));
                    break;
                case WoopsaValueType.Real:
                    if (adsProperty.AdsInfo.Type == BeckhoffValueType.REAL)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToFloat()));
                    else if (adsProperty.AdsInfo.Type == BeckhoffValueType.LREAL)
                        stream = new AdsStream(BitConverter.GetBytes(value.ToDouble()));
                    else
                        throw new WoopsaException("Ads type not compatible with Woopsa Real");
                    break;
                case WoopsaValueType.Text:
                    stream = new AdsStream(80);
                    byte[] byteString = System.Text.Encoding.ASCII.GetBytes(value.ToString());
                    stream.Write(byteString, 0, byteString.Length);
                    break;
                case WoopsaValueType.TimeSpan:
                    stream = new AdsStream(BitConverter.GetBytes((uint)(value.ToTimeSpan().Ticks / TimeSpan.TicksPerMillisecond)));
                    break;
                case WoopsaValueType.DateTime:
                    TimeSpan timeSp;
                    DateTime dateTime;
                    if (adsProperty.AdsInfo.Type == BeckhoffValueType.TIME_OF_DAY)
                    {
                        dateTime = value.ToDateTime();
                        uint timeOfDay = (uint)dateTime.Millisecond + ((uint)dateTime.Second + ((uint)dateTime.Minute + ((uint)dateTime.Hour * 60)) * 60) * 1000;
                        stream = new AdsStream(BitConverter.GetBytes(timeOfDay));
                    }
                    else
                    {
                        timeSp = value.ToDateTime() - BeckhoffPlcReferenceDateTime;
                        stream = new AdsStream(BitConverter.GetBytes((uint)timeSp.TotalSeconds));
                    }
                    break;
                default:
                    stream = new AdsStream(1);
                    break;
            }
            _tcAds.Write(adsProperty.AdsInfo.IndexGroup, adsProperty.AdsInfo.IndexOffset, stream);
        }
Пример #34
0
        public WoopsaValue ReadAdsValue(IWoopsaProperty woopsaProperty)
        {
            WoopsaAdsProperty property = (WoopsaAdsProperty)woopsaProperty;
            AdsStream stream = new AdsStream(80); // for STRING(80)
            long data = 0;

            stream.Flush();
            try
            {
                _tcAds.Read(property.AdsInfo.IndexGroup, property.AdsInfo.IndexOffset, stream);
            }
            catch (Exception)
            {
                isAdsConnected = false;
                return null;
            }
            switch (property.Type)
            {
                case WoopsaValueType.Integer:
                    if (property.AdsInfo.Type == BeckhoffValueType.WORD ||
                        property.AdsInfo.Type == BeckhoffValueType.UINT)
                        return BitConverter.ToUInt16(stream.GetBuffer(), 0);
                    else if (property.AdsInfo.Type == BeckhoffValueType.DWORD ||
                            property.AdsInfo.Type == BeckhoffValueType.UDINT)
                        return BitConverter.ToUInt32(stream.GetBuffer(), 0);
                    else if (property.AdsInfo.Type == BeckhoffValueType.SINT)
                        return Convert.ToSByte((sbyte)stream.GetBuffer()[0]);
                    else if (property.AdsInfo.Type == BeckhoffValueType.INT)
                        return BitConverter.ToInt16(stream.GetBuffer(), 0);
                    else if (property.AdsInfo.Type == BeckhoffValueType.DINT)
                        return BitConverter.ToInt32(stream.GetBuffer(), 0);
                    else if (property.AdsInfo.Type == BeckhoffValueType.LINT || property.AdsInfo.Type == BeckhoffValueType.ULINT)
                        return BitConverter.ToInt64(stream.GetBuffer(), 0);
                    else if (property.AdsInfo.Type == BeckhoffValueType.USINT || property.AdsInfo.Type == BeckhoffValueType.BYTE)
                        return (byte)stream.GetBuffer()[0];
                    else
                        throw new WoopsaException("Ads type not compatible with Woopsa Integer");
                case WoopsaValueType.Logical:
                    return Convert.ToBoolean(stream.GetBuffer()[0]);
                case WoopsaValueType.Real:
                    if (property.AdsInfo.Type == BeckhoffValueType.REAL)
                        return BitConverter.ToSingle(stream.GetBuffer(), 0);
                    else if (property.AdsInfo.Type == BeckhoffValueType.LREAL)
                        return BitConverter.ToDouble(stream.GetBuffer(), 0);
                    else
                        throw new WoopsaException("Ads type not compatible with Woopsa Real");
                case WoopsaValueType.Text:
                    string s = System.Text.Encoding.ASCII.GetString(stream.GetBuffer());
                    int index = s.IndexOf('\0');
                    return s.Remove(index, s.Length - index);
                case WoopsaValueType.TimeSpan:
                    data = bufferToLong(stream.GetBuffer(), 4);
                    TimeSpan timeSpan = new TimeSpan(TimeSpan.TicksPerMillisecond * data);
                    return timeSpan;
                case WoopsaValueType.DateTime:
                    TimeSpan timeSp;
                    DateTime dateTime;
                    data = bufferToLong(stream.GetBuffer(), 4);
                    dateTime = BeckhoffPlcReferenceDateTime;
                    if (property.AdsInfo.Type == BeckhoffValueType.TIME_OF_DAY)
                        timeSp = TimeSpan.FromMilliseconds(data);
                    else
                        timeSp = TimeSpan.FromSeconds(data);
                    dateTime = dateTime + timeSp;
                    WoopsaValue value = new WoopsaValue(dateTime);
                    return value;
                default:
                    return null;
            }
        }