Esempio n. 1
0
 private void CreateHandles(TcAdsClient ads)
 {
     hDB       = ads.CreateVariableHandle("MAIN.ConnectDB.DBInfo.MYSQLConnectionInfo.DB");
     hServer   = ads.CreateVariableHandle("MAIN.ConnectDB.DBInfo.MYSQLConnectionInfo.server");
     hUser     = ads.CreateVariableHandle("MAIN.ConnectDB.DBInfo.MYSQLConnectionInfo.user");
     hPassword = ads.CreateVariableHandle("MAIN.ConnectDB.DBInfo.MYSQLConnectionInfo.password");
 }
Esempio n. 2
0
        public ObservableForTests()
        {
            adsClient = new TcAdsClient();
            adsClient.Connect(851);

            client = new TwinCatRxClient(adsClient);
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Asyncronus write adds the write operation to PendingOps list
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="ParamAddress"></param>
        //public void WriteValue(int ID, int ParamAddress, Object newValue)
        //{
        //	Task<bool> t = Task.Run(() =>
        //	{
        //		return WriteValue(ParamAddress, newValue);
        //	}
        //	);

        //	object[] d = new object[] { ID, ParamAddress, t };
        //	PendingOps.Add(d);
        //}

        public void Move()
        {
            if (IsBeckhoff)
            {
                TcAdsClient Kid = (TcAdsClient)this.Client;
            }
        }
Esempio n. 5
0
        public StreamTests()
        {
            adsClient = new TcAdsClient();
            adsClient.Connect(851);

            client = new TwinCatRxClient(adsClient);
        }
        ///////////////////////////////////////////////////////////////////////////////
        public TwincatConfig(TcAdsClient _tcAds)
        {
            string type = "";

            try
            {
                this.m_tcAds   = _tcAds;
                this.Variables = new Dictionary <string, TwincatVariable>();

                this.m_symbolLoader = this.m_tcAds.CreateSymbolInfoLoader();



                foreach (TcAdsSymbolInfo symbol in this.m_symbolLoader)
                {
                    if (symbol.Name.Contains("UBS_"))
                    {
                        type = symbol.Type.ToString();

                        if (this.m_tipos.ContainsKey(type))
                        {
                            this.Variables.Add(symbol.Name, new TwincatVariable(symbol, this.m_tipos[type]));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(new Form()
                {
                    TopMost = true
                }, type + e.ToString(), "Error", MessageBoxButtons.OK);
            }
        }
Esempio n. 7
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. 8
0
        private void IOPage_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;

            ioClient = new TcAdsClient();

            try
            {
                ioClient.Connect(851);
            }
            catch (Exception err)
            {
                MessageBox.Show("IO page: client to PLC: " + err.Message);
            }

            try
            {
                ioClient.AddDeviceNotificationEx("GVL_General.bLamp01", AdsTransMode.OnChange, 100, 0, ioBtnLamp01, typeof(Boolean));
                ioClient.AddDeviceNotificationEx("GVL_General.bLamp02", AdsTransMode.OnChange, 100, 0, ioBtnLamp02, typeof(Boolean));
                ioClient.AddDeviceNotificationEx("GVL_General.bLamp03", AdsTransMode.OnChange, 100, 0, ioBtnLamp03, typeof(Boolean));
                ioClient.AddDeviceNotificationEx("GVL_General.bLamp04", AdsTransMode.OnChange, 100, 0, ioBtnLamp04, typeof(Boolean));

                ioClient.AdsNotificationEx += Client_AdsNotificationEx;
            }
            catch (Exception)
            {
                // throw;
                MessageBox.Show("add device notification");
            }
        }
Esempio n. 9
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);
        }
Esempio n. 10
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="client">TwinCAT ADS client. It should be connected</param>
        /// <param name="defaultCycleTime">Default cycle time the ADS client will poll for changes</param>
        /// <param name="maxDelay">Maximum ADS delay</param>
        public TwinCatRxClient(TcAdsClient client, int defaultCycleTime = 100, int maxDelay = 100)
        {
            _defaultCycleTime = defaultCycleTime;
            _maxDelay         = maxDelay;

            OnIninitialize(client);
        }
Esempio n. 11
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);
 }
Esempio n. 12
0
 public void ReadConnectionInfo(TcAdsClient ads)
 {
     server   = ads.ReadAny(hServer, typeof(string), new int[] { 255 }).ToString();
     user     = ads.ReadAny(hUser, typeof(string), new int[] { 255 }).ToString();
     password = ads.ReadAny(hPassword, typeof(string), new int[] { 255 }).ToString();
     DB       = ads.ReadAny(hDB, typeof(string), new int[] { 255 }).ToString();
 }
