public void LoadSymbols()
        {
            try
            {
                using (var adsClient = new AdsClient())
                {
                    // connection
                    adsClient.Connect(new AmsAddress(_appOptions.Value.AMSNetId, _appOptions.Value.Port));

                    // get the symbol loader, FLAT mode
                    var symbolLoader = SymbolLoaderFactory.Create(adsClient, new SymbolLoaderSettings(SymbolsLoadMode.Flat));

                    if (symbolLoader != null)
                    {
                        _symbolCollection = symbolLoader.Symbols;
                        SymbolInfos       = new BindableCollection <ISymbol>(_symbolCollection);
                        NotifyOfPropertyChange(() => SymbolInfos);
                    }
                }
            }
            catch (ObjectDisposedException exDisposed)
            {
                Console.WriteLine("exception\n" + exDisposed.Message);
            }
            catch (InvalidOperationException exInvalid)
            {
                Console.WriteLine("exception\n" + exInvalid.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Undentified exception\n" + ex.Message);
            }
        }
Esempio n. 2
0
        public static async Task <IEnumerable <Function> > ListFunctionsAsync(AmsNetId target, CancellationToken cancel)
        {
            var functions = new List <Function>();

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));

                foreach (var key in RegistryDefinitions.Keys)
                {
                    try
                    {
                        var name   = RegistryDefinitions[key];
                        var regKey = @"SOFTWARE\WOW6432Node\Beckhoff\TwinCAT3 Functions\" + name + @"\Common";

                        var version = await Registry.QueryValueAsync(target, regKey, "Version");

                        functions.Add(new Function
                        {
                            Name    = name,
                            Version = System.Version.Parse(version),
                            Type    = key
                        });
                    }
                    catch { }
                }
            }

            return(functions);
        }
Esempio n. 3
0
 public static async Task RestartAsync(AmsNetId target, CancellationToken cancel)
 {
     using (AdsClient client = new AdsClient())
     {
         client.Connect(new AmsAddress(target, AmsPort.SystemService));
         await client.WriteControlAsync(AdsState.Reset, 0, cancel);
     }
 }
Esempio n. 4
0
 public static void Restart(AmsNetId target)
 {
     using (AdsClient client = new AdsClient())
     {
         client.Connect(new AmsAddress(target, AmsPort.SystemService));
         client.WriteControl(new StateInfo(AdsState.Reset, 0));
     }
 }
        private void Initialize()
        {
            _adsClient = new AdsClient();
            _adsClient.Connect(Target, AmsPort.SystemService);

            if (!_adsClient.IsConnected)
            {
                throw new Exception("Could not connect to target " + Target.ToString());
            }
        }
Esempio n. 6
0
        public static async Task RebootAsync(AmsNetId target, TimeSpan delay, CancellationToken cancel)
        {
            var data   = BitConverter.GetBytes((int)delay.TotalSeconds);
            var buffer = new ReadOnlyMemory <byte>(data);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                await client.WriteControlAsync(AdsState.Shutdown, 1, buffer, cancel);
            }
        }
Esempio n. 7
0
        public static void Reboot(AmsNetId target, TimeSpan delay)
        {
            var data   = BitConverter.GetBytes((int)delay.TotalSeconds);
            var buffer = new ReadOnlyMemory <byte>(data);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                client.WriteControl(new StateInfo(AdsState.Shutdown, 1), buffer);
            }
        }
Esempio n. 8
0
        public static int GetSystemLatencyMaximum(AmsNetId target)
        {
            var buffer = new Memory <byte>(new byte[8]);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                client.Read(0x01, 0x02, buffer);
            }

            return(BitConverter.ToInt32(buffer.ToArray(), 4));
        }
Esempio n. 9
0
        public static int GetCpuUsage(AmsNetId target)
        {
            var buffer = new Memory <byte>(new byte[4]);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                client.Read(0x01, 0x06, buffer);
            }

            return(BitConverter.ToInt32(buffer.ToArray(), 0));
        }
