use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.
the class Plc4x2AdsProtocol method encode.
@Override
protected void encode(ChannelHandlerContext ctx, PlcRequestContainer<InternalPlcRequest, InternalPlcResponse> msg, List<Object> out) throws Exception {
LOGGER.trace("(<--OUT): {}, {}, {}", ctx, msg, out);
PlcRequest request = msg.getRequest();
if (request instanceof PlcReadRequest) {
encodeReadRequest(msg, out);
} else if (request instanceof PlcWriteRequest) {
encodeWriteRequest(msg, out);
} else if (request instanceof PlcProprietaryRequest) {
encodeProprietaryRequest(msg, out);
} else {
throw new PlcProtocolException("Unknown type " + request.getClass());
}
}
use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.
the class OpcuaPlcDriverTest method readVariables.
@Test
public void readVariables() throws Exception {
PlcConnection opcuaConnection = new PlcDriverManager().getConnection(tcpConnectionAddress);
assert opcuaConnection.isConnected();
PlcReadRequest.Builder builder = opcuaConnection.readRequestBuilder();
builder.addItem("Bool", BOOL_IDENTIFIER_READ_WRITE);
builder.addItem("Byte", BYTE_IDENTIFIER_READ_WRITE);
builder.addItem("Double", DOUBLE_IDENTIFIER_READ_WRITE);
builder.addItem("Float", FLOAT_IDENTIFIER_READ_WRITE);
builder.addItem("Int16", INT16_IDENTIFIER_READ_WRITE);
builder.addItem("Int32", INT32_IDENTIFIER_READ_WRITE);
builder.addItem("Int64", INT64_IDENTIFIER_READ_WRITE);
builder.addItem("Integer", INTEGER_IDENTIFIER_READ_WRITE);
builder.addItem("SByte", SBYTE_IDENTIFIER_READ_WRITE);
builder.addItem("String", STRING_IDENTIFIER_READ_WRITE);
builder.addItem("UInt16", UINT16_IDENTIFIER_READ_WRITE);
builder.addItem("UInt32", UINT32_IDENTIFIER_READ_WRITE);
builder.addItem("UInt64", UINT64_IDENTIFIER_READ_WRITE);
builder.addItem("UInteger", UINTEGER_IDENTIFIER_READ_WRITE);
builder.addItem("DoesNotExists", DOES_NOT_EXIST_IDENTIFIER_READ_WRITE);
PlcReadRequest request = builder.build();
PlcReadResponse response = request.execute().get();
assert response.getResponseCode("Bool").equals(PlcResponseCode.OK);
assert response.getResponseCode("Byte").equals(PlcResponseCode.OK);
assert response.getResponseCode("Double").equals(PlcResponseCode.OK);
assert response.getResponseCode("Float").equals(PlcResponseCode.OK);
assert response.getResponseCode("Int16").equals(PlcResponseCode.OK);
assert response.getResponseCode("Int32").equals(PlcResponseCode.OK);
assert response.getResponseCode("Int64").equals(PlcResponseCode.OK);
assert response.getResponseCode("Integer").equals(PlcResponseCode.OK);
assert response.getResponseCode("SByte").equals(PlcResponseCode.OK);
assert response.getResponseCode("String").equals(PlcResponseCode.OK);
assert response.getResponseCode("UInt16").equals(PlcResponseCode.OK);
assert response.getResponseCode("UInt32").equals(PlcResponseCode.OK);
assert response.getResponseCode("UInt64").equals(PlcResponseCode.OK);
assert response.getResponseCode("UInteger").equals(PlcResponseCode.OK);
assert response.getResponseCode("DoesNotExists").equals(PlcResponseCode.NOT_FOUND);
opcuaConnection.close();
assert !opcuaConnection.isConnected();
}
use of org.apache.plc4x.java.api.messages.PlcReadRequest in project plc4x by apache.
the class S7PlcToAzureIoTHubSample method main.
/**
* Example code do demonstrate sending events from an S7 device to Microsoft Azure IoT Hub
*
* @param args Expected: [plc4x connection string, plc4x field address, IoT-Hub connection string].
*/
public static void main(String[] args) throws Exception {
CliOptions options = CliOptions.fromArgs(args);
if (options == null) {
CliOptions.printHelp();
// Could not parse.
System.exit(1);
}
LOGGER.info("Connecting {}, {}, {}", options.getPlc4xConnectionString(), options.getPlc4xFieldAddress(), options.getIotHubConnectionString());
// Open both a connection to the remote PLC and the cloud service.
DeviceClient client = new DeviceClient(options.getIotHubConnectionString(), IotHubClientProtocol.MQTT);
try (PlcConnection plcConnection = new PlcDriverManager().getConnection(options.getPlc4xConnectionString())) {
LOGGER.info("Connected");
client.open(true);
// Prepare a read request.
PlcReadRequest request = plcConnection.readRequestBuilder().addItem(FIELD_NAME, options.getPlc4xFieldAddress()).build();
while (!Thread.currentThread().isInterrupted()) {
// Simulate telemetry.
PlcReadResponse response = request.execute().get();
response.getAllLongs(FIELD_NAME).forEach(longValue -> {
String result = Long.toBinaryString(longValue);
LOGGER.info("Outputs {}", result);
Message msg = new Message("{ \"bits\" : \"" + result + "\"}");
// Send the message.
client.sendEventAsync(msg, (sentMessage, clientException, callbackContext) -> {
if (clientException != null) {
LOGGER.info("Received exception: ", clientException);
} else {
LOGGER.info("Sent successfully");
}
}, msg);
});
// Wait a second.
TimeUnit.SECONDS.sleep(1);
}
} finally {
client.close();
}
}
use of org.apache.plc4x.java.api.messages.PlcReadRequest 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.messages.PlcReadRequest in project plc4x by apache.
the class HelloPlc4x method main.
/**
* Example code do demonstrate using PLC4X.
*
* @param args ignored.
*/
public static void main(String[] args) throws Exception {
CliOptions options = CliOptions.fromArgs(args);
if (options == null) {
CliOptions.printHelp();
// 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(options.getConnectionString())) {
// Check if this connection support reading of data.
if (!plcConnection.getMetadata().canRead()) {
logger.error("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 = 0; i < options.getFieldAddress().length; i++) {
builder.addItem("value-" + options.getFieldAddress()[i], options.getFieldAddress()[i]);
}
PlcReadRequest readRequest = builder.build();
// ////////////////////////////////////////////////////////
// Read synchronously ...
// NOTICE: the ".get()" immediately lets this thread pause until
// the response is processed and available.
logger.info("Synchronous request ...");
PlcReadResponse syncResponse = readRequest.execute().get();
// Simply iterating over the field names returned in the response.
printResponse(syncResponse);
/*PlcValue asPlcValue = syncResponse.getAsPlcValue();
System.out.println(asPlcValue.toString());*/
// ////////////////////////////////////////////////////////
// Read asynchronously ...
// Register a callback executed as soon as a response arrives.
/*logger.info("Asynchronous request ...");
CompletionStage<? extends PlcReadResponse> asyncResponse = readRequest.execute();
asyncResponse.whenComplete((readResponse, throwable) -> {
if (readResponse != null) {
printResponse(readResponse);
} else {
logger.error("An error occurred: " + throwable.getMessage(), throwable);
}
});*/
// Give the async request a little time...
TimeUnit.MILLISECONDS.sleep(1000);
plcConnection.close();
System.exit(0);
}
}
Aggregations