Esempio n. 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;
        }
        /// <summary>
        /// Connects to TwinCAT Ads via TcAdsClient.Connect. Hooks up Ads events to logging text box
        /// </summary>
        /// <param name="amsNetId">As defined in TwinCAT Project (in Project > System > Routes > Project Routes). Something like 192.168.0.1.1.1 </param>
        /// <param name="port">As defined in TwinCAT. Normally 851 or 852</param>
        public void Connect(string amsNetId, int port)
        {
            try
            {
                if (TcClient == null)
                {
                    TcClient = new TcAdsClient();
                }

                TcClient.ConnectionStateChanged  += TcClient_ConnectionStateChanged;
                TcClient.AdsNotification         += TcClient_AdsNotification;
                TcClient.AdsNotificationError    += TcClient_AdsNotificationError;
                TcClient.AdsNotificationEx       += TcClient_AdsNotificationEx;
                TcClient.AdsStateChanged         += TcClient_AdsStateChanged;
                TcClient.AdsSymbolVersionChanged += TcClient_AdsSymbolVersionChanged;
                TcClient.AmsRouterNotification   += TcClient_AmsRouterNotification;

                AmsNetId id = new AmsNetId(amsNetId);
                TcClient.Connect(id, port);
            }
            catch (Exception e)
            {
                Send_TcClient_EventHandling(DateTime.Now, LogTextCategory.Error, string.Format("Could not connect to ADS Server: {0}", e));
            }
        }
Esempio n. 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);
            }
        }
Esempio n. 16
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. 17
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. 18
0
 public AdsKid(TcAdsClient MOM, int KidIndex)
 {
     LastPolled.Start();
     if (!Connected)
     {
         try
         {
             this.Mom           = MOM;
             this.kidIndex      = KidIndex;
             TargetPosAddr      = MOM.CreateVariableHandle("MAIN.Kid[" + kidIndex + "].targetpos_FromMom_Raw");
             CurrentPosAddr     = MOM.CreateVariableHandle("MAIN.Kid[" + kidIndex + "].HomedPosition_toMom");
             ModeVelAddr        = MOM.CreateVariableHandle("MAIN.Kid[" + kidIndex + "].ModeVel_FromMom");
             ModeAccelAddr      = MOM.CreateVariableHandle("MAIN.Kid[" + kidIndex + "].ModeAccel_FromMom");
             ModeDecelAddr      = MOM.CreateVariableHandle("MAIN.Kid[" + kidIndex + "].ModeDecel_FromMom");
             DeadManPressedAddr = Mom.CreateVariableHandle("MAIN.Kid[" + KidIndex + "].RMT_DeadManPressed");
             ScalingIntAddr     = Mom.CreateVariableHandle("MAIN.Kid[" + KidIndex + "].ScalingNumber");
             MomControlAddr     = Mom.CreateVariableHandle("MAIN.Kid[" + KidIndex + "].CheckIn.MomControl");
             string checkStr = MOM.ReadAny(TargetPosAddr, typeof(int)).ToString();
             //  TcAdsSymbolInfoLoader tcl = MOM.CreateSymbolInfoLoader();
             // TcAdsSymbolInfo tci = tcl.FindSymbol("MAIN.Kid[" + KidIndex + "].SCALINGINT");
             currentPosition = int.Parse(MOM.ReadAny(CurrentPosAddr, typeof(int)).ToString());
             targetPosition  = currentPosition;
             Connected       = true;
         }
         catch
         {
             Connected = false;
             throw;
         }
     }
 }
Esempio n. 19
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);
        }
Esempio n. 20
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);
            }
        }
Esempio n. 21
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            try
            {
                log.Debug("Start app debugging");
                log.Info("Start timer tick- 10sec ");
                InitTimer();

                //Connecto ADS Server
                log.Info("Connecting to PLC via ADS ");
                adsClient = new TcAdsClient();
                adsClient.Connect(netidplc, 851);

                symbolLoader = adsClient.CreateSymbolInfoLoader();

                //Open connection
                log.Info("Connecting to PostgreSQL Server ");
                TestconnOpen();

                //Open connection
                log.Info("Connecting to PostgreSQL Server ");

                PrepareLiveTable();
                PrepareAccuTable();
            }
            catch (Exception err)
            {
                log.Debug(err.Message);
            }
        }