Esempio n. 10
0
        public static async Task SetLocalTimeAsync(AmsNetId target, DateTime time, CancellationToken cancel)
        {
            var buffer = new ReadOnlyMemory <byte>(BitConverter.GetBytes(time.Ticks));

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                var result = await client.WriteAsync(400, 1, buffer, cancel);

                result.ThrowOnError();
            }
        }
Esempio n. 11
0
        public static async Task <int> GetSystemLatencyMaximumAsync(AmsNetId target, CancellationToken cancel)
        {
            var buffer = new Memory <byte>(new byte[8]);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                var result = await client.ReadAsync(0x01, 0x02, buffer, cancel);

                result.ThrowOnError();
            }

            return(BitConverter.ToInt32(buffer.ToArray(), 4));
        }
Esempio n. 12
0
        private static void Main(string[] args)
        {
            ReadCoe();

            ReadMultipleVariables();
            ReadMultipleVariablesAsDynamic();

            using (var client = new AdsClient())
            {
                client.Connect(NetId, Port);

                ReadSingleVariable(client);
                PrintSymbols(client);
            }

            Console.ReadLine();
        }
        /*
         * public CX9020(Datenstruktur datenstruktur, Action<Datenstruktur> cbInput, Action<Datenstruktur> cbOutput)
         *    {
         *        _spsClient = JsonConvert.DeserializeObject<IpAdressen>(File.ReadAllText("IpAdressen.json"));
         *
         *        _datenstruktur = datenstruktur;
         *
         *        _callbackInput = cbInput;
         *        _callbackOutput = cbOutput;
         *
         *        System.Threading.Tasks.Task.Run(SPS_Pingen_TaskAsync);
         *    }
         */

        public void SPS_Pingen_TaskAsync()
        {
            var cancel = CancellationToken.None;

            var valueWrite = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            var valueRead  = new byte[100];

            while (_taskRunning)
            {
                var pingSender = new Ping();
                var reply      = pingSender.Send(_spsClient.IpAdresse, SpsTimeout);


                if (reply?.Status == IPStatus.Success)
                {
                    _spsStatus = "CX9020 sichtbar (Ping: " + reply.RoundtripTime + "ms)";

                    _adsClient.Connect(_spsClient.AmsNetId, _spsClient.Port);



                    var handleDigInput2 = _adsClient.CreateVariableHandle("Computer.DigInput[2]");
                    var handleDigOutput = _adsClient.CreateVariableHandle("Computer.DigOutput");

                    while (true)
                    {
                        valueRead[2] = (byte)_adsClient.ReadAny(handleDigInput2, typeof(byte));

                        _adsClient.WriteAny(handleDigOutput, valueWrite);

                        valueWrite[0]++;
                        valueWrite[2]++;

                        Thread.Sleep(100);
                    }
                }

                _spsStatus = "Keine Verbindung zur S7-1200!";


                Thread.Sleep(50);
            }

            valueRead[0] = valueRead[2];
        }
Esempio n. 14
0
        public static bool IsTargetReachable(AmsNetId target)
        {
            using (AdsClient client = new AdsClient())
            {
                try
                {
                    client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                    client.ReadState();

                    return(true);
                }
                catch (Exception ex)
                {
                }
            }

            return(false);
        }
        public async Task Should_read_symbols_from_server()
        {
            using (var serverMock = new Mock(12347, "AdsServerMock"))
            {
                serverMock.RegisterReplay(@".\TestFiles\ReadSymbolsPort851.cap");
                using (var client = new AdsClient())
                {
                    // connect to our mocking server
                    client.Connect(serverMock.ServerAddress.Port);
                    if (client.IsConnected)
                    {
                        var symbolLoader = SymbolLoaderFactory.Create(client, new SymbolLoaderSettings(SymbolsLoadMode.Flat, TcAds.ValueAccess.ValueAccessMode.Default));
                        var symbols      = await symbolLoader.GetSymbolsAsync(CancellationToken.None);

                        Assert.IsTrue(symbols.Succeeded);
                    }
                }
            }
        }
        public static async Task SetValueAsync(AmsNetId target, string subKey, string valueName, RegistryValueType type, IEnumerable <byte> data)
        {
            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));

                var writeBuffer = new List <byte>();

                writeBuffer.AddRange(System.Text.Encoding.UTF8.GetBytes(subKey));
                writeBuffer.Add(new byte()); // End delimiter
                writeBuffer.AddRange(System.Text.Encoding.UTF8.GetBytes(valueName));
                writeBuffer.Add(new byte());
                writeBuffer.AddRange(data);

                var result = await client.WriteAsync(200, 0, new ReadOnlyMemory <byte>(writeBuffer.ToArray()), CancellationToken.None);

                result.ThrowOnError();
            }
        }
