Search in sources :

Example 1 with PlcFieldConfig

use of org.apache.plc4x.java.examples.connectivity.mqtt.model.PlcFieldConfig 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)

Aggregations

ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)1 JsonArray (com.google.gson.JsonArray)1 JsonObject (com.google.gson.JsonObject)1 MqttClient (com.hivemq.client.mqtt.MqttClient)1 MqttQos (com.hivemq.client.mqtt.datatypes.MqttQos)1 Mqtt3RxClient (com.hivemq.client.mqtt.mqtt3.Mqtt3RxClient)1 Mqtt3ConnAck (com.hivemq.client.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck)1 Mqtt3Publish (com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish)1 Mqtt3PublishResult (com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3PublishResult)1 Flowable (io.reactivex.Flowable)1 Single (io.reactivex.Single)1 File (java.io.File)1 IOException (java.io.IOException)1 UUID (java.util.UUID)1 TimeUnit (java.util.concurrent.TimeUnit)1 StringUtils (org.apache.commons.lang3.StringUtils)1 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)1 PlcConnection (org.apache.plc4x.java.api.PlcConnection)1 PlcException (org.apache.plc4x.java.api.exceptions.PlcException)1