Search in sources :

Example 1 with PlcReadRequest

use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.

the class Plc4x2AdsProtocol method decodeReadResponse.

@SuppressWarnings("unchecked")
private InternalPlcResponse decodeReadResponse(AdsReadResponse responseMessage, PlcRequestContainer<InternalPlcRequest, InternalPlcResponse> requestContainer) {
    InternalPlcReadRequest plcReadRequest = (InternalPlcReadRequest) requestContainer.getRequest();
    // TODO: only single requests supported for now
    AdsField field = (AdsField) plcReadRequest.getFields().get(0);
    PlcResponseCode responseCode = decodeResponseCode(responseMessage.getResult());
    byte[] bytes = responseMessage.getData().getBytes();
    PlcValue value = decodeData(field.getAdsDataType(), bytes);
    // TODO: does every item has the same ads response or is this whole aggregation broken?
    Map<String, Pair<PlcResponseCode, PlcValue>> responseItems = plcReadRequest.getFieldNames().stream().collect(Collectors.toMap(fieldName -> fieldName, ignore -> Pair.of(responseCode, value)));
    return new DefaultPlcReadResponse(plcReadRequest, responseItems);
}
Also used : DirectAdsField(org.apache.plc4x.java.ads.model.DirectAdsField) PlcIoException(org.apache.plc4x.java.api.exceptions.PlcIoException) PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) PlcRequest(org.apache.plc4x.java.api.messages.PlcRequest) LoggerFactory(org.slf4j.LoggerFactory) PlcValue(org.apache.plc4x.java.api.value.PlcValue) ConcurrentMap(java.util.concurrent.ConcurrentMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AdsException(org.apache.plc4x.java.ads.protocol.exception.AdsException) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) LittleEndianEncoder.encodeData(org.apache.plc4x.java.ads.protocol.util.LittleEndianEncoder.encodeData) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) org.apache.plc4x.java.ads.api.commands(org.apache.plc4x.java.ads.api.commands) PlcList(org.apache.plc4x.java.api.value.PlcList) LinkedList(java.util.LinkedList) AdsDataType(org.apache.plc4x.java.ads.model.AdsDataType) Invoke(org.apache.plc4x.java.ads.api.generic.types.Invoke) PlcProtocolException(org.apache.plc4x.java.api.exceptions.PlcProtocolException) AmsPacket(org.apache.plc4x.java.ads.api.generic.AmsPacket) Logger(org.slf4j.Logger) AmsNetId(org.apache.plc4x.java.ads.api.generic.types.AmsNetId) PlcProtocolPayloadTooBigException(org.apache.plc4x.java.api.exceptions.PlcProtocolPayloadTooBigException) org.apache.plc4x.java.ads.api.commands.types(org.apache.plc4x.java.ads.api.commands.types) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) org.apache.plc4x.java.spi.messages(org.apache.plc4x.java.spi.messages) SymbolicAdsField(org.apache.plc4x.java.ads.model.SymbolicAdsField) Collectors(java.util.stream.Collectors) PlcField(org.apache.plc4x.java.api.model.PlcField) MessageToMessageCodec(io.netty.handler.codec.MessageToMessageCodec) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) AmsPort(org.apache.plc4x.java.ads.api.generic.types.AmsPort) AdsField(org.apache.plc4x.java.ads.model.AdsField) PlcValue(org.apache.plc4x.java.api.value.PlcValue) DirectAdsField(org.apache.plc4x.java.ads.model.DirectAdsField) SymbolicAdsField(org.apache.plc4x.java.ads.model.SymbolicAdsField) AdsField(org.apache.plc4x.java.ads.model.AdsField) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) Pair(org.apache.commons.lang3.tuple.Pair)

Example 2 with PlcReadRequest

use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.

the class Plc4x2AdsProtocol method decode.

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, AmsPacket amsPacket, List<Object> out) throws Exception {
    LOGGER.trace("(-->IN): {}, {}, {}", channelHandlerContext, amsPacket, out);
    if (amsPacket instanceof AdsDeviceNotificationRequest) {
        LOGGER.debug("Received notification {}", amsPacket);
        handleAdsDeviceNotificationRequest((AdsDeviceNotificationRequest) amsPacket);
        return;
    }
    PlcRequestContainer<InternalPlcRequest, InternalPlcResponse> plcRequestContainer = requests.remove(amsPacket.getAmsHeader().getInvokeId().getAsLong());
    if (plcRequestContainer == null) {
        LOGGER.info("Unmapped packet received {}", amsPacket);
        return;
    }
    PlcRequest request = plcRequestContainer.getRequest();
    final InternalPlcResponse response;
    // Handle the response to a read request.
    if (request instanceof PlcReadRequest) {
        if (amsPacket instanceof AdsReadResponse) {
            response = decodeReadResponse((AdsReadResponse) amsPacket, plcRequestContainer);
        } else {
            throw new PlcProtocolException("Wrong type correlated " + amsPacket);
        }
    } else if (request instanceof PlcWriteRequest) {
        if (amsPacket instanceof AdsWriteResponse) {
            response = decodeWriteResponse((AdsWriteResponse) amsPacket, plcRequestContainer);
        } else {
            throw new PlcProtocolException("Wrong type correlated " + amsPacket);
        }
    } else if (request instanceof PlcProprietaryRequest) {
        response = decodeProprietaryResponse(amsPacket, plcRequestContainer);
    } else {
        response = null;
    }
    LOGGER.debug("Plc4x response {}", response);
    // Confirm the response being handled.
    if (response != null) {
        plcRequestContainer.getResponseFuture().complete(response);
    }
}
Also used : PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) PlcProtocolException(org.apache.plc4x.java.api.exceptions.PlcProtocolException) PlcRequest(org.apache.plc4x.java.api.messages.PlcRequest) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest)

