Example #1
0
        private void button1_Click(object sender, EventArgs e)        //Turnon
        {
            try
            {
                Form1_Load(sender, e);

                AdsStream adsStream = new AdsStream(30);
                //		AdsBinaryReader reader = new AdsBinaryReader(adsStream);
                //		adsClient.Read(intStart, adsStream);

                AdsStream adsStream2 = new AdsStream(30);
                //		AdsBinaryReader reader2 = new AdsBinaryReader(adsStream2);
                //		adsClient.Read(intStatus, adsStream2);

                AdsStream adsStream3 = new AdsStream(30);

                //		blStart = reader.ReadBoolean();
                //		blStatus = reader2.ReadBoolean();

                //	if (blStart == false)
                //	{
                label2.Text = adsClient.ReadAny(intStart, typeof(Boolean)).ToString();
                label3.Text = adsClient.ReadAny(intStop, typeof(Boolean)).ToString();
                label4.Text = adsClient.ReadAny(intStatus, typeof(Boolean)).ToString();

                blStart  = true;
                blStatus = true;
                blStop   = false;

                AdsBinaryWriter write = new AdsBinaryWriter(adsStream);
                adsClient.WriteAny(intStart, blStart);

                AdsBinaryWriter writer2 = new AdsBinaryWriter(adsStream2);
                adsClient.WriteAny(intStatus, blStatus);

                AdsBinaryWriter writer3 = new AdsBinaryWriter(adsStream3);
                adsClient.WriteAny(intStop, blStop);

                label1.Text = "Đã bật đèn";
                label5.Text = adsClient.ReadAny(intStart, typeof(Boolean)).ToString();
                label6.Text = adsClient.ReadAny(intStop, typeof(Boolean)).ToString();
                label7.Text = adsClient.ReadAny(intStatus, typeof(Boolean)).ToString();
                //	}
                //	else
                //blStatus = true;
                //		label1.Text = "TRUE nè";

                adsClient.Dispose();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Example #2
0
 public void Dispose()
 {
     if (!_tcAds.Disposed)
     {
         _tcAds.Dispose();
     }
 }
Example #3
0
 private void button1_Click(object sender, EventArgs e)          //ReadButton
 {
     try
     {
         Form1_Load(sender, e);
         AdsStream       adsStream = new AdsStream(30);
         AdsBinaryReader reader    = new AdsBinaryReader(adsStream);
         adsClient.Read(varHandle, adsStream);
         textBox1.Text = reader.ReadPlcAnsiString(30).ToString();
         adsClient.Dispose();
     }
     catch (Exception err)
     {
         MessageBox.Show(err.Message);
     }
 }
Example #4
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);
        }
Example #5
0
 public void Dispose()
 {
     foreach (var item in NotifyParameters)
     {
         try
         {
             _tcClient.DeleteDeviceNotification(item.Value.NotifyID);
         }
         catch (Exception)
         {
             // ignored
         }
     }
     try
     {
         _tcClient.AdsNotification -= tcClient_AdsNotification;
         _tcClient.Dispose();
         _dataStream.Close();
         _dataStream.Dispose();
         _binReader.Close();
     }
     catch (Exception)
     {
         // ignored
     }
 }
Example #6
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);
        }
Example #7
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);
            }
        }
Example #8
0
 private void Window_Closing(object sender, CancelEventArgs e)
 {
     if (tcclient != null)
     {
         tcclient.Dispose();
     }
 }
 public void Dispose()
 {
     if (_client != null)
     {
         _client.Dispose();
     }
 }
Example #10
0
        public void Dispose()
        {
            if (_client != null)
            {
                if (_eventSymbols.Count > 0)
                {
                    // unregister events
                    foreach (string symbol in _eventSymbols)
                    {
                        IValueSymbol symb = (IValueSymbol)_symbolLoader.Symbols[symbol];
                        symb.ValueChanged -= Symbol_ValueChanged;
                    }
                }

                // dispose custom event container
                _dynamicEvents.Dispose();


                // disconnect client
                if (_client.IsConnected)
                {
                    _client.Disconnect();
                }

                _client.Dispose();
            }
        }