Esempio n. 17
0
        public async Task Should_read_32Bytes_from_Server()
        {
            // arrange
            var ig     = 1u;
            var io     = 123u;
            var buffer = new byte[256];

            _Mock.RegisterBehavior(new ReadIndicationBehavior(ig, io, Enumerable.Range(1, buffer.Length).Select(i => (byte)i).ToArray()));
            using (var client = new AdsClient())
            {
                client.Connect(_Mock.ServerAddress.Port);

                // act
                var result = await client.ReadAsync(ig, io, buffer, CancellationToken.None);

                // assert
                Assert.IsTrue(result.Succeeded);
                Assert.AreEqual(result.ReadBytes, buffer.Length);
            }
        }
Esempio n. 18
0
        public static void StartProcess(AmsNetId target, string path, string dir, string args)
        {
            byte[] Data = new byte[777];

            BitConverter.GetBytes(path.Length).CopyTo(Data, 0);
            BitConverter.GetBytes(dir.Length).CopyTo(Data, 4);
            BitConverter.GetBytes(args.Length).CopyTo(Data, 8);

            System.Text.Encoding.ASCII.GetBytes(path).CopyTo(Data, 12);
            System.Text.Encoding.ASCII.GetBytes(dir).CopyTo(Data, 12 + path.Length + 1);
            System.Text.Encoding.ASCII.GetBytes(args).CopyTo(Data, 12 + path.Length + 1 + dir.Length + 1);

            ReadOnlyMemory <byte> buffer = new ReadOnlyMemory <byte>(Data);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                client.Write(500, 0, buffer);
                client.Dispose();
            }
        }
        static async Task Main(string[] args)
        {
            using (var serviceProvider = new ServiceCollection()
                                         .AddLogging(cfg => cfg.AddConsole())
                                         .Configure <LoggerFilterOptions>(cfg => cfg.MinLevel = LogLevel.Information)
                                         .BuildServiceProvider())
            {
                var logger = serviceProvider.GetService <ILogger <Program> >();

                // setup mocking server
                ushort port     = 12345;
                string portName = "MyTestAdsServer";
                using (var mockServer = new Mock(port, portName, logger))
                {
                    var serverBuffer = new byte[65535];
                    mockServer.RegisterBehavior(new ReadIndicationBehavior(IndexGroup: 1, IndexOffset: 123, Enumerable.Range(1, 32).Select(i => (byte)i).ToArray()))
                    .RegisterBehavior(new ReadIndicationBehavior(1, 1, Encoding.UTF8.GetBytes("acting as a ADS server")))
                    .RegisterBehavior(new ReadIndicationBehavior(0, 0, null, AdsErrorCode.DeviceAccessDenied))
                    .RegisterBehavior(new WriteIndicationBehavior(0, 0, 22));

                    Console.WriteLine("Server up and running");

                    // now the actual Ads Read/WriteRequests...

                    // create TwinCAT Ads client
                    using (var client = new AdsClient(logger))
                    {
                        // connect to our mocking server
                        client.Connect(mockServer.ServerAddress.Port);
                        if (client.IsConnected)
                        {
                            // . . .
                            var readBuffer  = new byte[65535];
                            var readMemory  = new Memory <byte>(readBuffer);
                            var writeBuffer = new byte[65535];
                            var writeMemory = new Memory <byte>(writeBuffer);

                            // 1st behavior
                            var resRd = await client.ReadAsync(1, 123, readMemory[..32], CancellationToken.None);
Esempio n. 20
0
        private void RegisterSubscriptions()
        {
            try
            {
                // create client
                _adsClient = new AdsClient();

                // connection
                _adsClient.Connect(new AmsAddress(_appOptions.AMSNetId, _appOptions.Port));

                // get the symbol loader
                _symbolLoader = SymbolLoaderFactory.Create(_adsClient, SymbolLoaderSettings.Default);

                if (_symbolLoader == null)
                {
                    return;
                }

                // symbol from appsetting.json
                if (_appOptions.ValueSymbols.Count > 0)
                {
                    for (int i = 0; i < _appOptions.ValueSymbols.Count; i++)
                    {
                        var currentValueSymbol = _appOptions.ValueSymbols[i];

                        // GetIValueSymbol
                        var res = GetIValueSymbol(_symbolLoader, currentValueSymbol);
                        if (res != null)
                        {
                            SubscribeIValueSymbol(res);
                        }
                    }
                }
            }
            catch (ObjectDisposedException ex_objectDisposed)
            {
                //throw;
            }
        }
Esempio n. 21
0
        public static async Task StartProcessAsync(AmsNetId target, string path, string directory, string args, CancellationToken cancel)
        {
            byte[] Data = new byte[777];

            BitConverter.GetBytes(path.Length).CopyTo(Data, 0);
            BitConverter.GetBytes(directory.Length).CopyTo(Data, 4);
            BitConverter.GetBytes(args.Length).CopyTo(Data, 8);

            System.Text.Encoding.ASCII.GetBytes(path).CopyTo(Data, 12);
            System.Text.Encoding.ASCII.GetBytes(directory).CopyTo(Data, 12 + path.Length + 1);
            System.Text.Encoding.ASCII.GetBytes(args).CopyTo(Data, 12 + path.Length + 1 + directory.Length + 1);

            ReadOnlyMemory <byte> buffer = new ReadOnlyMemory <byte>(Data);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                var res = await client.WriteAsync(500, 0, buffer, cancel);

                res.ThrowOnError();
            }
        }
        public static void Do_TwincatNotification(bool burn)
        {
            var cts = new CancellationTokenSource();

            AdsClient client = new AdsClient();

            client.Connect(AmsPort.R0_RTS + 1);

            client.AdsNotification += (s, e) => DoTick();
            var notiSets = new NotificationSettings(AdsTransMode.OnChange, 1, 0);
            var h_tick   = client.AddDeviceNotification("MAIN.tick", 1, notiSets, null);

            if (burn)
            {
                CpuBurner.Fire(cts.Token);
            }

            Wait_PressEnterToStop();

            cts.Cancel();
            client.DeleteDeviceNotification(h_tick);
            client.Disconnect();
        }
        public static async Task <string> QueryValueAsync(AmsNetId target, string subKey, string valueName)
        {
            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));

                var readBuffer = new Memory <byte>(new byte[255]);

                var data = new List <byte>();

                data.AddRange(System.Text.Encoding.UTF8.GetBytes(subKey));
                data.Add(new byte()); // End delimiter
                data.AddRange(System.Text.Encoding.UTF8.GetBytes(valueName));
                data.Add(new byte());

                var writeBuffer = new ReadOnlyMemory <byte>(data.ToArray());

                var result = await client.ReadWriteAsync(200, 0, readBuffer, writeBuffer, CancellationToken.None);

                result.ThrowOnError();
                return(System.Text.Encoding.UTF8.GetString(readBuffer.ToArray(), 0, result.ReadBytes));
            }
        }
Esempio n. 24
0
        public static async Task <DeviceInfo> GetDeviceInfoAsync(AmsNetId target, CancellationToken cancel)
        {
            var buffer = new Memory <byte>(new byte[2048]);

            DeviceInfo device = new DeviceInfo();

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                var result = await client.ReadAsync(700, 1, buffer, cancel);

                result.ThrowOnError();

                String data = System.Text.Encoding.ASCII.GetString(buffer.ToArray());

                device.TargetType       = GetValueFromTag("<TargetType>", data);
                device.HardwareModel    = GetValueFromTag("<Model>", data);
                device.HardwareSerialNo = GetValueFromTag("<SerialNo>", data);
                device.HardwareVersion  = GetValueFromTag("<CPUArchitecture>", data);
                device.HardwareDate     = GetValueFromTag("<Date>", data);
                device.HardwareCPU      = GetValueFromTag("<CPUVersion>", data);

                device.ImageDevice    = GetValueFromTag("<ImageDevice>", data);
                device.ImageVersion   = GetValueFromTag("<ImageVersion>", data);
                device.ImageLevel     = GetValueFromTag("<ImageLevel>", data);
                device.ImageOsName    = GetValueFromTag("<OsName>", data);
                device.ImageOsVersion = GetValueFromTag("<OsVersion>", data);

                var major = GetValueFromTag("<Version>", data);
                var minor = GetValueFromTag("<Revision>", data);
                var build = GetValueFromTag("<Build>", data);
                device.TwinCATVersion = Version.Parse(major + "." + minor + "." + build);
            }

            return(device);
        }