Example 3 with PlcReadRequest

use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.

the class ManualProfinetIoTest method main.

public static void main(String[] args) throws Exception {
    final PlcConnection connection = new PlcDriverManager().getConnection("profinet://192.168.24.31");
    final PlcReadRequest readRequest = connection.readRequestBuilder().addItem("test", "").build();
    final PlcReadResponse plcReadResponse = readRequest.execute().get();
    System.out.println(plcReadResponse);
}
Also used : PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 4 with PlcReadRequest

use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.

the class Plc4xReadClient method main.

public static void main(String[] args) throws Exception {
    try (final PlcConnection connection = new PlcDriverManager().getConnection("plc4x://localhost?remote-connection-string=simulated%3A%2F%2Flocalhost")) {
        final PlcReadRequest.Builder requestBuilder = connection.readRequestBuilder();
        requestBuilder.addItem("test-BOOL", "RANDOM/foo:BOOL");
        requestBuilder.addItem("test-BYTE", "RANDOM/foo:BYTE");
        requestBuilder.addItem("test-WORD", "RANDOM/foo:WORD");
        requestBuilder.addItem("test-DWORD", "RANDOM/foo:DWORD");
        requestBuilder.addItem("test-USINT", "RANDOM/foo:USINT");
        requestBuilder.addItem("test-UINT", "RANDOM/foo:UINT");
        requestBuilder.addItem("test-UDINT", "RANDOM/foo:UDINT");
        requestBuilder.addItem("test-ULINT", "RANDOM/foo:ULINT");
        requestBuilder.addItem("test-SINT", "RANDOM/foo:SINT");
        requestBuilder.addItem("test-INT", "RANDOM/foo:INT");
        requestBuilder.addItem("test-DINT", "RANDOM/foo:DINT");
        requestBuilder.addItem("test-LINT", "RANDOM/foo:LINT");
        requestBuilder.addItem("test-REAL", "RANDOM/foo:REAL");
        requestBuilder.addItem("test-LREAL", "RANDOM/foo:LREAL");
        requestBuilder.addItem("test-CHAR", "RANDOM/foo:CHAR");
        requestBuilder.addItem("test-WCHAR", "RANDOM/foo:WCHAR");
        final PlcReadRequest readRequest = requestBuilder.build();
        final PlcReadResponse readResponse = readRequest.execute().get();
        System.out.println(readResponse);
    }
}
Also used : PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 5 with PlcReadRequest

use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.

the class S7PlcToGoogleIoTCoreSample method main.

/**
 * Example code do demonstrate sending events from an S7 device to Microsoft Azure IoT Hub
 *
 * @param args Expected: [plc4x connection string, plc4x address, IoT-Hub connection string].
 */
