Search in sources :

Example 26 with PlcReadRequest

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

the class Plc4x2AdsProtocol method encode.

@Override
protected void encode(ChannelHandlerContext ctx, PlcRequestContainer<InternalPlcRequest, InternalPlcResponse> msg, List<Object> out) throws Exception {
    LOGGER.trace("(<--OUT): {}, {}, {}", ctx, msg, out);
    PlcRequest request = msg.getRequest();
    if (request instanceof PlcReadRequest) {
        encodeReadRequest(msg, out);
    } else if (request instanceof PlcWriteRequest) {
        encodeWriteRequest(msg, out);
    } else if (request instanceof PlcProprietaryRequest) {
        encodeProprietaryRequest(msg, out);
    } else {
        throw new PlcProtocolException("Unknown type " + request.getClass());
    }
}
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 27 with PlcReadRequest

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

the class OpcuaPlcDriverTest method readVariables.

@Test
public void readVariables() throws Exception {
    PlcConnection opcuaConnection = new PlcDriverManager().getConnection(tcpConnectionAddress);
    assert opcuaConnection.isConnected();
    PlcReadRequest.Builder builder = opcuaConnection.readRequestBuilder();
    builder.addItem("Bool", BOOL_IDENTIFIER_READ_WRITE);
    builder.addItem("Byte", BYTE_IDENTIFIER_READ_WRITE);
    builder.addItem("Double", DOUBLE_IDENTIFIER_READ_WRITE);
    builder.addItem("Float", FLOAT_IDENTIFIER_READ_WRITE);
    builder.addItem("Int16", INT16_IDENTIFIER_READ_WRITE);
    builder.addItem("Int32", INT32_IDENTIFIER_READ_WRITE);
    builder.addItem("Int64", INT64_IDENTIFIER_READ_WRITE);
    builder.addItem("Integer", INTEGER_IDENTIFIER_READ_WRITE);
    builder.addItem("SByte", SBYTE_IDENTIFIER_READ_WRITE);
    builder.addItem("String", STRING_IDENTIFIER_READ_WRITE);
    builder.addItem("UInt16", UINT16_IDENTIFIER_READ_WRITE);
    builder.addItem("UInt32", UINT32_IDENTIFIER_READ_WRITE);
    builder.addItem("UInt64", UINT64_IDENTIFIER_READ_WRITE);
    builder.addItem("UInteger", UINTEGER_IDENTIFIER_READ_WRITE);
    builder.addItem("DoesNotExists", DOES_NOT_EXIST_IDENTIFIER_READ_WRITE);
    PlcReadRequest request = builder.build();
    PlcReadResponse response = request.execute().get();
    assert response.getResponseCode("Bool").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Byte").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Double").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Float").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Int16").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Int32").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Int64").equals(PlcResponseCode.OK);
    assert response.getResponseCode("Integer").equals(PlcResponseCode.OK);
    assert response.getResponseCode("SByte").equals(PlcResponseCode.OK);
    assert response.getResponseCode("String").equals(PlcResponseCode.OK);
    assert response.getResponseCode("UInt16").equals(PlcResponseCode.OK);
    assert response.getResponseCode("UInt32").equals(PlcResponseCode.OK);
    assert response.getResponseCode("UInt64").equals(PlcResponseCode.OK);
    assert response.getResponseCode("UInteger").equals(PlcResponseCode.OK);
    assert response.getResponseCode("DoesNotExists").equals(PlcResponseCode.NOT_FOUND);
    opcuaConnection.close();
    assert !opcuaConnection.isConnected();
}
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 28 with PlcReadRequest

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

the class S7PlcToAzureIoTHubSample method main.

/**
 * Example code do demonstrate sending events from an S7 device to Microsoft Azure IoT Hub
 *
 * @param args Expected: [plc4x connection string, plc4x field address, IoT-Hub connection string].
 */