Esempio n. 25
0
        public void SpsKommunikationTask()
        {
            while (_taskRunning)
            {
                var pingSender = new Ping();
                var reply      = pingSender.Send(_spsCx9020.IpAdresse, SpsTimeout);

                if (reply?.Status == IPStatus.Success)
                {
                    _spsStatus = "CX9020 sichtbar (Ping: " + reply.RoundtripTime + "ms)";
                    _adsClient.Connect(_spsCx9020.AmsNetId, _spsCx9020.Port);

                    _callbackRangieren(_datenstruktur, true);

                    var handleVersionsInfo = _adsClient.CreateVariableHandle("VersionsInfo.Ver");
                    var handleBefehle      = _adsClient.CreateVariableHandle("VersionsInfo.Befehle");
                    var handleAnalogInput  = _adsClient.CreateVariableHandle("AnalogInput.AI");
                    var handleAnalogOutput = _adsClient.CreateVariableHandle("AnalogOutput.AA");
                    var handleDigInput     = _adsClient.CreateVariableHandle("DigInput.DI");
                    var handleDigOutput    = _adsClient.CreateVariableHandle("DigOutput.DA");

                    while (true)
                    {
                        byte betriebsartPlc = 0;

                        _callbackRangieren(_datenstruktur, true);

                        if (_datenstruktur.BetriebsartProjekt != BetriebsartProjekt.LaborPlatte)
                        {
                            betriebsartPlc = 1;
                        }

                        Versionsinfo = (byte[])_adsClient.ReadAny(handleVersionsInfo, typeof(byte[]), new[] { 255 });

                        if (_anzAa > 0)
                        {
                            _datenstruktur.AnalogOutput = (byte[])_adsClient.ReadAny(handleAnalogOutput, typeof(byte[]), new[] { 1024 });
                        }
                        if (_anzDa > 0)
                        {
                            _datenstruktur.DigOutput = (byte[])_adsClient.ReadAny(handleDigOutput, typeof(byte[]), new[] { 1024 });
                        }

                        _adsClient.WriteAny(handleBefehle, betriebsartPlc);
                        if (_anzAi > 0)
                        {
                            _adsClient.WriteAny(handleAnalogInput, _datenstruktur.AnalogInput);
                        }
                        if (_anzDi > 0)
                        {
                            _adsClient.WriteAny(handleDigInput, _datenstruktur.DigInput);
                        }

                        for (var i = 0; i < 100; i++)
                        {
                            _datenstruktur.VersionInputSps[1 + i] = Versionsinfo[i];
                        }

                        Thread.Sleep(10);
                    }
                }

                _spsStatus = "Keine Verbindung zur CX9020!";

                Thread.Sleep(50);
            }
        }
Esempio n. 26
0
 private void Connect()
 {
     _client = new AdsClient();
     _client.Connect(_address);
 }