Read/Write PlcOpen types (DATE, TIME ...)

The following PLCOpen types have specific representations within the TwinCAT.Ads Communication Library: DT

The following section shows the different scenarios as code snippets.

HowTo Read/Write PlcOpen values

Reading writing by streams:

Read/Write PlcOpen types (streamed)

using (TcAdsClient client = new TcAdsClient())
{
    client.Connect(851); // Connect to local plc

    int handle1 = 0;
    int handle2 = 0;

    try
    {
    handle1 = client.CreateVariableHandle("MAIN.time"); // TIME
    handle2 = client.CreateVariableHandle("MAIN.date"); // DATE

    AdsStream readStream = new AdsStream(LTIME.MarshalSize); // Largest (8 Bytes)
    AdsBinaryReader reader = new AdsBinaryReader(readStream);

    client.Read(handle1, readStream, 0, TIME.MarshalSize);
    TimeSpan time = reader.ReadPlcTIME();

    client.Read(handle2, readStream, 0, DATE.MarshalSize);
    DateTime dateTime = reader.ReadPlcDATE();
    }
    finally
    {
    client.DeleteVariableHandle(handle1);
    client.DeleteVariableHandle(handle2);
    }
}

Reading writing by ANY type concept:

Read/Write PlcOpen types (ANY)

using (TcAdsClient client = new TcAdsClient())
{
    client.Connect(851); // Connect to local plc

    int handle1 = 0;
    int handle2 = 0;
    int handle3 = 0;

    try
    {
    handle1 = client.CreateVariableHandle("MAIN.time"); // TIME
    handle2 = client.CreateVariableHandle("MAIN.date"); // DATE
    handle3 = client.CreateVariableHandle("MAIN.ltime"); // LTIME

    TIME time = (TIME)client.ReadAny(handle1, typeof(TIME)); // TIME
    TimeSpan timeSpan = time.Time;

    DATE date = (DATE)client.ReadAny(handle2, typeof(DATE)); // DATE
    DateTime dateTime = date.Date;

    LTIME ltime = (LTIME)client.ReadAny(handle3, typeof(LTIME)); // LTIME
    TimeSpan lTimeSpan = ltime.Time;
    }
    finally
    {
    client.DeleteVariableHandle(handle1);
    client.DeleteVariableHandle(handle2);
    client.DeleteVariableHandle(handle3);
    }
}