Search in sources :

Example 26 with PlcDriverManager

use of org.apache.plc4x.java.PlcDriverManager in project plc4x by apache.

the class HelloPlc4xSubscription method run.

public void run() throws Exception {
    // Establish a connection to the plc.
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getConnectionString())) {
        // Check if this connection support subscriptions.
        if (!plcConnection.getMetadata().canSubscribe()) {
            logger.error("This connection doesn't support subscriptions.");
            return;
        }
        // Create a new read request:
        // - Give the single item requested the alias name "value"
        final PlcSubscriptionRequest.Builder builder = plcConnection.subscriptionRequestBuilder();
        for (int i = 0; i < options.getFieldAddress().length; i++) {
            builder.addChangeOfStateField("value-" + i, options.getFieldAddress()[i]);
        }
        PlcSubscriptionRequest subscriptionRequest = builder.build();
        // Execute the subscription response.
        final PlcSubscriptionResponse subscriptionResponse = subscriptionRequest.execute().get();
        // Attach handlers for the incoming data.
        for (String subscriptionName : subscriptionResponse.getFieldNames()) {
            final PlcSubscriptionHandle subscriptionHandle = subscriptionResponse.getSubscriptionHandle(subscriptionName);
            subscriptionHandle.register(new ValueChangeHandler());
        }
        // Wait for the user to press "Enter" to abort the program.
        Scanner scanner = new Scanner(System.in);
        try {
            logger.info("Please press Enter to exit program.");
            scanner.nextLine();
            logger.info("Finishing");
        } catch (IllegalStateException e) {
            // System.in has been closed
            logger.error("System.in was closed; exiting");
        }
    }
}
Also used : Scanner(java.util.Scanner) PlcSubscriptionRequest(org.apache.plc4x.java.api.messages.PlcSubscriptionRequest) PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) PlcSubscriptionHandle(org.apache.plc4x.java.api.model.PlcSubscriptionHandle) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 27 with PlcDriverManager

use of org.apache.plc4x.java.PlcDriverManager in project plc4x by apache.

the class HelloPlc4xWrite method run.

public void run() throws Exception {
    // Establish a connection to the plc.
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getConnectionString())) {
        // Check if this connection support subscriptions.
        if (!plcConnection.getMetadata().canWrite()) {
            LOGGER.error("This connection doesn't support writing.");
            return;
        }
        if (options.getFieldValues().length != options.getFieldAddress().length) {
            LOGGER.error("The number of values doesn't match the number of addresses.");
            return;
        }
        // Create a new read request:
        // - Give the single item requested the alias name "value"
        final PlcWriteRequest.Builder builder = plcConnection.writeRequestBuilder();
        for (int i = 0; i < options.getFieldAddress().length; i++) {
            // If an array value is passed instead of a single value then convert to a String array
            if ((options.getFieldValues()[i].charAt(0) == '[') && (options.getFieldValues()[i].charAt(options.getFieldValues()[i].length() - 1) == ']')) {
                String[] values = options.getFieldValues()[i].substring(1, options.getFieldValues()[i].length() - 1).split(",");
                builder.addItem("value-" + i, options.getFieldAddress()[i], values);
            } else {
                builder.addItem("value-" + i, options.getFieldAddress()[i], options.getFieldValues()[i]);
            }
        }
        PlcWriteRequest writeRequest = builder.build();
        // Execute the write request.
        final PlcWriteResponse writeResponse = writeRequest.execute().get();
        // Attach handlers for the incoming data.
        for (String fieldName : writeResponse.getFieldNames()) {
            LOGGER.info(String.format("Return code for %s was %s", fieldName, writeResponse.getResponseCode(fieldName)));
        }
    }
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 28 with PlcDriverManager

use of org.apache.plc4x.java.PlcDriverManager 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)

Example 29 with PlcDriverManager

use of org.apache.plc4x.java.PlcDriverManager in project plc4x by apache.

the class HelloInflux method connectToPlc.

private PlcConnection connectToPlc() throws PlcException {
    final PlcConnection connection = new PlcDriverManager().getConnection(configuration.getString("plc.connectionString"));
    connection.connect();
    return connection;
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 30 with PlcDriverManager

use of org.apache.plc4x.java.PlcDriverManager in project plc4x by apache.

the class ManualKnxNetIp method main.

// Addresses:
// */*/10: Temperature
// */*/12: Heating
// */*/60: Primary Window
// */*/64: Second Window
// */*/101: Power Line 1
public static void main(String[] args) throws Exception {
    // final PlcConnection connection = new PlcDriverManager().getConnection("knxnet-ip://192.168.42.11?knxproj-file-path=/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/KNX/Stettiner%20Str.%2013/StettinerStr-Soll-Ist-Temperatur.knxproj");
    final PlcConnection connection = new PlcDriverManager().getConnection("knxnet-ip:pcap:///Users/christofer.dutz/Projects/Apache/PLC4X-Documents/KNX/Recording-01.03.2020-2.pcapng?knxproj-file-path=/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/KNX/Stettiner%20Str.%2013/StettinerStr-Soll-Ist-Temperatur.knxproj");
    // Make sure we hang up correctly when terminating.
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            connection.close();
        } catch (Exception e) {
            throw new PlcRuntimeException("Error closing connection", e);
        }
    }));
    // Create a new subscription request.
    // The address and the name is just bogus as we're always returning everything.
    // We will probably refactor the API in the near future.
    final PlcSubscriptionRequest subscriptionRequest = connection.subscriptionRequestBuilder().addEventField("knxData", "*/*/*").build();
    // Register the subscription
    // The timeout is also just a bogus value as the data is coming in actively
    // We will probably refactor the API in the near future.
    final PlcSubscriptionResponse subscriptionResponse = subscriptionRequest.execute().get(1000, TimeUnit.MILLISECONDS);
    // Register a callback which is called on new data being available.
    final PlcSubscriptionHandle subscriptionHandle = subscriptionResponse.getSubscriptionHandle("knxData");
    subscriptionHandle.register(knxData -> {
        System.out.println(knxData.getTimestamp().toString() + " - " + ((DefaultPlcSubscriptionEvent) knxData).getValues().get("knxData"));
    });
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcSubscriptionRequest(org.apache.plc4x.java.api.messages.PlcSubscriptionRequest) PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) PlcSubscriptionHandle(org.apache.plc4x.java.api.model.PlcSubscriptionHandle) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException)

Aggregations

PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)54 PlcConnection (org.apache.plc4x.java.api.PlcConnection)35 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)13 PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)13 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)13 Test (org.junit.jupiter.api.Test)12 PooledPlcDriverManager (org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager)10 BigInteger (java.math.BigInteger)8 ExecutionException (java.util.concurrent.ExecutionException)8 TimeUnit (java.util.concurrent.TimeUnit)5 Condition (org.assertj.core.api.Condition)5 BigDecimal (java.math.BigDecimal)4 LocalDate (java.time.LocalDate)4 Map (java.util.Map)4 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)4 PlcSubscriptionRequest (org.apache.plc4x.java.api.messages.PlcSubscriptionRequest)4 PlcSubscriptionResponse (org.apache.plc4x.java.api.messages.PlcSubscriptionResponse)4 PlcSubscriptionHandle (org.apache.plc4x.java.api.model.PlcSubscriptionHandle)4 Disabled (org.junit.jupiter.api.Disabled)4 LocalDateTime (java.time.LocalDateTime)3