Example #11
0
 public static void Disconnect()
 {
     try
     {
         foreach (int handle in NotificationHandles)
         {
             TwinCat3Client.DeleteDeviceNotification(handle);
         }
         TwinCat3Client.Dispose();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     NotificationHandles.Clear();
     TwinCat3Client.Dispose();
 }
Example #12
0
        private void DateTimeSample_FormClosing(object sender, FormClosingEventArgs e)
        {
            client.DeleteVariableHandle(hdate1);
            client.DeleteVariableHandle(htime1);
            client.DeleteVariableHandle(hdate2);

            client.Dispose();
        }
        public async Task OnExecute()
        {
            var adsClient = new TcAdsClient {
                Synchronize = false
            };
            var handle = GetConsoleWindow();

            ShowWindow(handle, SW_HIDE);

            CreateLogger();
            var logger = LoggerFactory.GetLogger();

            try
            {
                logger.Debug("Starting Json Read Writer");
                logger.Debug($"Connecting to Beckhoff Port: {AdsPort} - AdsNet: '{AdsNetId}'");
                adsClient.Connect(AdsNetId, AdsPort);

                logger.Debug($"Method: {Method}");

                logger.Debug($"File: {FilePath}");

                logger.Debug($"Field: {Field}");

                logger.Debug($"Executing...");

                if (Method == FileOperationMethod.Write)
                {
                    var content = File.ReadAllText(FilePath);
                    logger.Debug($"Writing json into {Field}...");
                    var objectResponse = JObject.Parse(content);
                    await adsClient.WriteJson(Field, objectResponse);
                }
                else if (Method == FileOperationMethod.Read)
                {
                    var json = await adsClient.ReadJson(Field);

                    File.WriteAllText(FilePath, json.ToString());
                }
                else
                {
                    logger.Warn("Invalid Method");
                }

                adsClient.Disconnect();
            }
            catch (Exception e)
            {
                logger.Error($"Error while calling Json Parser: {e}", e);
                logger.Error($"{e.StackTrace}");
            }
            finally
            {
                adsClient?.Dispose();
            }
        }
Example #14
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();
        }
Example #15
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();
        }
Example #16
0
        private static void SetConfigMode()
        {
            var client = new TcAdsClient();
            var mode   = new StateInfo();

            client.Connect((int)AmsPort.SystemService);
            mode.AdsState = client.ReadState().AdsState;
            mode.AdsState = AdsState.Reconfig;
            client.WriteControl(mode);
            client.Dispose();
        }
Example #17
0
 private void Sample02_FormClosing(object sender, FormClosingEventArgs e)
 {
     try
     {
         client.DeleteVariableHandle(hPLCVar);
     }
     catch (Exception err)
     {
         MessageBox.Show(err.Message);
     }
     client.Dispose();
 }
Example #18
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposedValue == false)
            {
                if (disposing == true)
                {
                    client.Dispose();
                }

                disposedValue = true;
            }
        }
 public bool Disconnect()
 {
     try
     {
         tcAds.Dispose();
         return(true);
     }
     catch (Exception e)
     {
         parent.UBSMod.Error("Error al desconectar el bloque " + m_id + " de comunicaciones. " + e.Message, true, false);
         return(false);
     }
 }
Example #20
0
 /// <summary>
 /// 关闭倍福PLC
 /// </summary>
 /// <param name="tac"></param>
 /// <returns></returns>
 public bool CloseConnect(TcAdsClient tac)
 {
     try
     {
         tac.Close();
         tac.Dispose();
     }
     catch
     {
         return(false);
     }
     return(true);
 }
 ///////////////////////////////////////////////////////////////////////////////
 public bool Disconnect()
 {
     try
     {
         DisconnectBlocks();
         tcAds.Dispose();
         return(true);
     }
     catch (Exception e)
     {
         UBSMod.Error("Error al desconectar los bloques de comunicación. " + e.Message, true, false);
         return(false);
     }
 }
Example #22
0
        static void Main(string[] args)
        {
            string deviceDescription = "USB-4704,BID#0";
            string profilePath       = @"C:\Advantech\Profile\p2.xml";

            tcClient   = new TcAdsClient();
            dataStream = new AdsStream(1);

            instantDoCtrl = new InstantDoCtrl();
            binReader     = new BinaryReader(dataStream, System.Text.Encoding.ASCII);
            tcClient.Connect(851);

            try
            {
                instantDoCtrl.SelectedDevice = new DeviceInformation(deviceDescription);
                errorCode = instantDoCtrl.LoadProfile(profilePath);//Loads a profile to initialize the device.
                if (BioFailed(errorCode))
                {
                    throw new Exception();
                }

                hDigOutP0                 = tcClient.AddDeviceNotification("A4704.byDigOutP0", dataStream, 0, 1, AdsTransMode.OnChange, 10, 0, huValHandle);
                hEndA4704Program          = tcClient.AddDeviceNotification("A4704.bEndA4704Program", dataStream, 0, 1, AdsTransMode.OnChange, 10, 0, huValHandle);
                tcClient.AdsNotification += new AdsNotificationEventHandler(OnNotification);

                HeartbeatThread heartbeat = new HeartbeatThread(tcClient);
                heartbeatThread = new Thread(new ThreadStart(heartbeat.beat));
                heartbeatThread.Start();

                manualResetEvent = new ManualResetEvent(false);
                manualResetEvent.WaitOne();

                //Console.ReadKey(false);
            }
            catch (Exception e)
            {
                // Something is wrong
                string errStr = BioFailed(errorCode) ? " Some error occurred. And the last error code is " + errorCode.ToString()
                                                           : e.Message;
                //Console.WriteLine(errStr);
            }
            finally
            {
                instantDoCtrl.Dispose();
                heartbeatThread.Abort();
                heartbeatThread.Join();
                tcClient.DeleteDeviceNotification(hDigOutP0);
                tcClient.Dispose();
            }
        }
