AdsSession Class

AdsSession class

Inheritance Hierarchy

SystemObject
  TwinCATSession
    TwinCAT.AdsAdsSessionBase
      TwinCAT.AdsAdsSession

Namespace: TwinCAT.Ads
Assembly: TwinCAT.Ads (in TwinCAT.Ads.dll) Version: 7.0.0+e56d35ccc4675faac24789a4aab60071fc61d470

Syntax

C#

public class AdsSession : AdsSessionBase

The AdsSession type exposes the following members.

Constructors

 

Name

Description

AdsSession Class 1:

AdsSession(AmsAddress)

Initializes a new instance of the AdsSession class.

AdsSession Class 2:

AdsSession(Int32)

Initializes a new instance of the AdsSession class addressed to the Local System.

AdsSession Class 3:

AdsSession(AmsAddress, ILoggerFactory)

Initializes a new instance of the AdsSession class.

AdsSession Class 4:

AdsSession(AmsAddress, SessionSettings)

Initializes a new instance of the AdsSession class.

AdsSession Class 5:

AdsSession(AmsNetId, Int32)

Initializes a new instance of the AdsSession class.

AdsSession Class 6:

AdsSession(String, Int32)

Initializes a new instance of the AdsSession class.

AdsSession Class 7:

AdsSession(AmsAddress, SessionSettings, ILoggerFactory)

Initializes a new instance of the AdsSession class.

AdsSession Class 8:

AdsSession(AmsAddress, SessionSettings, Object)

Initializes a new instance of the AdsSession class.

AdsSession Class 9:

AdsSession(AmsNetId, Int32, ILoggerFactory)

Initializes a new instance of the AdsSession class.

AdsSession Class 10:

AdsSession(AmsNetId, Int32, SessionSettings)

Initializes a new instance of the AdsSession class.

AdsSession Class 11:

AdsSession(String, Int32, ILoggerFactory)

Initializes a new instance of the AdsSession class.

AdsSession Class 12:

AdsSession(String, Int32, SessionSettings)

Initializes a new instance of the AdsSession class.

AdsSession Class 13:

AdsSession(AmsNetId, Int32, SessionSettings, ILoggerFactory)

Initializes a new instance of the AdsSession class.

AdsSession Class 14:

AdsSession(String, Int32, SessionSettings, ILoggerFactory)

Initializes a new instance of the AdsSession class.

AdsSession Class 15:

AdsSession(AmsAddress, SessionSettings, IConfiguration, ILoggerFactory, Object)

Initializes a new instance of the AdsSession class.

Properties

 

Name

Description

AdsSession Class 16:

Address

Gets the target address of the AdsSessionBase
(Inherited from AdsSessionBase)

AdsSession Class 17:

AddressSpecifier

Gets the communication endpoint address string representation.
(Inherited from Session)

AdsSession Class 18:

Configuration

Gets the logger interface or null.
(Inherited from AdsSessionBase)

AdsSession Class 19:

Connection

Gets the connection.
(Inherited from AdsSessionBase)

AdsSession Class 20:

AdsSession Class 21:

ConnectionState

Gets the current Connection state of the Session
(Inherited from Session)

AdsSession Class 22:

Disposed

Gets a value indicating whether this Session is disposed.
(Inherited from Session)

AdsSession Class 23:

EstablishedAt

Gets the UTC time when the session was established.
(Inherited from Session)

AdsSession Class 24:

Id

Gets the Session Identifier
(Inherited from Session)

AdsSession Class 25:

IsConnected

Gets a value indicating whether this instance is connected.
(Inherited from Session)

Logger

Gets the actual used logger or null.
(Inherited from AdsSessionBase)

AdsSession Class 26:

LoggerFactory

Gets the logger factory.
(Inherited from AdsSessionBase)

AdsSession Class 27:

Name

Gets the name of the session
(Inherited from Session)

AdsSession Class 28:

NetId

Gets the NetId of the Session
(Inherited from AdsSessionBase)

AdsSession Class 29:

Owner

Gets the Session owner.
(Inherited from AdsSessionBase)

