You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by cd...@apache.org on 2018/11/20 15:39:37 UTC
[incubator-plc4x] branch develop updated (e3f3936 -> d9d2503)
This is an automated email from the ASF dual-hosted git repository.
cdutz pushed a change to branch develop
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git.
from e3f3936 - Minor update of the release.adoc to use a different tag name as the original version was causing problems during the release. - Manually added a mention of the MqttExampleOptions.java being copyrighted by Google to the main LICENSE file.
new d33bfbd - Fixed the MQTT example after API changes in the MQTT-Bee project
new d9d2503 - Unified the way the examples are configured.
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
examples/hello-cloud-azure/pom.xml | 6 +
.../java/examples/cloud/azure/CliOptions.java | 93 +++++++++
.../cloud/azure/S7PlcToAzureIoTHubSample.java | 22 +--
examples/hello-cloud-google/pom.xml | 23 +--
.../java/examples/cloud/google/CliOptions.java | 216 +++++++++++++++++++++
.../examples/cloud/google/MqttExampleOptions.java | 164 ----------------
.../cloud/google/S7PlcToGoogleIoTCoreSample.java | 28 +--
.../examples/connectivity/mqtt/MqttConnector.java | 8 +-
.../plc4x/java/examples/helloplc4x/HelloPlc4x.java | 110 -----------
examples/hello-world-plc4x/pom.xml | 5 +
.../plc4x/java/examples/helloplc4x/CliOptions.java | 78 ++++++++
.../plc4x/java/examples/helloplc4x/HelloPlc4x.java | 14 +-
12 files changed, 442 insertions(+), 325 deletions(-)
create mode 100644 examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/CliOptions.java
create mode 100644 examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/CliOptions.java
delete mode 100644 examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/MqttExampleOptions.java
delete mode 100644 examples/hello-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java
create mode 100644 examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/CliOptions.java
[incubator-plc4x] 01/02: - Fixed the MQTT example after API changes
in the MQTT-Bee project
Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git
commit d33bfbd0a648cbcd669f4146252f4f6b9613e1af
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Nov 20 16:13:09 2018 +0100
- Fixed the MQTT example after API changes in the MQTT-Bee project
---
.../plc4x/java/examples/connectivity/mqtt/MqttConnector.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/examples/hello-connectivity-mqtt/src/main/java/org/apache/plc4x/java/examples/connectivity/mqtt/MqttConnector.java b/examples/hello-connectivity-mqtt/src/main/java/org/apache/plc4x/java/examples/connectivity/mqtt/MqttConnector.java
index 948f11d..685f63d 100644
--- a/examples/hello-connectivity-mqtt/src/main/java/org/apache/plc4x/java/examples/connectivity/mqtt/MqttConnector.java
+++ b/examples/hello-connectivity-mqtt/src/main/java/org/apache/plc4x/java/examples/connectivity/mqtt/MqttConnector.java
@@ -35,7 +35,7 @@ import org.apache.plc4x.java.examples.connectivity.mqtt.model.Configuration;
import org.apache.plc4x.java.examples.connectivity.mqtt.model.PlcFieldConfig;
import org.mqttbee.api.mqtt.MqttClient;
import org.mqttbee.api.mqtt.datatypes.MqttQos;
-import org.mqttbee.api.mqtt.mqtt3.Mqtt3Client;
+import org.mqttbee.api.mqtt.mqtt3.Mqtt3RxClient;
import org.mqttbee.api.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck;
import org.mqttbee.api.mqtt.mqtt3.message.publish.Mqtt3Publish;
import org.mqttbee.api.mqtt.mqtt3.message.publish.Mqtt3PublishResult;
@@ -73,15 +73,15 @@ public class MqttConnector {
private void run() throws PlcException {
// Create a new MQTT client.
- final Mqtt3Client client = MqttClient.builder()
+ final Mqtt3RxClient client = MqttClient.builder()
.identifier(UUID.randomUUID().toString())
.serverHost(config.getMqttConfig().getServerHost())
.serverPort(config.getMqttConfig().getServerPort())
.useMqttVersion3()
- .buildReactive();
+ .buildRx();
// Connect to the MQTT broker.
- final Single<Mqtt3ConnAck> connAckSingle = client.connect().keepAlive(10, TimeUnit.SECONDS).done();
+ final Single<Mqtt3ConnAck> connAckSingle = client.connect().timeout(10, TimeUnit.SECONDS);
// Connect to the PLC.
try (PlcConnection plcConnection = new PlcDriverManager().getConnection(config.getPlcConfig().getConnection())) {
[incubator-plc4x] 02/02: - Unified the way the examples are
configured.
Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git
commit d9d2503c93e6c2c320dec71f01a312e49d2e63c8
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Nov 20 16:39:33 2018 +0100
- Unified the way the examples are configured.
---
examples/hello-cloud-azure/pom.xml | 6 +
.../java/examples/cloud/azure/CliOptions.java | 93 +++++++++
.../cloud/azure/S7PlcToAzureIoTHubSample.java | 22 +--
examples/hello-cloud-google/pom.xml | 23 +--
.../java/examples/cloud/google/CliOptions.java | 216 +++++++++++++++++++++
.../examples/cloud/google/MqttExampleOptions.java | 164 ----------------
.../cloud/google/S7PlcToGoogleIoTCoreSample.java | 28 +--
.../plc4x/java/examples/helloplc4x/HelloPlc4x.java | 110 -----------
examples/hello-world-plc4x/pom.xml | 5 +
.../plc4x/java/examples/helloplc4x/CliOptions.java | 78 ++++++++
.../plc4x/java/examples/helloplc4x/HelloPlc4x.java | 14 +-
11 files changed, 438 insertions(+), 321 deletions(-)
diff --git a/examples/hello-cloud-azure/pom.xml b/examples/hello-cloud-azure/pom.xml
index 5cff896..966d6ff 100644
--- a/examples/hello-cloud-azure/pom.xml
+++ b/examples/hello-cloud-azure/pom.xml
@@ -52,6 +52,12 @@
</dependency>
<dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>1.4</version>
+ </dependency>
+
+ <dependency>
<groupId>org.apache.plc4x</groupId>
<artifactId>plc4j-protocol-s7</artifactId>
<version>0.3.0-SNAPSHOT</version>
diff --git a/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/CliOptions.java b/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/CliOptions.java
new file mode 100644
index 0000000..42fb547
--- /dev/null
+++ b/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/CliOptions.java
@@ -0,0 +1,93 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+
+package org.apache.plc4x.java.examples.cloud.azure;
+
+import org.apache.commons.cli.*;
+
+public class CliOptions {
+
+ private final String plc4xConnectionString;
+ private final String plc4xFieldAddress;
+ private final String iotHubConnectionString;
+
+ /** Construct an MqttExampleOptions class from command line flags. */
+ public static CliOptions fromFlags(String[] args) {
+ org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();
+ // Required arguments
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("plc4x-connection-string")
+ .hasArg()
+ .desc("Connection String")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("plc4x-field-address")
+ .hasArg()
+ .desc("Field Address.")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("iot-hub-connection-string")
+ .hasArg()
+ .desc("IoT Hub Connection String.")
+ .required()
+ .build());
+
+ CommandLineParser parser = new DefaultParser();
+ CommandLine commandLine;
+ try {
+ commandLine = parser.parse(options, args);
+
+ String plc4xConnectionString = commandLine.getOptionValue("plc4x-connection-string");
+ String plc4xFieldAddress = commandLine.getOptionValue("plc4x-field-address");
+ String iotHubConnectionString = commandLine.getOptionValue("iot-hub-connection-string");
+
+ return new CliOptions(plc4xConnectionString, plc4xFieldAddress, iotHubConnectionString);
+ } catch (ParseException e) {
+ System.err.println(e.getMessage());
+ return null;
+ }
+ }
+
+ public CliOptions(String plc4xConnectionString, String plc4xFieldAddress, String iotHubConnectionString) {
+ this.plc4xConnectionString = plc4xConnectionString;
+ this.plc4xFieldAddress = plc4xFieldAddress;
+ this.iotHubConnectionString = iotHubConnectionString;
+ }
+
+ public String getPlc4xConnectionString() {
+ return plc4xConnectionString;
+ }
+
+ public String getPlc4xFieldAddress() {
+ return plc4xFieldAddress;
+ }
+
+ protected String getIotHubConnectionString() {
+ return iotHubConnectionString;
+ }
+
+}
diff --git a/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/S7PlcToAzureIoTHubSample.java b/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/S7PlcToAzureIoTHubSample.java
index 71cf6bd..34f8c3c 100644
--- a/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/S7PlcToAzureIoTHubSample.java
+++ b/examples/hello-cloud-azure/src/main/java/org/apache/plc4x/java/examples/cloud/azure/S7PlcToAzureIoTHubSample.java
@@ -42,26 +42,25 @@ public class S7PlcToAzureIoTHubSample {
* @param args Expected: [plc4x connection string, plc4x field address, IoT-Hub connection string].
*/
public static void main(String[] args) throws Exception {
- if (args.length != 3) {
- System.out.println("Usage: S7PlcToAzureIoTHubSample " +
- "{plc4x-connection-string} {plc4x-field-address} {iot-hub-connection-string}");
- return;
+ CliOptions options = CliOptions.fromFlags(args);
+ if (options == null) {
+ // Could not parse.
+ System.exit(1);
}
- String plc4xConnectionString = args[0];
- String addressString = args[1];
- String iotConnectionString = args[2];
- LOGGER.info("Connecting {}, {}, {}", plc4xConnectionString, addressString, iotConnectionString);
+ LOGGER.info("Connecting {}, {}, {}", options.getPlc4xConnectionString(), options.getPlc4xFieldAddress(),
+ options.getIotHubConnectionString());
// Open both a connection to the remote PLC as well as a connection to the cloud service.
- try (PlcConnection plcConnection = new PlcDriverManager().getConnection(plc4xConnectionString);
- DeviceClient client = new DeviceClient(iotConnectionString, IotHubClientProtocol.MQTT)) {
+ try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getPlc4xConnectionString());
+ DeviceClient client = new DeviceClient(options.getIotHubConnectionString(), IotHubClientProtocol.MQTT)) {
LOGGER.info("Connected");
client.open();
// Prepare a read request.
- PlcReadRequest request = plcConnection.readRequestBuilder().addItem(FIELD_NAME, addressString).build();
+ PlcReadRequest request = plcConnection.readRequestBuilder()
+ .addItem(FIELD_NAME, options.getPlc4xFieldAddress()).build();
while (!Thread.currentThread().isInterrupted()) {
// Simulate telemetry.
@@ -82,4 +81,5 @@ public class S7PlcToAzureIoTHubSample {
}
}
}
+
}
diff --git a/examples/hello-cloud-google/pom.xml b/examples/hello-cloud-google/pom.xml
index d3d7f9b..7ccb311 100644
--- a/examples/hello-cloud-google/pom.xml
+++ b/examples/hello-cloud-google/pom.xml
@@ -59,41 +59,27 @@
<artifactId>plc4j-core</artifactId>
<version>0.3.0-SNAPSHOT</version>
</dependency>
+
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
- <groupId>org.apache.plc4x</groupId>
- <artifactId>plc4j-protocol-s7</artifactId>
- <version>0.3.0-SNAPSHOT</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
- <scope>compile</scope>
</dependency>
- <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- <!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
- <!-- https://mvnrepository.com/artifact/org.apache.beam/beam-runners-google-cloud-dataflow-java -->
- <!--dependency>
- <groupId>org.apache.beam</groupId>
- <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
- <version>2.6.0</version>
- </dependency-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
@@ -103,6 +89,13 @@
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.apache.plc4x</groupId>
+ <artifactId>plc4j-protocol-s7</artifactId>
+ <version>0.3.0-SNAPSHOT</version>
+ <scope>runtime</scope>
+ </dependency>
</dependencies>
<dependencyManagement>
diff --git a/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/CliOptions.java b/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/CliOptions.java
new file mode 100644
index 0000000..ae72ff0
--- /dev/null
+++ b/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/CliOptions.java
@@ -0,0 +1,216 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+
+package org.apache.plc4x.java.examples.cloud.google;
+
+import org.apache.commons.cli.*;
+
+/** Command line options for the MQTT example. */
+public class CliOptions {
+
+ private final String projectId;
+ private final String registryId;
+ private final String deviceId;
+ private final String privateKeyFile;
+ private final String algorithm;
+ private final String cloudRegion;
+ private final int tokenExpMins;
+ private final String mqttBridgeHostname;
+ private final short mqttBridgePort;
+ private final String messageType;
+
+ /** Construct an MqttExampleOptions class from command line flags. */
+ public static CliOptions fromFlags(String[] args) {
+ org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();
+ // Required arguments
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("project-id")
+ .hasArg()
+ .desc("GCP cloud project name.")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("registry-id")
+ .hasArg()
+ .desc("Cloud IoT Core registry id.")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("device-id")
+ .hasArg()
+ .desc("Cloud IoT Core device id.")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("private-key-file")
+ .hasArg()
+ .desc("Path to private key file.")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("algorithm")
+ .hasArg()
+ .desc("Encryption algorithm to use to generate the JWT. Either 'RS256' or 'ES256'.")
+ .required()
+ .build());
+
+ // Optional arguments.
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("cloud-region")
+ .hasArg()
+ .desc("GCP cloud region.")
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("mqtt-bridge-hostname")
+ .hasArg()
+ .desc("MQTT bridge hostname.")
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(Number.class)
+ .longOpt("token-exp-minutes")
+ .hasArg()
+ .desc("Minutes to JWT token refresh (token expiration time).")
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(Number.class)
+ .longOpt("mqtt-bridge-port")
+ .hasArg()
+ .desc("MQTT bridge port.")
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("message-type")
+ .hasArg()
+ .desc("Indicates whether the message is a telemetry event or a device state message")
+ .build());
+
+ CommandLineParser parser = new DefaultParser();
+ CommandLine commandLine;
+ try {
+ commandLine = parser.parse(options, args);
+
+ String projectId = commandLine.getOptionValue("project-id");
+ String registryId = commandLine.getOptionValue("registry-id");
+ String deviceId = commandLine.getOptionValue("device-id");
+ String privateKeyFile = commandLine.getOptionValue("private-key-file");
+ String algorithm = commandLine.getOptionValue("algorithm");
+ String cloudRegion = "europe-west1";
+ if (commandLine.hasOption("cloud-region")) {
+ cloudRegion = commandLine.getOptionValue("cloud-region");
+ }
+ int tokenExpMins = 20;
+ if (commandLine.hasOption("token-exp-minutes")) {
+ tokenExpMins =
+ ((Number) commandLine.getParsedOptionValue("token-exp-minutes")).intValue();
+ }
+ String mqttBridgeHostname = "mqtt.googleapis.com";
+ if (commandLine.hasOption("mqtt-bridge-hostname")) {
+ mqttBridgeHostname = commandLine.getOptionValue("mqtt-bridge-hostname");
+ }
+ short mqttBridgePort = 8883;
+ if (commandLine.hasOption("mqtt-bridge-port")) {
+ mqttBridgePort =
+ ((Number) commandLine.getParsedOptionValue("mqtt-bridge-port")).shortValue();
+ }
+ String messageType = "event";
+ if (commandLine.hasOption("message-type")) {
+ messageType = commandLine.getOptionValue("message-type");
+ }
+
+ return new CliOptions(projectId, registryId, deviceId, privateKeyFile, algorithm, cloudRegion, tokenExpMins,
+ mqttBridgeHostname, mqttBridgePort, messageType);
+ } catch (ParseException e) {
+ System.err.println(e.getMessage());
+ return null;
+ }
+ }
+
+ public CliOptions(String projectId, String registryId, String deviceId, String privateKeyFile, String algorithm,
+ String cloudRegion, int tokenExpMins, String mqttBridgeHostname, short mqttBridgePort,
+ String messageType) {
+ this.projectId = projectId;
+ this.registryId = registryId;
+ this.deviceId = deviceId;
+ this.privateKeyFile = privateKeyFile;
+ this.algorithm = algorithm;
+ this.cloudRegion = cloudRegion;
+ this.tokenExpMins = tokenExpMins;
+ this.mqttBridgeHostname = mqttBridgeHostname;
+ this.mqttBridgePort = mqttBridgePort;
+ this.messageType = messageType;
+ }
+
+ public String getProjectId() {
+ return projectId;
+ }
+
+ public String getRegistryId() {
+ return registryId;
+ }
+
+ public String getDeviceId() {
+ return deviceId;
+ }
+
+ public String getPrivateKeyFile() {
+ return privateKeyFile;
+ }
+
+ public String getAlgorithm() {
+ return algorithm;
+ }
+
+ public String getCloudRegion() {
+ return cloudRegion;
+ }
+
+ public int getTokenExpMins() {
+ return tokenExpMins;
+ }
+
+ public String getMqttBridgeHostname() {
+ return mqttBridgeHostname;
+ }
+
+ public short getMqttBridgePort() {
+ return mqttBridgePort;
+ }
+
+ public String getMessageType() {
+ return messageType;
+ }
+
+}
\ No newline at end of file
diff --git a/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/MqttExampleOptions.java b/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/MqttExampleOptions.java
deleted file mode 100644
index 22a2a07..0000000
--- a/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/MqttExampleOptions.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-package org.apache.plc4x.java.examples.cloud.google;
-
-import org.apache.commons.cli.*;
-
-/** Command line options for the MQTT example. */
-public class MqttExampleOptions {
- String projectId;
- String registryId;
- String deviceId;
- String privateKeyFile;
- String algorithm;
- String cloudRegion = "europe-west1";
- int numMessages = 100;
- int tokenExpMins = 20;
- String mqttBridgeHostname = "mqtt.googleapis.com";
- short mqttBridgePort = 8883;
- String messageType = "event";
-
- /** Construct an MqttExampleOptions class from command line flags. */
- public static MqttExampleOptions fromFlags(String[] args) {
- Options options = new Options();
- // Required arguments
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("project_id")
- .hasArg()
- .desc("GCP cloud project name.")
- .required()
- .build());
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("registry_id")
- .hasArg()
- .desc("Cloud IoT Core registry id.")
- .required()
- .build());
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("device_id")
- .hasArg()
- .desc("Cloud IoT Core device id.")
- .required()
- .build());
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("private_key_file")
- .hasArg()
- .desc("Path to private key file.")
- .required()
- .build());
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("algorithm")
- .hasArg()
- .desc("Encryption algorithm to use to generate the JWT. Either 'RS256' or 'ES256'.")
- .required()
- .build());
-
- // Optional arguments.
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("cloud_region")
- .hasArg()
- .desc("GCP cloud region.")
- .build());
- options.addOption(
- Option.builder()
- .type(Number.class)
- .longOpt("num_messages")
- .hasArg()
- .desc("Number of messages to publish.")
- .build());
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("mqtt_bridge_hostname")
- .hasArg()
- .desc("MQTT bridge hostname.")
- .build());
- options.addOption(
- Option.builder()
- .type(Number.class)
- .longOpt("token_exp_minutes")
- .hasArg()
- .desc("Minutes to JWT token refresh (token expiration time).")
- .build());
- options.addOption(
- Option.builder()
- .type(Number.class)
- .longOpt("mqtt_bridge_port")
- .hasArg()
- .desc("MQTT bridge port.")
- .build());
- options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("message_type")
- .hasArg()
- .desc("Indicates whether the message is a telemetry event or a device state message")
- .build());
-
- CommandLineParser parser = new DefaultParser();
- CommandLine commandLine;
- try {
- commandLine = parser.parse(options, args);
- MqttExampleOptions res = new MqttExampleOptions();
-
- res.projectId = commandLine.getOptionValue("project_id");
- res.registryId = commandLine.getOptionValue("registry_id");
- res.deviceId = commandLine.getOptionValue("device_id");
- res.privateKeyFile = commandLine.getOptionValue("private_key_file");
- res.algorithm = commandLine.getOptionValue("algorithm");
- if (commandLine.hasOption("cloud_region")) {
- res.cloudRegion = commandLine.getOptionValue("cloud_region");
- }
- if (commandLine.hasOption("num_messages")) {
- res.numMessages = ((Number) commandLine.getParsedOptionValue("num_messages")).intValue();
- }
- if (commandLine.hasOption("token_exp_minutes")) {
- res.tokenExpMins =
- ((Number) commandLine.getParsedOptionValue("token_exp_minutes")).intValue();
- }
- if (commandLine.hasOption("mqtt_bridge_hostname")) {
- res.mqttBridgeHostname = commandLine.getOptionValue("mqtt_bridge_hostname");
- }
- if (commandLine.hasOption("mqtt_bridge_port")) {
- res.mqttBridgePort =
- ((Number) commandLine.getParsedOptionValue("mqtt_bridge_port")).shortValue();
- }
- if (commandLine.hasOption("message_type")) {
- res.messageType = commandLine.getOptionValue("message_type");
- }
- return res;
- } catch (ParseException e) {
- System.err.println(e.getMessage());
- return null;
- }
- }
-}
\ No newline at end of file
diff --git a/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/S7PlcToGoogleIoTCoreSample.java b/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/S7PlcToGoogleIoTCoreSample.java
index 08db1e3..2301ae2 100644
--- a/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/S7PlcToGoogleIoTCoreSample.java
+++ b/examples/hello-cloud-google/src/main/java/org/apache/plc4x/java/examples/cloud/google/S7PlcToGoogleIoTCoreSample.java
@@ -126,20 +126,20 @@ public class S7PlcToGoogleIoTCoreSample {
// [END iot_mqtt_configcallback]
- private static void setConnectPassword(MqttExampleOptions options, MqttConnectOptions connectOptions)
+ private static void setConnectPassword(CliOptions options, MqttConnectOptions connectOptions)
throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
- switch (options.algorithm) {
+ switch (options.getAlgorithm()) {
case "RS256":
connectOptions.setPassword(
- createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
+ createJwtRsa(options.getProjectId(), options.getPrivateKeyFile()).toCharArray());
break;
case "ES256":
connectOptions.setPassword(
- createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
+ createJwtEs(options.getProjectId(), options.getPrivateKeyFile()).toCharArray());
break;
default:
throw new IllegalArgumentException(
- "Invalid algorithm " + options.algorithm
+ "Invalid algorithm " + options.getAlgorithm()
+ ". Should be one of 'RS256' or 'ES256'.");
}
}
@@ -152,7 +152,7 @@ public class S7PlcToGoogleIoTCoreSample {
public static void main(String[] args) throws Exception {
// [START iot_mqtt_configuremqtt]
- MqttExampleOptions options = MqttExampleOptions.fromFlags(args);
+ CliOptions options = CliOptions.fromFlags(args);
if (options == null) {
// Could not parse.
System.exit(1);
@@ -162,13 +162,13 @@ public class S7PlcToGoogleIoTCoreSample {
// connections are accepted. For server authentication, the JVM's root certificates
// are used.
final String mqttServerAddress =
- String.format("ssl://%s:%s", options.mqttBridgeHostname, options.mqttBridgePort);
+ 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.projectId, options.cloudRegion, options.registryId, options.deviceId);
+ 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
@@ -223,15 +223,15 @@ public class S7PlcToGoogleIoTCoreSample {
}
}
- attachCallback(client, options.deviceId);
+ attachCallback(client, options.getDeviceId());
// Publish to the events or state topic based on the flag.
- String subTopic = "event".equals(options.messageType) ? "events" : options.messageType;
+ 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.deviceId, subTopic);
+ String mqttTopic = String.format("/devices/%s/%s", options.getDeviceId(), subTopic);
// Connect to Plc
logger.info("Connecting to Plc");
@@ -247,13 +247,13 @@ public class S7PlcToGoogleIoTCoreSample {
// Refresh the connection credentials before the JWT expires.
// [START iot_mqtt_jwt_refresh]
long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
- if (secsSinceRefresh > (options.tokenExpMins * 60)) {
+ 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.deviceId);
+ attachCallback(client, options.getDeviceId());
}
// [END iot_mqtt_jwt_refresh]
@@ -268,7 +268,7 @@ public class S7PlcToGoogleIoTCoreSample {
MqttMessage message = new MqttMessage(array);
message.setQos(1);
client.publish(mqttTopic, message);
- if ("event".equals(options.messageType)) {
+ if ("event".equals(options.getMessageType())) {
// Send telemetry events every second
Thread.sleep(1000);
} else {
diff --git a/examples/hello-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java b/examples/hello-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java
deleted file mode 100644
index 1204bd3..0000000
--- a/examples/hello-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied. See the License for the
-specific language governing permissions and limitations
-under the License.
-*/
-package org.apache.plc4x.java.examples.helloplc4x;
-
-import org.apache.plc4x.java.PlcDriverManager;
-import org.apache.plc4x.java.api.PlcConnection;
-import org.apache.plc4x.java.api.messages.PlcReadRequest;
-import org.apache.plc4x.java.api.messages.PlcReadResponse;
-import org.apache.plc4x.java.api.types.PlcResponseCode;
-
-import java.util.concurrent.CompletableFuture;
-
-public class HelloPlc4x {
-
- /**
- * Example code do demonstrate using PLC4X.
- *
- * @param args ignored.
- */
-public static void main(String[] args) throws Exception {
- if (args.length < 2) {
- System.out.println("Usage: HelloPlc4x {connection-string} {address-string}+");
- System.out.println("Example: HelloPlc4x s7://10.10.64.20/1/1 %Q0.0:BOOL %Q0:BYTE");
- return;
- }
-
- // Establish a connection to the plc using the url provided as first argument
- try (PlcConnection plcConnection = new PlcDriverManager().getConnection(args[0])) {
-
- // 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:
- // - Give the single item requested the alias name "value"
- PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
- for (int i = 1; i < args.length; i++) {
- builder.addItem("value-" + i, args[i]);
- }
-
- //////////////////////////////////////////////////////////
- // Read synchronously ...
- // NOTICE: the ".get()" immediately lets this thread pause until
- // the response is processed and available.
- System.out.println("Synchronous request ...");
- PlcReadRequest syncReadRequest = builder.build();
- PlcReadResponse syncResponse = syncReadRequest.execute().get();
- // Simply iterating over the field names returned in the response.
- printResponse(syncResponse);
-
- //////////////////////////////////////////////////////////
- // Read asynchronously ...
- // Register a callback executed as soon as a response arrives.
- System.out.println("Asynchronous request ...");
- PlcReadRequest asyncReadRequest = builder.build();
- CompletableFuture<? extends PlcReadResponse> asyncResponse = asyncReadRequest.execute();
- asyncResponse.whenComplete((readResponse, throwable) -> {
- if (readResponse != null) {
- printResponse(readResponse);
- } else {
- System.err.println("An error occurred: " + throwable.getMessage());
- throwable.printStackTrace();
- }
- });
-
- }
-}
-
-private static void printResponse(PlcReadResponse response) {
- for (String fieldName : response.getFieldNames()) {
- if(response.getResponseCode(fieldName) == PlcResponseCode.OK) {
- int numValues = response.getNumberOfValues(fieldName);
- // If it's just one element, output just one single line.
- if(numValues == 1) {
- System.out.println("Value[" + fieldName + "]: " + response.getObject(fieldName));
- }
- // If it's more than one element, output each in a single row.
- else {
- System.out.println("Value[" + fieldName + "]:");
- for(int i = 0; i < numValues; i++) {
- System.out.println(" - " + response.getObject(fieldName, i));
- }
- }
- }
- // Something went wrong, to output an error message instead.
- else {
- System.out.println("Error[" + fieldName + "]: " + response.getResponseCode(fieldName).name());
- }
- }
-}
-
-}
diff --git a/examples/hello-world-plc4x/pom.xml b/examples/hello-world-plc4x/pom.xml
index de841c2..0fdff06 100644
--- a/examples/hello-world-plc4x/pom.xml
+++ b/examples/hello-world-plc4x/pom.xml
@@ -62,6 +62,11 @@
</dependency>
<dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>1.4</version>
+ </dependency>
+ <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
diff --git a/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/CliOptions.java b/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/CliOptions.java
new file mode 100644
index 0000000..7efbda4
--- /dev/null
+++ b/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/CliOptions.java
@@ -0,0 +1,78 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+
+package org.apache.plc4x.java.examples.helloplc4x;
+
+import org.apache.commons.cli.*;
+
+public class CliOptions {
+
+ private final String connectionString;
+ private final String[] fieldAddress;
+
+ /** Construct an MqttExampleOptions class from command line flags. */
+ public static CliOptions fromFlags(String[] args) {
+ org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();
+ // Required arguments
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("connection-string")
+ .hasArg()
+ .desc("Connection String")
+ .required()
+ .build());
+ options.addOption(
+ Option.builder()
+ .type(String.class)
+ .longOpt("field-addresses")
+ .hasArg()
+ .desc("Field Addresses (Space separated).")
+ .required()
+ .build());
+
+ CommandLineParser parser = new DefaultParser();
+ CommandLine commandLine;
+ try {
+ commandLine = parser.parse(options, args);
+
+ String connectionString = commandLine.getOptionValue("connection-string");
+ String[] fieldAddress = commandLine.getOptionValues("field-addresses");
+
+ return new CliOptions(connectionString, fieldAddress);
+ } catch (ParseException e) {
+ System.err.println(e.getMessage());
+ return null;
+ }
+ }
+
+ public CliOptions(String connectionString, String[] fieldAddress) {
+ this.connectionString = connectionString;
+ this.fieldAddress = fieldAddress;
+ }
+
+ public String getConnectionString() {
+ return connectionString;
+ }
+
+ public String[] getFieldAddress() {
+ return fieldAddress;
+ }
+
+}
diff --git a/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java b/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java
index 6fedf8b..47fa44d 100644
--- a/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java
+++ b/examples/hello-world-plc4x/src/main/java/org/apache/plc4x/java/examples/helloplc4x/HelloPlc4x.java
@@ -38,14 +38,14 @@ public class HelloPlc4x {
* @param args ignored.
*/
public static void main(String[] args) throws Exception {
- if (args.length < 2) {
- logger.info("Usage: HelloPlc4x {connection-string} {address-string}+");
- logger.info("Example: HelloPlc4x test:plc4x-example-mqtt RANDOM/foo:INTEGER RANDOM/bar:INTEGER");
- return;
+ CliOptions options = CliOptions.fromFlags(args);
+ if (options == null) {
+ // 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(args[0])) {
+ try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getConnectionString())) {
// Check if this connection support reading of data.
if (!plcConnection.getMetadata().canRead()) {
@@ -56,8 +56,8 @@ public class HelloPlc4x {
// Create a new read request:
// - Give the single item requested the alias name "value"
PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
- for (int i = 1; i < args.length; i++) {
- builder.addItem("value-" + i, args[i]);
+ for (int i = 0; i < options.getFieldAddress().length; i++) {
+ builder.addItem("value-" + i, options.getFieldAddress()[i]);
}
PlcReadRequest readRequest = builder.build();