Search in sources :

Example 11 with PlcException

use of org.apache.plc4x.java.api.exceptions.PlcException 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 12 with PlcException

use of org.apache.plc4x.java.api.exceptions.PlcException in project plc4x by apache.

the class Plc4xServer method start.

public void start() throws PlcException {
    if (loopGroup != null) {
        return;
    }
    try {
        loopGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(loopGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel channel) {
                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast(new GeneratedProtocolMessageCodec<>(Plc4xMessage.class, Plc4xMessage::staticParse, ByteOrder.BIG_ENDIAN, null, new ByteLengthEstimator(), null));
                pipeline.addLast(new Plc4xServerAdapter());
            }
        }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.bind(Plc4xConstants.PLC4XTCPDEFAULTPORT).sync();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new PlcException(e);
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Plc4xMessage(org.apache.plc4x.java.plc4x.readwrite.Plc4xMessage) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) GeneratedProtocolMessageCodec(org.apache.plc4x.java.spi.connection.GeneratedProtocolMessageCodec) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Plc4xServerAdapter(org.apache.plc4x.java.tools.plc4xserver.protocol.Plc4xServerAdapter)

Aggregations

PlcException (org.apache.plc4x.java.api.exceptions.PlcException)12 CompletableFuture (java.util.concurrent.CompletableFuture)6 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)4 java.util (java.util)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 IOException (java.io.IOException)2 BigInteger (java.math.BigInteger)2 Duration (java.time.Duration)2 Instant (java.time.Instant)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ExecutorService (java.util.concurrent.ExecutorService)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 Consumer (java.util.function.Consumer)2 Collectors (java.util.stream.Collectors)2 IntStream (java.util.stream.IntStream)2 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)2 org.apache.plc4x.java.spi.generation (org.apache.plc4x.java.spi.generation)2 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1