AdsSession Class 30:

Port

Gets the Ams Port of the Session
(Inherited from AdsSessionBase)

AdsSession Class 31:

Settings

Gets the settings.
(Inherited from AdsSessionBase)

AdsSession Class 32:

Statistics

Gets the Communication / Session statistics.
(Inherited from AdsSessionBase)

AdsSession Class 33:

SymbolServer

Gets the symbol server.
(Inherited from Session)

Methods

 

Name

Description

AdsSession Class 34:

Close

Closes this ISession
(Inherited from Session)

AdsSession Class 35:

Connect

Connects the session.
(Inherited from Session)

AdsSession Class 36:

ConnectAndWaitAsync

Connects the session.
(Inherited from Session)

AdsSession Class 37:

ConnectAsync

Connects the session.
(Inherited from Session)

AdsSession Class 38:

Disconnect

Disconnects the session from the target.
(Inherited from Session)

AdsSession Class 39:

Dispose

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
(Inherited from Session)

AdsSession Class 40:

Dispose(Boolean)

Releases unmanaged and - optionally - managed resources.
(Inherited from AdsSessionBase)

AdsSession Class 41:

EnsureConnection

Ensures, that the ISession is connected and returns the IConnection object.
(Inherited from AdsSessionBase)

AdsSession Class 42:

Equals

Determines whether the specified object is equal to the current object.
(Inherited from Object)

AdsSession Class 43:

Finalize

Finalizes an instance of the AdsSessionBase class.
(Inherited from AdsSessionBase)

AdsSession Class 44:

GetHashCode

Serves as the default hash function.
(Inherited from Object)

AdsSession Class 45:

GetSessionName

Gets the name/string identifier of the session.
(Inherited from AdsSessionBase)

AdsSession Class 46:

GetType

Gets the Type of the current instance.
(Inherited from Object)

AdsSession Class 47:

MemberwiseClone

Creates a shallow copy of the current Object.
(Inherited from Object)

AdsSession Class 48:

OnConnect

Handler function connecting the Session.
(Inherited from AdsSessionBase)

AdsSession Class 49:

OnConnectAndWaitAsync

Handler function connecting the Session.
(Inherited from AdsSessionBase)

AdsSession Class 50:

OnConnectAsync

Handler function connecting the Session.
(Inherited from AdsSessionBase)

AdsSession Class 51:

OnConnectionStateChanged

Handles the [E:ConnectionStateChanged] event.
(Inherited from Session)

AdsSession Class 52:

OnCreateSymbolServer

Handler function creating the symbol server object.
(Inherited from AdsSessionBase)

AdsSession Class 53:

OnDisconnect

Handler function disconnecting the session.
(Inherited from AdsSessionBase)

AdsSession Class 54:

OnGetAddress

Handler function getting the address of the session.
(Inherited from AdsSessionBase)

AdsSession Class 55:

ToString

Returns a String that represents this instance.
(Inherited from Session)

Events

 

Name

Description

AdsSession Class 56:

AdsSession Class 57:

ConnectionStateChanged

Occurs when connection status of the IConnectionStateProvider has been changed.
(Inherited from Session)

Fields

 

Name

Description

connection

The (established) connection
(Inherited from Session)

Remarks

On top of the well known AdsClient class that is used traditionally for ADS communication, the AdsSession class provides the following additionally abilities out of the box: These are used to provide more stable connections to ADS Servers than the AdsClient can provide. The main issues are Resurrection / Self-Healing after communication timeouts, faster and less error prone reaction to communication errors (not necessarily waiting for communication timeouts) und enhanced communication diagnosis. These enhanced features are provided by the following additions to the TwinCAT.Ads API:

The AdsConnection is established by calling the Connect method. The returned AdsConnection can be used as long the AdsSessionBase exists.

Example

The following sample shows a simple use of the AdsSessionBase object. The AdsSession object (and the dynamic SymbolLoader features) are only available from .NET 4 and upwards.

Use Session (async)

using System;
using System.Diagnostics;
using System.Threading;