public static void main(String[] args) throws Exception {
    CliOptions options = CliOptions.fromArgs(args);
    if (options == null) {
        CliOptions.printHelp();
        // Could not parse.
        System.exit(1);
    }
    LOGGER.info("Connecting {}, {}, {}", options.getPlc4xConnectionString(), options.getPlc4xFieldAddress(), options.getIotHubConnectionString());
    // Open both a connection to the remote PLC and the cloud service.
    DeviceClient client = new DeviceClient(options.getIotHubConnectionString(), IotHubClientProtocol.MQTT);
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getPlc4xConnectionString())) {
        LOGGER.info("Connected");
        client.open(true);
        // Prepare a read request.
        PlcReadRequest request = plcConnection.readRequestBuilder().addItem(FIELD_NAME, options.getPlc4xFieldAddress()).build();
        while (!Thread.currentThread().isInterrupted()) {
            // Simulate telemetry.
            PlcReadResponse response = request.execute().get();
            response.getAllLongs(FIELD_NAME).forEach(longValue -> {
                String result = Long.toBinaryString(longValue);
                LOGGER.info("Outputs {}", result);
                Message msg = new Message("{ \"bits\" : \"" + result + "\"}");
                // Send the message.
                client.sendEventAsync(msg, (sentMessage, clientException, callbackContext) -> {
                    if (clientException != null) {
                        LOGGER.info("Received exception: ", clientException);
                    } else {
                        LOGGER.info("Sent successfully");
                    }
                }, msg);
            });
            // Wait a second.
            TimeUnit.SECONDS.sleep(1);
        }
    } finally {
        client.close();
    }
}
Also used : PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) Message(com.microsoft.azure.sdk.iot.device.Message) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 29 with PlcReadRequest

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

the class MqttConnector method run.

private void run() throws PlcException {
    // Create a new MQTT client.
    final Mqtt3RxClient client = MqttClient.builder().identifier(UUID.randomUUID().toString()).serverHost(config.getMqttConfig().getServerHost()).serverPort(config.getMqttConfig().getServerPort()).useMqttVersion3().buildRx();
    // Connect to the MQTT broker.
    final Single<Mqtt3ConnAck> connAckSingle = client.connect().timeout(10, TimeUnit.SECONDS);
    // Connect to the PLC.
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(config.getPlcConfig().getConnection())) {
        // Check if this connection support reading of data.
        if (!plcConnection.getMetadata().canRead()) {
            System.err.println("This connection doesn't support reading.");
            return;
        }
        // Create a new read request.
        PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
        for (PlcFieldConfig fieldConfig : config.getPlcConfig().getPlcFields()) {
            builder = builder.addItem(fieldConfig.getName(), fieldConfig.getAddress());
        }
        PlcReadRequest readRequest = builder.build();
        // Send a message containing the PLC read response.
        Flowable<Mqtt3Publish> messagesToPublish = Flowable.generate(emitter -> {
            PlcReadResponse response = readRequest.execute().get();
            String jsonPayload = getPayload(response);
            final Mqtt3Publish publishMessage = Mqtt3Publish.builder().topic(config.getMqttConfig().getTopicName()).qos(MqttQos.AT_LEAST_ONCE).payload(jsonPayload.getBytes()).build();
            emitter.onNext(publishMessage);
        });
        // Emit 1 message only every 100 milliseconds.
        messagesToPublish = messagesToPublish.zipWith(Flowable.interval(config.getPollingInterval(), TimeUnit.MILLISECONDS), (publish, aLong) -> publish);
        final Single<Mqtt3ConnAck> connectScenario = connAckSingle.doOnSuccess(connAck -> System.out.println("Connected with return code " + connAck.getReturnCode())).doOnError(throwable -> System.out.println("Connection failed, " + throwable.getMessage()));
        final Flowable<Mqtt3PublishResult> publishScenario = client.publish(messagesToPublish).doOnNext(publishResult -> System.out.println("Publish acknowledged: " + new String(publishResult.getPublish().getPayloadAsBytes())));
        connectScenario.toCompletable().andThen(publishScenario).blockingSubscribe();
    } catch (Exception e) {
        throw new PlcException("Error creating connection to " + config.getPlcConfig().getConnection(), e);
    }
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) JsonObject(com.google.gson.JsonObject) PlcConnection(org.apache.plc4x.java.api.PlcConnection) LoggerFactory(org.slf4j.LoggerFactory) MqttQos(com.hivemq.client.mqtt.datatypes.MqttQos) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) Single(io.reactivex.Single) StringUtils(org.apache.commons.lang3.StringUtils) Mqtt3PublishResult(com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3PublishResult) MqttClient(com.hivemq.client.mqtt.MqttClient) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) Flowable(io.reactivex.Flowable) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) Mqtt3RxClient(com.hivemq.client.mqtt.mqtt3.Mqtt3RxClient) PlcFieldConfig(org.apache.plc4x.java.examples.connectivity.mqtt.model.PlcFieldConfig) Logger(org.slf4j.Logger) Configuration(org.apache.plc4x.java.examples.connectivity.mqtt.model.Configuration) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Mqtt3ConnAck(com.hivemq.client.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck) IOException(java.io.IOException) UUID(java.util.UUID) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) JsonArray(com.google.gson.JsonArray) Mqtt3Publish(com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish) Mqtt3RxClient(com.hivemq.client.mqtt.mqtt3.Mqtt3RxClient) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) IOException(java.io.IOException) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) Mqtt3PublishResult(com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3PublishResult) PlcFieldConfig(org.apache.plc4x.java.examples.connectivity.mqtt.model.PlcFieldConfig) Mqtt3Publish(com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) Mqtt3ConnAck(com.hivemq.client.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager)

