Search in sources :

Example 1 with PlcResponseCode

use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.

the class EipProtocolLogic method decodeWriteResponse.

private PlcResponse decodeWriteResponse(CipService p, PlcWriteRequest writeRequest) {
    Map<String, PlcResponseCode> responses = new HashMap<>();
    if (p instanceof CipWriteResponse) {
        CipWriteResponse resp = (CipWriteResponse) p;
        String fieldName = writeRequest.getFieldNames().iterator().next();
        EipField field = (EipField) writeRequest.getField(fieldName);
        responses.put(fieldName, decodeResponseCode(resp.getStatus()));
        return new DefaultPlcWriteResponse(writeRequest, responses);
    } else if (p instanceof MultipleServiceResponse) {
        MultipleServiceResponse resp = (MultipleServiceResponse) p;
        int nb = resp.getServiceNb();
        List<CipService> arr = new ArrayList<>(nb);
        ReadBufferByteBased read = new ReadBufferByteBased(resp.getServicesData());
        int total = (int) read.getTotalBytes();
        for (int i = 0; i < nb; i++) {
            int length = 0;
            int offset = resp.getOffsets().get(i);
            if (offset == nb - 1) {
                // Get the rest if last
                length = total - offset;
            } else {
                // Calculate length with offsets
                length = resp.getOffsets().get(i + 1) - offset;
            }
            ReadBuffer serviceBuf = new ReadBufferByteBased(read.getBytes(offset, length), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
            CipService service = null;
            try {
                service = CipService.staticParse(read, length);
                arr.add(service);
            } catch (ParseException e) {
                throw new PlcRuntimeException(e);
            }
        }
        Services services = new Services(nb, resp.getOffsets(), arr, -1);
        Iterator<String> it = writeRequest.getFieldNames().iterator();
        for (int i = 0; i < nb && it.hasNext(); i++) {
            String fieldName = it.next();
            EipField field = (EipField) writeRequest.getField(fieldName);
            PlcValue plcValue = null;
            if (services.getServices().get(i) instanceof CipWriteResponse) {
                CipWriteResponse writeResponse = (CipWriteResponse) services.getServices().get(i);
                PlcResponseCode code = decodeResponseCode(writeResponse.getStatus());
                responses.put(fieldName, code);
            }
        }
        return new DefaultPlcWriteResponse(writeRequest, responses);
    }
    return null;
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) EipField(org.apache.plc4x.java.eip.readwrite.field.EipField) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) ReadBuffer(org.apache.plc4x.java.spi.generation.ReadBuffer) ReadBufferByteBased(org.apache.plc4x.java.spi.generation.ReadBufferByteBased) ParseException(org.apache.plc4x.java.spi.generation.ParseException)

Example 2 with PlcResponseCode

use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.

the class Plc4x2AdsProtocol method decodeReadResponse.