using TwinCAT;
using TwinCAT.Ads;
using TwinCAT.Ads.TypeSystem;
using TwinCAT.TypeSystem;
using TwinCAT.TypeSystem.Generic;

namespace Sample
{
    class SessionAsync
    {
    /// <summary>
    /// Defines the entry point of the application.
    /// </summary>
    /// <param name="args">The arguments.</param>
    static async void Main(string[] args)
    {
        AmsAddress address = ArgParser.Parse(args);

        CancellationTokenSource cancelSource = new CancellationTokenSource();
        CancellationToken cancel = cancelSource.Token;
        SessionSettings settings = SessionSettings.Default; // Default settings are Async access with Timeout 5 sec

        // Async access is necessary for Console applications!

        using (AdsSession session = new AdsSession(address, settings))
        {
        AdsConnection connection = (AdsConnection) session.Connect(); // Establish the connection
        connection.ConnectionStateChanged += Connection_ConnectionStateChanged;

        ConnectionState connectionState = connection.ConnectionState; // The actual connection state

        // Read the identification and version number of the device
        var result = await connection.ReadDeviceInfoAsync(cancel);

        result.ThrowOnError(); // Throws exception if failed.

        DeviceInfo deviceInfo = result.DeviceInfo; 
        Version version = deviceInfo.Version.ConvertToStandard();
        Console.WriteLine(string.Format("DeviceName: {0}", deviceInfo.Name));
        Console.WriteLine(string.Format("DeviceVersion: {0}", version.ToString(3)));

        /// Read the state of the device
        var resultReadState = await connection.ReadStateAsync(cancel);
        resultReadState.ThrowOnError();

        StateInfo stateInfo = resultReadState.State;
        AdsState adsState = stateInfo.AdsState;
        short deviceState = stateInfo.DeviceState;

        Console.WriteLine(string.Format("DeviceState: {0}", deviceState));
        Console.WriteLine(string.Format("AdsState   : {0}", adsState));

        // Other ADS methods (as formerly used on AdsClient) can be used also on connection object:

        // connection.ReadAsync(...)
        // connection.WriteAsync(...)
        // connection.AddDeviceNotificationEx += ...

        // Session communication Diagnostic:

        int resurrectionTries = connection.TotalResurrectingTries;
        int succeededResurrections = connection.TotalResurrections;

        AdsCommunicationStatistics statistics = session.Statistics; // The communication statistics

        // Symbol access:
        // The Session holds and Caches the Symbolic data information
        var resultDataTypes = await session.SymbolServer.GetDataTypesAsync(cancel);
        var resultSymbols = await session.SymbolServer.GetSymbolsAsync(cancel);

        if (resultDataTypes.Succeeded && resultSymbols.Succeeded) // Check for succeed
        {
            IDataTypeCollection<IDataType> types = resultDataTypes.DataTypes;
            ISymbolCollection<ISymbol> symbols = resultSymbols.Symbols;

            Symbol projectNameSymbol = (Symbol)symbols["TwinCAT_SystemInfoVarList._AppInfo.ProjectName"];
            var resultReadProjectName = await projectNameSymbol.ReadValueAsync(cancel);
            string projectName = (string)resultReadProjectName.Value;

            // Or use dynamic objects
            dynamic appInfo = symbols["TwinCAT_SystemInfoVarList._AppInfo"];
            string projectName2 = appInfo.ProjectName; // Property dynamically created (synchronous call)!
        }
        Console.WriteLine("");
        Console.WriteLine("Press [Enter] for leave:");
        Console.ReadLine();
        }
    }