Example #23
0
 private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
 {
     try
     {
         for (int i = 0; i < hLamp.Length; i++)
         {
             client.DeleteDeviceNotification(hLamp[i]);
         }
     }
     catch (Exception err)
     {
         MessageBox.Show("Error: deleteDeviceNotification: " + err.Message);
     }
     client.Dispose();
 }
Example #24
0
        private void OnExit(object sender, EventArgs e)
        {
            //enable resources
            try
            {
                adsClient.DeleteVariableHandle(hTemperature);
                adsClient.DeleteVariableHandle(hProducedPieces);
                adsClient.DeleteVariableHandle(hIsRunning);
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                Console.ReadLine();
            }

            adsClient.Dispose();
        }
Example #25
0
        private void Window_Closed(object sender, EventArgs e)
        {
            PageDataExchange context = PageDataExchange.getInstance();

            context.removeResultObserver(TAG);

            WarnningDataSource observer = WarnningDataSource.GetInstance();

            observer.UnregisterObserver();

            // http://forums.adobe.com/thread/487023
            Win32Helper.CoFreeUnusedLibraries();
            //  Win32Helper.CoUninitialize();

            mAdsClient.Dispose();
            String description = @"退出系统";

            Log.write(Log.CATEGOTY_RUN, description);
        }
Example #26
0
 void DisposeTcADSClient()
 {
     try
     {
         tcClient.DeleteVariableHandle(hVarTcADS_Write_Enable);
         tcClient.DeleteVariableHandle(hVarTcADS_Write_Disable);
         tcClient.DeleteVariableHandle(hVarTcADS_Write_StateRequest);
         tcClient.DeleteVariableHandle(hVarTcADS_Read_Errors);
         tcClient.DeleteVariableHandle(hVarTcADS_Read_SystemStates);
         tcClient.DeleteVariableHandle(hVarTcADS_Read_OpsEnabled);
         tcClient.DeleteVariableHandle(hVarTcADS_Read_LoggerPaused);
         tcClient.DeleteVariableHandle(hVarTcADS_Read_DataToADS);
     }
     catch (Exception err)
     {
         MessageBox.Show(err.Message);
     }
     tcClient.Dispose();
 }
Example #27
0
 public override bool Close()
 {
     try
     {
         if (bInitOK)
         {
             clientStateInfo.AdsState = AdsState.Stop;
             tcClient.WriteControl(clientStateInfo);
         }
         for (int i = 0; i < 3; i++)
         {
             tcClient.DeleteDeviceNotification(posInt[i]);
             tcClient.DeleteDeviceNotification(isMovingInt[i]);
             tcClient.DeleteDeviceNotification(alarmInt[i]);
             tcClient.DeleteDeviceNotification(homeDoneInt[i]);
             //tcClient.DeleteDeviceNotification(cwInt[i]);
             //tcClient.DeleteDeviceNotification(ccwInt[i]);
             //tcClient.DeleteDeviceNotification(homeInt[i]);
             tcClient.DeleteDeviceNotification(isMoveDoneInt[i]);
         }
         for (int i = 1; i <= 6; i++)
         {
             for (int j = 1; j <= 16; j++)
             {
                 tcClient.DeleteDeviceNotification(inputIntNot[i, j]);
                 tcClient.DeleteDeviceNotification(outputIntNot[i, j]);
             }
         }
         Global.bPLCConnected = false;
         bInitOK = false;
         if (tcClient != null)
         {
             tcClient.Disconnect();
             tcClient.Dispose();
         }
     }
     catch (Exception ex)
     {
         Global.bPLCConnected = false;
         bInitOK = false;
     }
     return(true);
 }
        public void Dispose()
        {
            if (!_disposed)
            {
                try
                {
                    _twinCatClient.Dispose();
                    _twinCatClientBackground.Dispose();
                }
                catch (InvalidOperationException e)
                {
                    if (!Debugger.IsAttached)
                    {
                        throw e;
                    }
                }

                _disposed = true;
            }
        }
Example #29
0
        //------------------------------------------------------
        // wird beim Beenden des Programms aufgerufen
        // is activated when ending the program
        //------------------------------------------------------
        private void Close(object sender, EventArgs e)
        {
            try
            {
                // Löschen der Notifications und Handles
                // Deleting of the notifications and handles
                tcClient.DeleteDeviceNotification(hEngine);
                tcClient.DeleteDeviceNotification(hDeviceUp);
                tcClient.DeleteDeviceNotification(hDeviceDown);
                tcClient.DeleteDeviceNotification(hSteps);
                tcClient.DeleteDeviceNotification(hCount);
                tcClient.DeleteDeviceNotification(hSwitchNotify);

                tcClient.DeleteVariableHandle(hSwitchWrite);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            tcClient.Dispose();
        }
Example #30
0
 public void DisconnectPLC()
 {
     timer1.Enabled = false;
     adsClient.Dispose();
 }
Example #31
0
 public void Dispose()
 {
     client = null;
     adsClient.Dispose();
 }