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);
}
}
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);
}
}
Aggregations