@SuppressWarnings("unchecked")
private InternalPlcResponse decodeReadResponse(AdsReadResponse responseMessage, PlcRequestContainer<InternalPlcRequest, InternalPlcResponse> requestContainer) {
    InternalPlcReadRequest plcReadRequest = (InternalPlcReadRequest) requestContainer.getRequest();
    // TODO: only single requests supported for now
    AdsField field = (AdsField) plcReadRequest.getFields().get(0);
    PlcResponseCode responseCode = decodeResponseCode(responseMessage.getResult());
    byte[] bytes = responseMessage.getData().getBytes();
    PlcValue value = decodeData(field.getAdsDataType(), bytes);
    // TODO: does every item has the same ads response or is this whole aggregation broken?
    Map<String, Pair<PlcResponseCode, PlcValue>> responseItems = plcReadRequest.getFieldNames().stream().collect(Collectors.toMap(fieldName -> fieldName, ignore -> Pair.of(responseCode, value)));
    return new DefaultPlcReadResponse(plcReadRequest, responseItems);
}
Also used : DirectAdsField(org.apache.plc4x.java.ads.model.DirectAdsField) PlcIoException(org.apache.plc4x.java.api.exceptions.PlcIoException) PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) PlcRequest(org.apache.plc4x.java.api.messages.PlcRequest) LoggerFactory(org.slf4j.LoggerFactory) PlcValue(org.apache.plc4x.java.api.value.PlcValue) ConcurrentMap(java.util.concurrent.ConcurrentMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AdsException(org.apache.plc4x.java.ads.protocol.exception.AdsException) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) LittleEndianEncoder.encodeData(org.apache.plc4x.java.ads.protocol.util.LittleEndianEncoder.encodeData) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) org.apache.plc4x.java.ads.api.commands(org.apache.plc4x.java.ads.api.commands) PlcList(org.apache.plc4x.java.api.value.PlcList) LinkedList(java.util.LinkedList) AdsDataType(org.apache.plc4x.java.ads.model.AdsDataType) Invoke(org.apache.plc4x.java.ads.api.generic.types.Invoke) PlcProtocolException(org.apache.plc4x.java.api.exceptions.PlcProtocolException) AmsPacket(org.apache.plc4x.java.ads.api.generic.AmsPacket) Logger(org.slf4j.Logger) AmsNetId(org.apache.plc4x.java.ads.api.generic.types.AmsNetId) PlcProtocolPayloadTooBigException(org.apache.plc4x.java.api.exceptions.PlcProtocolPayloadTooBigException) org.apache.plc4x.java.ads.api.commands.types(org.apache.plc4x.java.ads.api.commands.types) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) org.apache.plc4x.java.spi.messages(org.apache.plc4x.java.spi.messages) SymbolicAdsField(org.apache.plc4x.java.ads.model.SymbolicAdsField) Collectors(java.util.stream.Collectors) PlcField(org.apache.plc4x.java.api.model.PlcField) MessageToMessageCodec(io.netty.handler.codec.MessageToMessageCodec) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) AmsPort(org.apache.plc4x.java.ads.api.generic.types.AmsPort) AdsField(org.apache.plc4x.java.ads.model.AdsField) PlcValue(org.apache.plc4x.java.api.value.PlcValue) DirectAdsField(org.apache.plc4x.java.ads.model.DirectAdsField) SymbolicAdsField(org.apache.plc4x.java.ads.model.SymbolicAdsField) AdsField(org.apache.plc4x.java.ads.model.AdsField) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) Pair(org.apache.commons.lang3.tuple.Pair)

Example 3 with PlcResponseCode

use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.

the class Plc4x2AdsProtocol method decodeWriteResponse.

@SuppressWarnings("unchecked")
private InternalPlcResponse decodeWriteResponse(AdsWriteResponse responseMessage, PlcRequestContainer<InternalPlcRequest, InternalPlcResponse> requestContainer) {
    InternalPlcWriteRequest plcWriteRequest = (InternalPlcWriteRequest) requestContainer.getRequest();
    PlcResponseCode responseCode = decodeResponseCode(responseMessage.getResult());
    // TODO: does every item has the same ads response or is this whole aggregation broken?
    Map<String, PlcResponseCode> responseItems = plcWriteRequest.getFieldNames().stream().collect(Collectors.toMap(fieldName -> fieldName, ignore -> responseCode));
    return new DefaultPlcWriteResponse(plcWriteRequest, responseItems);
}
Also used : DirectAdsField(org.apache.plc4x.java.ads.model.DirectAdsField) PlcIoException(org.apache.plc4x.java.api.exceptions.PlcIoException) PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) PlcRequest(org.apache.plc4x.java.api.messages.PlcRequest) LoggerFactory(org.slf4j.LoggerFactory) PlcValue(org.apache.plc4x.java.api.value.PlcValue) ConcurrentMap(java.util.concurrent.ConcurrentMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AdsException(org.apache.plc4x.java.ads.protocol.exception.AdsException) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) LittleEndianEncoder.encodeData(org.apache.plc4x.java.ads.protocol.util.LittleEndianEncoder.encodeData) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) org.apache.plc4x.java.ads.api.commands(org.apache.plc4x.java.ads.api.commands) PlcList(org.apache.plc4x.java.api.value.PlcList) LinkedList(java.util.LinkedList) AdsDataType(org.apache.plc4x.java.ads.model.AdsDataType) Invoke(org.apache.plc4x.java.ads.api.generic.types.Invoke) PlcProtocolException(org.apache.plc4x.java.api.exceptions.PlcProtocolException) AmsPacket(org.apache.plc4x.java.ads.api.generic.AmsPacket) Logger(org.slf4j.Logger) AmsNetId(org.apache.plc4x.java.ads.api.generic.types.AmsNetId) PlcProtocolPayloadTooBigException(org.apache.plc4x.java.api.exceptions.PlcProtocolPayloadTooBigException) org.apache.plc4x.java.ads.api.commands.types(org.apache.plc4x.java.ads.api.commands.types) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) org.apache.plc4x.java.spi.messages(org.apache.plc4x.java.spi.messages) SymbolicAdsField(org.apache.plc4x.java.ads.model.SymbolicAdsField) Collectors(java.util.stream.Collectors) PlcField(org.apache.plc4x.java.api.model.PlcField) MessageToMessageCodec(io.netty.handler.codec.MessageToMessageCodec) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) AmsPort(org.apache.plc4x.java.ads.api.generic.types.AmsPort) AdsField(org.apache.plc4x.java.ads.model.AdsField) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode)