Esempio n. 22
0
        private void OnIninitialize(TcAdsClient client)
        {
            _client             = client;
            _client.Synchronize = false; // This makes notifications come in on a ThreadPool thread instead of the UI thread

            _notifications = Observable.FromEventPattern <AdsNotificationExEventHandler, AdsNotificationExEventArgs>(
                h => _client.AdsNotificationEx += h, h => _client.AdsNotificationEx -= h).Publish().RefCount();
        }
Esempio n. 23
0
        public DataViewModel(IEventAggregator events)
        {
            ViewName    = ViewName.Data;
            tcAdsClient = new TcAdsClient();
            m_Event     = events;

            m_Event.Subscribe(this);
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PollingManagerForTagListener"/> class.
 /// </summary>
 /// <param name="tagListener">The tag listener.</param>
 /// <param name="twinCatClient">The twin cat client.</param>
 /// <param name="pollingRate">The polling rate.</param>
 /// <param name="globalLock">A class managing locking globally within the application.</param>
 /// <param name="logger">A logger for standard message logging</param>
 public PollingManagerForTagListener(BeckhoffPollingTagListener tagListener, TcAdsClient twinCatClient, int pollingRate, IGlobalLock globalLock, ILogger logger = null)
 {
     _tagListener   = tagListener;
     _twinCatClient = twinCatClient;
     _globalLock    = globalLock;
     _logger        = logger ?? new NullLogger();
     PollingRate    = pollingRate;
 }
Esempio n. 25
0
 internal ControllerConnection(TcAdsClient client)
 {
     _client           = client;
     _declarationSpace = new DeclarationSpace(this);
     _infoLoader       = _client.CreateSymbolInfoLoader();
     _infoLoader.GetFirstSymbol(true);
     _symbols = _infoLoader.GetSymbols(forceReload: true);
 }
Esempio n. 26
0
 public MainWindow()
 {
     InitializeComponent();
     _tcClient      = new TcAdsClient();
     adsReadStream  = new AdsStream(4);
     adsWriteStream = new AdsStream(4);
     DataContext    = this;
 }
 ///////////////////////////////////////////////////////////////////////////////
 public TwinCatCommunication(UBSLib.UBSModule parent)
 {
     tcAds            = new TcAdsClient();
     m_TCbloques      = new Dictionary <int, TCBlock>();
     m_BlockMap       = new Dictionary <string, int>();
     lastNotification = DateTime.Now;
     UBSMod           = parent;
 }
Esempio n. 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  = "机械臂";
 }
 public TCBlock(int id, Dictionary <string, TwincatVariable> dict, string filename, TwinCatCommunication comm)
 {
     m_id          = id;
     m_filename    = filename.Insert(filename.LastIndexOf('.'), id.ToString());
     parent        = comm;
     tcAds         = new TcAdsClient();
     notifications = new Dictionary <int, string>();
     IOparameters  = new IO_Parameters(dict);
 }
Esempio n. 30
0
        public void Connect(TcAdsClient ads)
        {
            CreateHandles(ads);
            ReadConnectionInfo(ads);
            ConnectionString = CreateConnectionString();

            Connected = true;
            Console.WriteLine("connected to SQLite DB");
        }
Esempio n. 31
0
        /**
         *  Reads the variables contained in the list "vars" (read from the config file).
         *  Adds each  supplied variable name as a key to a JSON-object, as well as its value
         *  as read from the PLC. A timestamp is added (Linux epoch milliseconds). The JSON-object
         *  is then sent to CouchDB.
        **/
        static void Main(string[] args)
        {
            TcAdsClient tcAds = new TcAdsClient();

            //Dictionary containing the configuration keys and values from the data.conf file.
            Dictionary<string, string> props = new Dictionary<string, string>();

            //List containing the variables to be read from the PLC and stored in the CouchDB database
            List<string> vars = new List<string>();

            //Populate the props dictionary and vars list from the content of the data.conf file
            readFile(props, vars, "data.conf");

            //Connect to the PLC
            Console.WriteLine("Connecting to " + props["netId"] + " on port " + props["adsport"]);
            tcAds.Connect(props["netId"], Convert.ToUInt16(props["adsport"]));

            //Create and build the JSON-object.
            JObject jobj = new JObject();
            jobj.Add("timestamp",(long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds);
            foreach (string s in vars)
            {
                float value = readByString(tcAds, s, "REAL");
                jobj.Add(s, value);
            }

            //End connection to the PLC.
            tcAds.Dispose();

            //Info printout of JSON-object
            Console.WriteLine(jobj.ToString());

            //Create a web request for posting to CouchDB.
            WebRequest request = WebRequest.Create(props["dbprotocol"]+"://"+props["dbip"]+":"+props["dbport"]+"/"+props["dbname"]);
            request.Method = "POST";
            request.Credentials = new NetworkCredential(props["dbusername"],props["dbpassword"]);
            string postData = jobj.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/json";
            request.ContentLength = postData.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //Get and print the response from the server
            WebResponse response = request.GetResponse();
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);

            reader.Close();
            dataStream.Close();
            response.Close();
        }