public static void main(String[] args) throws Exception {
    // [START iot_mqtt_configuremqtt]
    CliOptions options = CliOptions.fromArgs(args);
    if (options == null) {
        CliOptions.printHelp();
        // Could not parse.
        System.exit(1);
    }
    // Build the connection string for Google's Cloud IoT Core MQTT server. Only SSL
    // connections are accepted. For server authentication, the JVM's root certificates
    // are used.
    final String mqttServerAddress = String.format("ssl://%s:%s", options.getMqttBridgeHostname(), options.getMqttBridgePort());
    // Create our MQTT client. The mqttClientId is a unique string that identifies this device. For
    // Google Cloud IoT Core, it must be in the format below.
    final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s", options.getProjectId(), options.getCloudRegion(), options.getRegistryId(), options.getDeviceId());
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    // Note that the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we
    // explictly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    // With Google Cloud IoT Core, the username field is ignored, however it must be set for the
    // Paho client library to send the password field. The password field is used to transmit a JWT
    // to authorize the device.
    connectOptions.setUserName("unused");
    DateTime iat = new DateTime();
    setConnectPassword(options, connectOptions);
    // [END iot_mqtt_configuremqtt]
    // [START iot_mqtt_publish]
    // Create a client, and connect to the Google MQTT bridge.
    MqttClient client = new MqttClient(mqttServerAddress, mqttClientId, new MemoryPersistence());
    // Both connect and publish operations may fail. If they do, allow retries but with an
    // exponential backoff time period.
    long initialConnectIntervalMillis = 500L;
    long maxConnectIntervalMillis = 6000L;
    long maxConnectRetryTimeElapsedMillis = 900000L;
    float intervalMultiplier = 1.5f;
    long retryIntervalMs = initialConnectIntervalMillis;
    long totalRetryTimeMs = 0;
    while (!client.isConnected() && totalRetryTimeMs < maxConnectRetryTimeElapsedMillis) {
        try {
            client.connect(connectOptions);
        } catch (MqttException e) {
            int reason = e.getReasonCode();
            // If the connection is lost or if the server cannot be connected, allow retries, but with
            // exponential backoff.
            System.out.println("An error occurred: " + e.getMessage());
            if (reason == MqttException.REASON_CODE_CONNECTION_LOST || reason == MqttException.REASON_CODE_SERVER_CONNECT_ERROR) {
                System.out.println("Retrying in " + retryIntervalMs / 1000.0 + " seconds.");
                Thread.sleep(retryIntervalMs);
                totalRetryTimeMs += retryIntervalMs;
                retryIntervalMs *= intervalMultiplier;
                if (retryIntervalMs > maxConnectIntervalMillis) {
                    retryIntervalMs = maxConnectIntervalMillis;
                }
            } else {
                throw e;
            }
        }
    }
    attachCallback(client, options.getDeviceId());
    // Publish to the events or state topic based on the flag.
    String subTopic = "event".equals(options.getMessageType()) ? "events" : options.getMessageType();
    // The MQTT topic that this device will publish telemetry data to. The MQTT topic name is
    // required to be in the format below. Note that this is not the same as the device registry's
    // Cloud Pub/Sub topic.
    String mqttTopic = String.format("/devices/%s/%s", options.getDeviceId(), subTopic);
    // Connect to Plc
    logger.info("Connecting to Plc");
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection("s7://10.10.64.20/1/1")) {
        logger.info("Connected");
        PlcReadRequest readRequest = plcConnection.readRequestBuilder().addItem("outputs", "OUTPUTS/0").build();
        while (!Thread.currentThread().isInterrupted()) {
            PlcReadResponse plcReadResponse = readRequest.execute().get();
            // Refresh the connection credentials before the JWT expires.
            // [START iot_mqtt_jwt_refresh]
            long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
            if (secsSinceRefresh > (options.getTokenExpMins() * 60)) {
                System.out.format("\tRefreshing token after: %d seconds%n", secsSinceRefresh);
                iat = new DateTime();
                setConnectPassword(options, connectOptions);
                client.disconnect();
                client.connect();
                attachCallback(client, options.getDeviceId());
            }
            // Send data to cloud
            for (String fieldName : plcReadResponse.getFieldNames()) {
                Long l = plcReadResponse.getLong(fieldName);
                byte[] array = ByteBuffer.allocate(8).putLong(l).array();
                String result = Long.toBinaryString(l);
                System.out.println("Outputs: " + result);
                // Publish "array" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
                // also supports qos=0 for at most once delivery.
                MqttMessage message = new MqttMessage(array);
                message.setQos(1);
                client.publish(mqttTopic, message);
                if ("event".equals(options.getMessageType())) {
                    // Send telemetry events every second
                    Thread.sleep(1000);
                } else {
                    // Note: Update Device state less frequently than with telemetry events
                    Thread.sleep(5000);
                }
            }
        }
    }
    System.out.println("Sent all messages. Goodbye!");
// [END iot_mqtt_publish]
}
Also used : MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) DateTime(org.joda.time.DateTime) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager)

Aggregations

PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)32 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)17 PlcConnection (org.apache.plc4x.java.api.PlcConnection)16 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)12 PlcProtocolException (org.apache.plc4x.java.api.exceptions.PlcProtocolException)7 PlcRequest (org.apache.plc4x.java.api.messages.PlcRequest)7 PlcWriteRequest (org.apache.plc4x.java.api.messages.PlcWriteRequest)6 PlcField (org.apache.plc4x.java.api.model.PlcField)6 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)5 List (java.util.List)4 Map (java.util.Map)4 ExecutionException (java.util.concurrent.ExecutionException)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 AbEthField (org.apache.plc4x.java.abeth.field.AbEthField)3 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)3 JsonArray (com.google.gson.JsonArray)2 JsonObject (com.google.gson.JsonObject)2 IOException (java.io.IOException)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2