Example 4 with PlcResponseCode

use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.

the class ModbusProtocolLogic method write.

@Override
public CompletableFuture<PlcWriteResponse> write(PlcWriteRequest writeRequest) {
    CompletableFuture<PlcWriteResponse> future = new CompletableFuture<>();
    DefaultPlcWriteRequest request = (DefaultPlcWriteRequest) writeRequest;
    // 2. Split up into multiple sub-requests
    if (request.getFieldNames().size() == 1) {
        String fieldName = request.getFieldNames().iterator().next();
        PlcField field = request.getField(fieldName);
        final ModbusPDU requestPdu = getWriteRequestPdu(field, writeRequest.getPlcValue(fieldName));
        int transactionIdentifier = transactionIdentifierGenerator.getAndIncrement();
        // If we've reached the max value for a 16 bit transaction identifier, reset back to 1
        if (transactionIdentifierGenerator.get() == 0xFFFF) {
            transactionIdentifierGenerator.set(1);
        }
        ModbusTcpADU modbusTcpADU = new ModbusTcpADU(transactionIdentifier, unitIdentifier, requestPdu, false);
        RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
        transaction.submit(() -> context.sendRequest(modbusTcpADU).expectResponse(ModbusTcpADU.class, requestTimeout).onTimeout(future::completeExceptionally).onError((p, e) -> future.completeExceptionally(e)).check(p -> p.getTransactionIdentifier() == transactionIdentifier).unwrap(ModbusTcpADU::getPdu).handle(responsePdu -> {
            // Try to decode the response data based on the corresponding request.
            PlcResponseCode responseCode;
            // Check if the response was an error response.
            if (responsePdu instanceof ModbusPDUError) {
                ModbusPDUError errorResponse = (ModbusPDUError) responsePdu;
                responseCode = getErrorCode(errorResponse);
            } else {
                responseCode = PlcResponseCode.OK;
                // TODO: Check the correct number of elements were written.
                if (responsePdu instanceof ModbusPDUWriteSingleCoilResponse) {
                    ModbusPDUWriteSingleCoilResponse response = (ModbusPDUWriteSingleCoilResponse) responsePdu;
                    ModbusPDUWriteSingleCoilRequest requestSingleCoil = (ModbusPDUWriteSingleCoilRequest) requestPdu;
                    if (!((response.getValue() == requestSingleCoil.getValue()) && (response.getAddress() == requestSingleCoil.getAddress()))) {
                        responseCode = PlcResponseCode.REMOTE_ERROR;
                    }
                }
            }
            // Prepare the response.
            PlcWriteResponse response = new DefaultPlcWriteResponse(request, Collections.singletonMap(fieldName, responseCode));
            // Pass the response back to the application.
            future.complete(response);
            // Finish the request-transaction.
            transaction.endRequest();
        }));
    } else {
        future.completeExceptionally(new PlcRuntimeException("Modbus only supports single filed requests"));
    }
    return future;
}
Also used : org.apache.plc4x.java.api.value(org.apache.plc4x.java.api.value) PlcList(org.apache.plc4x.java.spi.values.PlcList) Arrays(java.util.Arrays) ArrayUtils(org.apache.commons.lang3.ArrayUtils) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) ArrayList(java.util.ArrayList) ModbusFieldDiscreteInput(org.apache.plc4x.java.modbus.field.ModbusFieldDiscreteInput) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) RequestTransactionManager(org.apache.plc4x.java.spi.transaction.RequestTransactionManager) ModbusField(org.apache.plc4x.java.modbus.field.ModbusField) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ModbusFieldCoil(org.apache.plc4x.java.modbus.field.ModbusFieldCoil) ConversationContext(org.apache.plc4x.java.spi.ConversationContext) Duration(java.time.Duration) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) Plc4xProtocolBase(org.apache.plc4x.java.spi.Plc4xProtocolBase) ModbusFieldInputRegister(org.apache.plc4x.java.modbus.field.ModbusFieldInputRegister) ModbusExtendedRegister(org.apache.plc4x.java.modbus.field.ModbusExtendedRegister) org.apache.plc4x.java.modbus.readwrite(org.apache.plc4x.java.modbus.readwrite) ModbusConfiguration(org.apache.plc4x.java.modbus.config.ModbusConfiguration) PlcField(org.apache.plc4x.java.api.model.PlcField) HasConfiguration(org.apache.plc4x.java.spi.configuration.HasConfiguration) org.apache.plc4x.java.spi.generation(org.apache.plc4x.java.spi.generation) List(java.util.List) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcBOOL(org.apache.plc4x.java.spi.values.PlcBOOL) ModbusFieldHoldingRegister(org.apache.plc4x.java.modbus.field.ModbusFieldHoldingRegister) DefaultPlcWriteRequest(org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest) DefaultPlcReadRequest(org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest) BitSet(java.util.BitSet) Collections(java.util.Collections) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem) org.apache.plc4x.java.api.messages(org.apache.plc4x.java.api.messages) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcField(org.apache.plc4x.java.api.model.PlcField) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) RequestTransactionManager(org.apache.plc4x.java.spi.transaction.RequestTransactionManager) DefaultPlcWriteRequest(org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse)

