Übertragen von Strukturen an die SPS

Dieses Beispiel zeigt die Übertragung einer Struktur an die SPS per ADS. Die Struktur besteht aus Elementen von verschiedenen Datentypen:


import de.beckhoff.jni.JNIByteBuffer;
import de.beckhoff.jni.tcads.AmsAddr;
import de.beckhoff.jni.tcads.AdsCallDllFunction;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main
{
public static void main(String[] args)
{
    long err;
    AmsAddr addr = new AmsAddr();

    TransferObject transfer = new TransferObject(); // See additional class
    JNIByteBuffer dataBuff = new JNIByteBuffer(19);

    // Open communication    
    AdsCallDllFunction.adsPortOpen();
    err = AdsCallDllFunction.getLocalAddress(addr);
    addr.setPort(851);

    if (err != 0) {
     System.out.println("Error: Open communication: 0x"
         + Long.toHexString(err));
    } else {
     System.out.println("Success: Open communication!");
    }

    // Use JNIByteBuffer as a backing array for ByteBuffer
    ByteBuffer bb = ByteBuffer.wrap(dataBuff.getByteArray());

    // Write elements to buffer. Litte Endian!
    bb.order(ByteOrder.LITTLE_ENDIAN);

    bb.putShort(transfer.getShortVal());
    bb.putInt(transfer.getIntVal());
    bb.put(transfer.getByteVal());
    bb.putDouble(transfer.getDoubleVal());
    bb.putFloat(transfer.getFloatVal());

    // Write struct to PLC
    err = AdsCallDllFunction.adsSyncWriteReq(addr,
        0x4020, // Index Group
        0x0,    // Index Offset
        19,
        dataBuff);
    if(err!=0) {
     System.out.println("Error: Write request: 0x"
         + Long.toHexString(err));
    } else {
     System.out.println("Success: Write struct!");
    }

    // Close communication
    err = AdsCallDllFunction.adsPortClose();
    if(err!=0) {
     System.out.println("Error: Close Communication: 0x"
         + Long.toHexString(err));
    }
}
}

Das zu übertragende Objekt:


public class TransferObject
{
private short shortVal;
private int intVal;
private byte byteVal;
private double doubleVal;
private float floatVal;

public TransferObject()
{
    this.shortVal = Short.MAX_VALUE;
    this.intVal = Integer.MIN_VALUE;
    this.byteVal = 3;
    this.doubleVal = 4.1234;
    this.floatVal = 5.4321f;
}

public short getShortVal() {
    return shortVal;
}
public int getIntVal() {
    return intVal;
}
public byte getByteVal() {
    return byteVal;
}
public double getDoubleVal() {
    return doubleVal;
}
public float getFloatVal() {
    return floatVal;
}
}

Beispielprogramm 'Übertragen von Strukturen an die SPS' entpacken.

Um das *.jar Sample ausführen zu können, muss in der Konsole im korrekten Verzeichnis der Befehl 'java -classpath "Sample04.jar;[Pfad zu TcJavaToAds.jar] Main' ausgeführt werden (Beispielpfad: "C:TwinCAT\Ads Api\AdsToJava\*"). Dazu muss Java in den Umgebungsvariablen eingetragen sein.

Voraussetzungen

Entwicklungsumgebung

Zielplattform

Einzubindende Java-Packages

TwinCAT v3.0 Build 3102, Java

PC or CX (x86)