Example 30 with PlcReadRequest

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

the class HelloPlc4x method main.

/**
 * Example code do demonstrate using PLC4X.
 *
 * @param args ignored.
 */
public static void main(String[] args) throws Exception {
    CliOptions options = CliOptions.fromArgs(args);
    if (options == null) {
        CliOptions.printHelp();
        // Could not parse.
        System.exit(1);
    }
    // Establish a connection to the plc using the url provided as first argument
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getConnectionString())) {
        // Check if this connection support reading of data.
        if (!plcConnection.getMetadata().canRead()) {
            logger.error("This connection doesn't support reading.");
            return;
        }
        // Create a new read request:
        // - Give the single item requested the alias name "value"
        PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
        for (int i = 0; i < options.getFieldAddress().length; i++) {
            builder.addItem("value-" + options.getFieldAddress()[i], options.getFieldAddress()[i]);
        }
        PlcReadRequest readRequest = builder.build();
        // ////////////////////////////////////////////////////////
        // Read synchronously ...
        // NOTICE: the ".get()" immediately lets this thread pause until
        // the response is processed and available.
        logger.info("Synchronous request ...");
        PlcReadResponse syncResponse = readRequest.execute().get();
        // Simply iterating over the field names returned in the response.
        printResponse(syncResponse);
        /*PlcValue asPlcValue = syncResponse.getAsPlcValue();
            System.out.println(asPlcValue.toString());*/
        // ////////////////////////////////////////////////////////
        // Read asynchronously ...
        // Register a callback executed as soon as a response arrives.
        /*logger.info("Asynchronous request ...");
            CompletionStage<? extends PlcReadResponse> asyncResponse = readRequest.execute();
            asyncResponse.whenComplete((readResponse, throwable) -> {
                if (readResponse != null) {
                    printResponse(readResponse);
                } else {
                    logger.error("An error occurred: " + throwable.getMessage(), throwable);
                }
            });*/
        // Give the async request a little time...
        TimeUnit.MILLISECONDS.sleep(1000);
        plcConnection.close();
        System.exit(0);
    }
}
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)

Aggregations

PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)37 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)21 PlcConnection (org.apache.plc4x.java.api.PlcConnection)17 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)12 PlcWriteRequest (org.apache.plc4x.java.api.messages.PlcWriteRequest)9 PlcField (org.apache.plc4x.java.api.model.PlcField)9 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)8 PlcProtocolException (org.apache.plc4x.java.api.exceptions.PlcProtocolException)7 PlcRequest (org.apache.plc4x.java.api.messages.PlcRequest)7 ExecutionException (java.util.concurrent.ExecutionException)5 PlcWriteResponse (org.apache.plc4x.java.api.messages.PlcWriteResponse)5 PlcValue (org.apache.plc4x.java.api.value.PlcValue)5 DefaultPlcReadResponse (org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse)5 Duration (java.time.Duration)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)4 DefaultPlcReadRequest (org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest)4 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)4