use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class GenericCANDriver method getStackConfigurer.
@Override
protected ProtocolStackConfigurer<Message> getStackConfigurer(Transport transport) {
if (!(transport instanceof CANTransport)) {
throw new PlcRuntimeException("Generic CAN Driver requires CAN Transport instance");
}
CANTransport<Message> canTransport = (CANTransport<Message>) transport;
return CustomProtocolStackConfigurer.builder(canTransport.getMessageType(), canTransport::getMessageInput).withProtocol(cfg -> {
GenericCANProtocolLogic protocolLogic = new GenericCANProtocolLogic();
ConfigurationFactory.configure(cfg, protocolLogic);
return new CANDriverAdapter<>(protocolLogic, canTransport.getMessageType(), canTransport.adapter(), new GenericCANFrameDataHandler(canTransport::getTransportFrameBuilder));
}).withDriverContext(cfg -> new GenericCANDriverContext()).withPacketSizeEstimator(cfg -> canTransport.getEstimator()).littleEndian().build();
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class OpcuaProtocolLogic method subscribe.
@Override
public CompletableFuture<PlcSubscriptionResponse> subscribe(PlcSubscriptionRequest subscriptionRequest) {
return CompletableFuture.supplyAsync(() -> {
Map<String, ResponseItem<PlcSubscriptionHandle>> values = new HashMap<>();
long subscriptionId;
ArrayList<String> fields = new ArrayList<>(subscriptionRequest.getFieldNames());
long cycleTime = (subscriptionRequest.getField(fields.get(0))).getDuration().orElse(Duration.ofMillis(1000)).toMillis();
try {
CompletableFuture<CreateSubscriptionResponse> subscription = onSubscribeCreateSubscription(cycleTime);
CreateSubscriptionResponse response = subscription.get(SecureChannel.REQUEST_TIMEOUT_LONG, TimeUnit.MILLISECONDS);
subscriptionId = response.getSubscriptionId();
subscriptions.put(subscriptionId, new OpcuaSubscriptionHandle(context, this, channel, subscriptionRequest, subscriptionId, cycleTime));
} catch (Exception e) {
throw new PlcRuntimeException("Unable to subscribe because of: " + e.getMessage());
}
for (String fieldName : subscriptionRequest.getFieldNames()) {
final DefaultPlcSubscriptionField fieldDefaultPlcSubscription = (DefaultPlcSubscriptionField) subscriptionRequest.getField(fieldName);
if (!(fieldDefaultPlcSubscription.getPlcField() instanceof OpcuaField)) {
values.put(fieldName, new ResponseItem<>(PlcResponseCode.INVALID_ADDRESS, null));
} else {
values.put(fieldName, new ResponseItem<>(PlcResponseCode.OK, subscriptions.get(subscriptionId)));
}
}
return new DefaultPlcSubscriptionResponse(subscriptionRequest, values);
});
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class EncryptionHandler method encodeMessage.
public ReadBuffer encodeMessage(MessagePDU pdu, byte[] message) {
int PREENCRYPTED_BLOCK_LENGTH = 190;
int unencryptedLength = pdu.getLengthInBytes();
int openRequestLength = message.length;
int positionFirstBlock = unencryptedLength - openRequestLength - 8;
int paddingSize = PREENCRYPTED_BLOCK_LENGTH - ((openRequestLength + 256 + 1 + 8) % PREENCRYPTED_BLOCK_LENGTH);
int preEncryptedLength = openRequestLength + 256 + 1 + 8 + paddingSize;
if (preEncryptedLength % PREENCRYPTED_BLOCK_LENGTH != 0) {
throw new PlcRuntimeException("Pre encrypted block length " + preEncryptedLength + " isn't a multiple of the block size");
}
int numberOfBlocks = preEncryptedLength / PREENCRYPTED_BLOCK_LENGTH;
int encryptedLength = numberOfBlocks * 256 + positionFirstBlock;
WriteBufferByteBased buf = new WriteBufferByteBased(encryptedLength, ByteOrder.LITTLE_ENDIAN);
try {
new OpcuaAPU(pdu, false).serialize(buf);
byte paddingByte = (byte) paddingSize;
buf.writeByte(paddingByte);
for (int i = 0; i < paddingSize; i++) {
buf.writeByte(paddingByte);
}
// Writing Message Length
int tempPos = buf.getPos();
buf.setPos(4);
buf.writeInt(32, encryptedLength);
buf.setPos(tempPos);
byte[] signature = sign(getBytes(buf.getBytes(), 0, unencryptedLength + paddingSize + 1));
// Write the signature to the end of the buffer
for (byte b : signature) {
buf.writeByte(b);
}
buf.setPos(positionFirstBlock);
encryptBlock(buf, getBytes(buf.getBytes(), positionFirstBlock, positionFirstBlock + preEncryptedLength));
return new ReadBufferByteBased(buf.getData(), ByteOrder.LITTLE_ENDIAN);
} catch (SerializationException e) {
throw new PlcRuntimeException("Unable to parse apu prior to encrypting");
}
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class SecureChannel method isEndpoint.
/**
* Checks each component of the return endpoint description against the connection string.
* If all are correct then return true.
*
* @param endpoint - EndpointDescription returned from server
* @return true if this endpoint matches our configuration
* @throws PlcRuntimeException - If the returned endpoint string doesn't match the format expected
*/
private boolean isEndpoint(EndpointDescription endpoint) throws PlcRuntimeException {
// Split up the connection string into it's individual segments.
Matcher matcher = URI_PATTERN.matcher(endpoint.getEndpointUrl().getStringValue());
if (!matcher.matches()) {
throw new PlcRuntimeException("Endpoint returned from the server doesn't match the format '{protocol-code}:({transport-code})?//{transport-host}(:{transport-port})(/{transport-endpoint})'");
}
LOGGER.trace("Using Endpoint {} {} {}", matcher.group("transportHost"), matcher.group("transportPort"), matcher.group("transportEndpoint"));
if (this.configuration.isDiscovery() && !this.endpoints.contains(matcher.group("transportHost"))) {
return false;
}
if (!this.configuration.getPort().equals(matcher.group("transportPort"))) {
return false;
}
if (!this.configuration.getTransportEndpoint().equals(matcher.group("transportEndpoint"))) {
return false;
}
if (!this.configuration.isDiscovery()) {
this.configuration.setHost(matcher.group("transportHost"));
}
return true;
}
use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.
the class StaticHelper method parseS7String.
public static String parseS7String(ReadBuffer io, int stringLength, String encoding) {
try {
if ("UTF-8".equalsIgnoreCase(encoding)) {
// This is the maximum number of bytes a string can be long.
short maxLength = io.readUnsignedShort(8);
// This is the total length of the string on the PLC (Not necessarily the number of characters read)
short totalStringLength = io.readUnsignedShort(8);
final byte[] byteArray = new byte[totalStringLength];
for (int i = 0; (i < stringLength) && io.hasMore(8); i++) {
final byte curByte = io.readByte();
if (i < totalStringLength) {
byteArray[i] = curByte;
} else {
// Gobble up the remaining data, which is not added to the string.
i++;
for (; (i < stringLength) && io.hasMore(8); i++) {
io.readByte();
}
break;
}
}
return new String(byteArray, StandardCharsets.UTF_8);
} else if ("UTF-16".equalsIgnoreCase(encoding)) {
// This is the maximum number of bytes a string can be long.
int maxLength = io.readUnsignedInt(16);
// This is the total length of the string on the PLC (Not necessarily the number of characters read)
int totalStringLength = io.readUnsignedInt(16);
final byte[] byteArray = new byte[totalStringLength * 2];
for (int i = 0; (i < stringLength) && io.hasMore(16); i++) {
final short curShort = io.readShort(16);
if (i < totalStringLength) {
byteArray[i * 2] = (byte) (curShort >>> 8);
byteArray[(i * 2) + 1] = (byte) (curShort & 0xFF);
} else {
// Gobble up the remaining data, which is not added to the string.
i++;
for (; (i < stringLength) && io.hasMore(16); i++) {
io.readShort(16);
}
break;
}
}
return new String(byteArray, StandardCharsets.UTF_16);
} else {
throw new PlcRuntimeException("Unsupported string encoding " + encoding);
}
} catch (ParseException e) {
throw new PlcRuntimeException("Error parsing string", e);
}
}
Aggregations