Example 5 with PlcResponseCode

use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.

the class HelloInflux method run.

public void run() {
    InfluxDBClient dbConnection = connectToDb();
    WriteApi writeApi = dbConnection.getWriteApi();
    try {
        PlcConnection plcConnection = connectToPlc();
        final PlcSubscriptionRequest subscriptionRequest = plcConnection.subscriptionRequestBuilder().addChangeOfStateField("query", configuration.getString("plc.query")).build();
        final PlcSubscriptionResponse subscriptionResponse = subscriptionRequest.execute().get(10, TimeUnit.SECONDS);
        subscriptionResponse.getSubscriptionHandle("query").register(plcSubscriptionEvent -> {
            DefaultPlcSubscriptionEvent internalEvent = (DefaultPlcSubscriptionEvent) plcSubscriptionEvent;
            final Point point = Point.measurement(configuration.getString("influx.measurement")).time(plcSubscriptionEvent.getTimestamp().toEpochMilli(), WritePrecision.MS);
            final Map<String, ResponseItem<PlcValue>> values = internalEvent.getValues();
            values.forEach((fieldName, fieldResponsePair) -> {
                final PlcResponseCode responseCode = fieldResponsePair.getCode();
                final PlcValue plcValue = fieldResponsePair.getValue();
                if (responseCode == PlcResponseCode.OK) {
                    PlcStruct structValue = (PlcStruct) plcValue;
                    for (String key : structValue.getKeys()) {
                        PlcValue subValue = structValue.getValue(key);
                        registerFields(point, key, subValue);
                    }
                }
            });
            writeApi.writePoint(configuration.getString("influx.bucket"), configuration.getString("influx.org"), point);
        });
    } catch (PlcException e) {
        logger.error("PLC Error", e);
    } catch (Exception e) {
        logger.error("General Error", e);
    }
}
Also used : InfluxDBClient(com.influxdb.client.InfluxDBClient) PlcSubscriptionRequest(org.apache.plc4x.java.api.messages.PlcSubscriptionRequest) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) Point(com.influxdb.client.write.Point) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ConfigurationException(org.apache.commons.configuration2.ex.ConfigurationException) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) WriteApi(com.influxdb.client.WriteApi) PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem)

Aggregations

PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)25 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)14 PlcValue (org.apache.plc4x.java.api.value.PlcValue)13 DefaultPlcReadResponse (org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse)10 CompletableFuture (java.util.concurrent.CompletableFuture)9 DefaultPlcWriteResponse (org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse)9 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)8 List (java.util.List)7 Map (java.util.Map)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 RequestTransactionManager (org.apache.plc4x.java.spi.transaction.RequestTransactionManager)6 PlcProtocolException (org.apache.plc4x.java.api.exceptions.PlcProtocolException)5 org.apache.plc4x.java.api.messages (org.apache.plc4x.java.api.messages)5 PlcField (org.apache.plc4x.java.api.model.PlcField)5 ConversationContext (org.apache.plc4x.java.spi.ConversationContext)5 Duration (java.time.Duration)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Consumer (java.util.function.Consumer)4