Esempio n. 32
0
 public WoopsaAdsServer(string netId)
 {
     _netId = netId;
     _tcAds = new TcAdsClient();
     try
     {
         _tcAds.Connect(netId, _PORT);
     }
     catch (Exception)
     {
         isAdsConnected = false;
     }
     _woopsaAdsPropertyGet = this.ReadAdsValue;
     _woopsaAdsPropertySet = this.WriteAdsValue;
 }
Esempio n. 33
0
        public MainWindow()
        {
            InitializeComponent();

            mGlobalWindow = this;
            mAdsClient = new TcAdsClient();

            menu.RegisterObeserver(this);

            sRedLight = new BitmapImage(new Uri("/image/debug_light_red.png", UriKind.Relative));
            sGreenLight = new BitmapImage(new Uri("/image/debug_light_green.png", UriKind.Relative));
            sDisableLight = new BitmapImage(new Uri("/image/debug_light_disable.png", UriKind.Relative));
            sEnableLight = new BitmapImage(new Uri("/image/debug_light_enable.png", UriKind.Relative));
            sSwitchOn = new BitmapImage(new Uri("/image/SwitchOn.bmp", UriKind.Relative));
            sSwitchOff = new BitmapImage(new Uri("/image/SwitchOff.bmp", UriKind.Relative));

            tmUserLogout.Tick += new EventHandler(tmLogout_Tick);
            tmUserLogout.Interval = TimeSpan.FromSeconds(300);

            InitBeckHoff();
        }
Esempio n. 34
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;
            }
        }
Esempio n. 35
0
        public BeckHoff(TcAdsClient adsClient)
        {
            this.adsClient = adsClient;
            foreach (String name in plcVariableNameTypes)
            {
                Type t = typeof(int);
                if(name.StartsWith(BOOL_TOKON)){
                    t = typeof(Boolean);
                }

                String varName = name.Substring(1);

                plcVariableNames.Add(varName);
                plcVarTypeMap.Add(varName,t);
                createPlcAccessHandle(varName);
            }

            mWriteFlagHandle = adsClient.CreateVariableHandle(".WriteFlag");
            initThreadHold();
            initVarDescription();
        }
Esempio n. 36
0
        public override void init()
        {
            adsClient = new TcAdsClient();
            nameDict["MAIN.MDF_WhichStack"] = typeof(int);
            nameDict["MAIN.MDF_WhichDish"] = typeof(int);
            nameDict["MAIN.MDF_RunningError"] = typeof(int);
            nameDict["MAIN.MDF_online_state"] = typeof(int);
            nameDict["MAIN.MDF_Command_response"] = typeof(String);
            nameDict["MAIN.MDF_bar_code"] = typeof(string);
            nameDict["MAIN.MDF_Motor_1_cur"] = typeof(float);
            nameDict["MAIN.MDF_Motor_2_cur"] = typeof(float);
            nameDict["MAIN.MDF_Motor_3_cur"] = typeof(float);
            nameDict["MAIN.MDF_Motor_4_cur"] = typeof(float);
            nameDict["MAIN.CCS_to_MDF_command_listen"] = typeof(String);
            nameDict["MAIN.CCS_to_MDF_NumsperStack_listen"] = typeof(int);
            nameDict["MAIN.CCS_to_MDF_VolsperDish_listen"] = typeof(float);
            cmdString = "MAIN.MDF_Command_response";
            try
            {
                adsClient.Connect(801);
                adsClient.AdsNotificationEx += new AdsNotificationExEventHandler(handleNotification);
                foreach (String s in nameDict.Keys)
                {
                    handleMap[s] = adsClient.CreateVariableHandle(s);
                    if (nameDict[s] == typeof(string))
                    {
                        adsClient.AddDeviceNotificationEx(s, AdsTransMode.OnChange, 100, 0, s, nameDict[s],new int[]{ConstSettings.StringLength});
                    }
                    else
                    {
                        adsClient.AddDeviceNotificationEx(s, AdsTransMode.OnChange, 100, 0, s, nameDict[s]);
                    }
                }
                adsClient.WriteAny(handleMap["MAIN.MDF_online_state"], 1);
            }
            catch (Exception ex)
            {

            }
        }