    private static void Connection_ConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e)
    {
        Console.WriteLine("Connection State changed (NewState: {0}, OldState: {1}",e.NewState,e.OldState);
    }

Use Session (sync)

using System;
using System.Diagnostics;
using System.Threading;

using TwinCAT;
using TwinCAT.Ads;
using TwinCAT.Ads.TypeSystem;
using TwinCAT.TypeSystem;
using TwinCAT.TypeSystem.Generic;

namespace Sample
{
    class Session
    {
    /// <summary>
    /// Defines the entry point of the application.
    /// </summary>
    /// <param name="args">The arguments.</param>
    static void Main(string[] args)
    {
        AmsAddress address = ArgParser.Parse(args);
        SessionSettings settings = SessionSettings.Default; // Default settings are Async access with Timeout 5 sec

        // Async access is necessary for Console applications!

        using (AdsSession session = new AdsSession(address, settings))
        {
        AdsConnection connection = (AdsConnection) session.Connect(); // Establish the connection
        connection.ConnectionStateChanged += Connection_ConnectionStateChanged;

        ConnectionState connectionState = connection.ConnectionState; // The actual connection state

        // Read the identification and version number of the device
        DeviceInfo deviceInfo = connection.ReadDeviceInfo();
        Version version = deviceInfo.Version.ConvertToStandard();
        Console.WriteLine(string.Format("DeviceName: {0}", deviceInfo.Name));
        Console.WriteLine(string.Format("DeviceVersion: {0}", version.ToString(3)));

        /// Read the state of the device
        StateInfo stateInfo = connection.ReadState();
        AdsState adsState = stateInfo.AdsState;

        short deviceState = stateInfo.DeviceState;
        Console.WriteLine(string.Format("DeviceState: {0}", deviceState));
        Console.WriteLine(string.Format("AdsState   : {0}", adsState));

        // Other ADS methods (as formerly used on AdsClient) can be used also on connection object:

        // connection.Read(...)
        // connection.Write(...)
        // connection.AddDeviceNotificationEx += ...


        // Session communication Diagnostic:

        int resurrectionTries = connection.TotalResurrectingTries;
        int succeededResurrections = connection.TotalResurrections;

        AdsCommunicationStatistics statistics = session.Statistics; // The communication statistics

        // Symbol access:
        // The Session holds and Caches the Symbolic data information
        IDataTypeCollection<IDataType> types = session.SymbolServer.DataTypes;
        ISymbolCollection<ISymbol> symbols = session.SymbolServer.Symbols;

        Symbol projectNameSymbol = (Symbol)symbols["TwinCAT_SystemInfoVarList._AppInfo.ProjectName"];
        string projectName = (string) projectNameSymbol.ReadValue();

        // Or use dynamic objects
        dynamic appInfo = symbols["TwinCAT_SystemInfoVarList._AppInfo"];
        string projectName2 = appInfo.ProjectName;

        Console.WriteLine("");
        Console.WriteLine("Press [Enter] for leave:");
        Console.ReadLine();
        }
    }

    private static void Connection_ConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e)
    {
        Console.WriteLine("Connection State changed (NewState: {0}, OldState: {1}",e.NewState,e.OldState);
    }

Add a custom logger

static async void Main(string[] args)
{
    CancellationTokenSource cancelSource = new CancellationTokenSource();
    CancellationToken cancel = cancelSource.Token;

    var address = new AmsAddress(AmsNetId.Local, AmsPort.SystemService);
    var sessionSettings = SessionSettings.Default;

    //https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line

    // Create a configuration for the custom logger
    var loggerConfig = new AdsLoggerConfiguration
    {
    LogLevel = LogLevel.Information,
    EventId = 0
    };

    // Create an ILoggerFactory and add the custom logger provider
    var loggerFactory = LoggerFactory.Create(builder =>
    {
    //builder.SetMinimumLevel(LogLevel.Information)
    builder.AddProvider(new AdsLoggerProvider(() => loggerConfig))
       .AddConsole(); // Adds the console
    });

    // Use AdsClient with custom logger
    using (AdsClient client = new AdsClient(loggerFactory))
    {
    // Connect
    client.Connect(address);
    }

    // Use AdsSession with custom logger
    using (AdsSession session = new AdsSession(address, sessionSettings, loggerFactory))
    {
    // Connect
    session.Connect();
    }
}

Reference

TwinCAT.Ads Namespace Session IAdsSessionIInterceptionFactory

Beckhoff Automation GmbH & Co. KG 2001-2026