Search in sources :

Example 26 with PlcRuntimeException

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();
}
Also used : GeneratedDriverBase(org.apache.plc4x.java.spi.connection.GeneratedDriverBase) Configuration(org.apache.plc4x.java.spi.configuration.Configuration) CANTransport(org.apache.plc4x.java.transport.can.CANTransport) CANDriverAdapter(org.apache.plc4x.java.can.adapter.CANDriverAdapter) GenericCANFrameDataHandler(org.apache.plc4x.java.can.generic.transport.GenericCANFrameDataHandler) GenericCANDriverContext(org.apache.plc4x.java.can.generic.context.GenericCANDriverContext) PlcValueHandler(org.apache.plc4x.java.api.value.PlcValueHandler) Message(org.apache.plc4x.java.spi.generation.Message) IEC61131ValueHandler(org.apache.plc4x.java.spi.values.IEC61131ValueHandler) GenericCANProtocolLogic(org.apache.plc4x.java.can.generic.protocol.GenericCANProtocolLogic) GenericCANConfiguration(org.apache.plc4x.java.can.generic.configuration.GenericCANConfiguration) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) ConfigurationFactory(org.apache.plc4x.java.spi.configuration.ConfigurationFactory) CustomProtocolStackConfigurer(org.apache.plc4x.java.spi.connection.CustomProtocolStackConfigurer) ProtocolStackConfigurer(org.apache.plc4x.java.spi.connection.ProtocolStackConfigurer) BaseOptimizer(org.apache.plc4x.java.spi.optimizer.BaseOptimizer) GenericCANFieldHandler(org.apache.plc4x.java.can.generic.field.GenericCANFieldHandler) Transport(org.apache.plc4x.java.spi.transport.Transport) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) Message(org.apache.plc4x.java.spi.generation.Message) GenericCANDriverContext(org.apache.plc4x.java.can.generic.context.GenericCANDriverContext) CANDriverAdapter(org.apache.plc4x.java.can.adapter.CANDriverAdapter) GenericCANProtocolLogic(org.apache.plc4x.java.can.generic.protocol.GenericCANProtocolLogic) CANTransport(org.apache.plc4x.java.transport.can.CANTransport) GenericCANFrameDataHandler(org.apache.plc4x.java.can.generic.transport.GenericCANFrameDataHandler)

Example 27 with PlcRuntimeException

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);
    });
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) TimeoutException(java.util.concurrent.TimeoutException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) DefaultPlcSubscriptionField(org.apache.plc4x.java.spi.model.DefaultPlcSubscriptionField) OpcuaField(org.apache.plc4x.java.opcua.field.OpcuaField) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem)

Example 28 with PlcRuntimeException

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");
    }
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) OpcuaAPU(org.apache.plc4x.java.opcua.readwrite.OpcuaAPU)

Example 29 with PlcRuntimeException

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;
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) Matcher(java.util.regex.Matcher)

Example 30 with PlcRuntimeException

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);
    }
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) ParseException(org.apache.plc4x.java.spi.generation.ParseException)

Aggregations

PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)95 BigInteger (java.math.BigInteger)17 CompletableFuture (java.util.concurrent.CompletableFuture)14 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)14 PlcValue (org.apache.plc4x.java.api.value.PlcValue)14 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)14 Duration (java.time.Duration)13 PlcField (org.apache.plc4x.java.api.model.PlcField)13 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)10 HasConfiguration (org.apache.plc4x.java.spi.configuration.HasConfiguration)10 ParseException (org.apache.plc4x.java.spi.generation.ParseException)10 RequestTransactionManager (org.apache.plc4x.java.spi.transaction.RequestTransactionManager)10 Collections (java.util.Collections)9 DefaultPlcReadRequest (org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest)9 DefaultPlcWriteRequest (org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest)9 IOException (java.io.IOException)8 org.apache.plc4x.java.modbus.readwrite (org.apache.plc4x.java.modbus.readwrite)8 DefaultPlcReadResponse (org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse)8 ModbusField (org.apache.plc4x.java.modbus.base.field.ModbusField)7 PlcList (org.apache.plc4x.java.spi.values.PlcList)7