Search in sources :

Example 1 with DefaultPlcWriteResponse

use of org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse in project plc4x by apache.

the class CANOpenProtocolLogic method writeInternally.

private void writeInternally(DefaultPlcWriteRequest writeRequest, CANOpenPDOField field, CompletableFuture<PlcWriteResponse> response) {
    PlcValue writeValue = writeRequest.getPlcValues().get(0);
    try {
        String fieldName = writeRequest.getFieldNames().iterator().next();
        WriteBufferByteBased writeBuffer = new WriteBufferByteBased(DataItem.getLengthInBytes(writeValue, field.getCanOpenDataType(), writeValue.getLength()), ByteOrder.LITTLE_ENDIAN);
        DataItem.staticSerialize(writeBuffer, writeValue, field.getCanOpenDataType(), writeValue.getLength(), ByteOrder.LITTLE_ENDIAN);
        final CANOpenPDOPayload payload = new CANOpenPDOPayload(new CANOpenPDO(writeBuffer.getData()));
        context.sendToWire(new CANOpenFrame((short) field.getNodeId(), field.getService(), payload));
        response.complete(new DefaultPlcWriteResponse(writeRequest, Collections.singletonMap(fieldName, PlcResponseCode.OK)));
    } catch (Exception e) {
        response.completeExceptionally(e);
    }
}
Also used : PlcValue(org.apache.plc4x.java.api.value.PlcValue) CANOpenPDO(org.apache.plc4x.java.canopen.readwrite.CANOpenPDO) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) CANOpenPDOPayload(org.apache.plc4x.java.canopen.readwrite.CANOpenPDOPayload) CANOpenAbortException(org.apache.plc4x.java.canopen.transport.CANOpenAbortException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) CANOpenFrame(org.apache.plc4x.java.canopen.readwrite.CANOpenFrame)

Example 2 with DefaultPlcWriteResponse

use of org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse 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 3 with DefaultPlcWriteResponse

use of org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse in project plc4x by apache.

the class PlcEntityManagerComplexTest method getPlcEntityManager.

private PlcEntityManager getPlcEntityManager(final Map<String, PlcValue> responses) throws PlcConnectionException {
    driverManager = Mockito.mock(PlcDriverManager.class);
    PlcDriverManager mock = driverManager;
    PlcConnection connection = Mockito.mock(PlcConnection.class);
    when(mock.getConnection(ArgumentMatchers.anyString())).thenReturn(connection);
    when(connection.getMetadata()).thenReturn(new PlcConnectionMetadata() {

        @Override
        public boolean canRead() {
            return true;
        }

        @Override
        public boolean canWrite() {
            return true;
        }

        @Override
        public boolean canSubscribe() {
            return true;
        }
    });
    PlcReader reader = readRequest -> {
        Map<String, ResponseItem<PlcValue>> map = readRequest.getFieldNames().stream().collect(Collectors.toMap(Function.identity(), s -> new ResponseItem<>(PlcResponseCode.OK, Objects.requireNonNull(responses.get(s), s + " not found"))));
        return CompletableFuture.completedFuture(new DefaultPlcReadResponse(readRequest, map));
    };
    when(connection.readRequestBuilder()).then(invocation -> new DefaultPlcReadRequest.Builder(reader, getFieldHandler()));
    PlcWriter writer = writeRequest -> {
        Map<String, PlcResponseCode> map = writeRequest.getFieldNames().stream().collect(Collectors.toMap(Function.identity(), s -> PlcResponseCode.OK));
        return CompletableFuture.completedFuture(new DefaultPlcWriteResponse(writeRequest, map));
    };
    when(connection.writeRequestBuilder()).then(invocation -> new DefaultPlcWriteRequest.Builder(writer, getFieldHandler(), getValueHandler()));
    return new PlcEntityManager(mock);
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) org.apache.plc4x.java.api.value(org.apache.plc4x.java.api.value) Arrays(java.util.Arrays) ArgumentMatchers(org.mockito.ArgumentMatchers) PlcConnection(org.apache.plc4x.java.api.PlcConnection) LocalDateTime(java.time.LocalDateTime) WithAssertions(org.assertj.core.api.WithAssertions) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Disabled(org.junit.jupiter.api.Disabled) Function(java.util.function.Function) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) PlcFieldHandler(org.apache.plc4x.java.spi.connection.PlcFieldHandler) PlcInvalidFieldException(org.apache.plc4x.java.api.exceptions.PlcInvalidFieldException) PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) BigDecimal(java.math.BigDecimal) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) LocalTime(java.time.LocalTime) FieldUtils(org.apache.commons.lang3.reflect.FieldUtils) BigInteger(java.math.BigInteger) PlcLINT(org.apache.plc4x.java.spi.values.PlcLINT) PlcConnectionMetadata(org.apache.plc4x.java.api.metadata.PlcConnectionMetadata) PlcReader(org.apache.plc4x.java.spi.messages.PlcReader) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) IEC61131ValueHandler(org.apache.plc4x.java.spi.values.IEC61131ValueHandler) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) Mockito(org.mockito.Mockito) PlcWriter(org.apache.plc4x.java.spi.messages.PlcWriter) LocalDate(java.time.LocalDate) Assertions(org.junit.jupiter.api.Assertions) DefaultPlcWriteRequest(org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest) DefaultPlcReadRequest(org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem) PlcWriter(org.apache.plc4x.java.spi.messages.PlcWriter) DefaultPlcWriteRequest(org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest) PlcConnection(org.apache.plc4x.java.api.PlcConnection) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) PlcConnectionMetadata(org.apache.plc4x.java.api.metadata.PlcConnectionMetadata) DefaultPlcReadRequest(org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) HashMap(java.util.HashMap) Map(java.util.Map) PlcReader(org.apache.plc4x.java.spi.messages.PlcReader)

Example 4 with DefaultPlcWriteResponse

use of org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse in project plc4x by apache.

the class BaseOptimizer method processWriteResponses.

protected PlcWriteResponse processWriteResponses(PlcWriteRequest writeRequest, Map<PlcRequest, Either<PlcResponse, Exception>> writeResponses) {
    Map<String, PlcResponseCode> fields = new HashMap<>();
    for (Map.Entry<PlcRequest, Either<PlcResponse, Exception>> requestsEntries : writeResponses.entrySet()) {
        PlcWriteRequest subWriteRequest = (PlcWriteRequest) requestsEntries.getKey();
        Either<PlcResponse, Exception> writeResponse = requestsEntries.getValue();
        for (String fieldName : subWriteRequest.getFieldNames()) {
            if (writeResponse.isLeft()) {
                PlcWriteResponse subWriteResponse = (PlcWriteResponse) writeResponse.getLeft();
                fields.put(fieldName, subWriteResponse.getResponseCode(fieldName));
            } else {
                fields.put(fieldName, PlcResponseCode.INTERNAL_ERROR);
            }
        }
    }
    return new DefaultPlcWriteResponse(writeRequest, fields);
}
Also used : DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) Either(io.vavr.control.Either)

Example 5 with DefaultPlcWriteResponse

use of org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse in project plc4x by apache.

the class Plc4xProtocolLogic method write.

@Override
public CompletableFuture<PlcWriteResponse> write(PlcWriteRequest writeRequest) {
    CompletableFuture<PlcWriteResponse> future = new CompletableFuture<>();
    // Prepare the request.
    List<Plc4xFieldValueRequest> fields = new ArrayList<>(writeRequest.getNumberOfFields());
    for (String fieldName : writeRequest.getFieldNames()) {
        final org.apache.plc4x.java.plc4x.field.Plc4xField plc4xField = (org.apache.plc4x.java.plc4x.field.Plc4xField) writeRequest.getField(fieldName);
        final Plc4xValueType plc4xValueType = plc4xField.getValueType();
        final PlcValue plcValue = writeRequest.getPlcValue(fieldName);
        Plc4xFieldValueRequest fieldRequest = new Plc4xFieldValueRequest(new Plc4xField(fieldName, plc4xField.getAddress() + ":" + plc4xField.getPlcDataType()), plc4xValueType, plcValue);
        fields.add(fieldRequest);
    }
    final int requestId = txIdGenerator.getAndIncrement();
    Plc4xWriteRequest write = new Plc4xWriteRequest(requestId, connectionId, fields);
    // Send the request and await a response.
    RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
    context.sendRequest(write).expectResponse(Plc4xMessage.class, requestTimeout).onTimeout(future::completeExceptionally).check(p -> p.getRequestId() == requestId).unwrap(plc4xMessage -> (Plc4xWriteResponse) plc4xMessage).check(plc4xReadResponse -> plc4xReadResponse.getConnectionId() == connectionId).handle(plc4xWriteResponse -> {
        Map<String, PlcResponseCode> apiResponses = new HashMap<>();
        // Create the API response from the incoming message.
        for (Plc4xFieldResponse plc4xField : plc4xWriteResponse.getFields()) {
            final Plc4xResponseCode plc4xResponseCode = plc4xField.getResponseCode();
            final PlcResponseCode apiResponseCode = PlcResponseCode.valueOf(plc4xResponseCode.name());
            apiResponses.put(plc4xField.getField().getName(), apiResponseCode);
        }
        // Send it back to the calling process.
        future.complete(new DefaultPlcWriteResponse(writeRequest, apiResponses));
        // Finish the request-transaction.
        transaction.endRequest();
    });
    return future;
}
Also used : Logger(org.slf4j.Logger) Plc4xConfiguration(org.apache.plc4x.java.plc4x.config.Plc4xConfiguration) LoggerFactory(org.slf4j.LoggerFactory) PlcValue(org.apache.plc4x.java.api.value.PlcValue) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) ArrayList(java.util.ArrayList) org.apache.plc4x.java.plc4x.readwrite(org.apache.plc4x.java.plc4x.readwrite) HasConfiguration(org.apache.plc4x.java.spi.configuration.HasConfiguration) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) RequestTransactionManager(org.apache.plc4x.java.spi.transaction.RequestTransactionManager) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConversationContext(org.apache.plc4x.java.spi.ConversationContext) Duration(java.time.Duration) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) Plc4xProtocolBase(org.apache.plc4x.java.spi.Plc4xProtocolBase) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem) org.apache.plc4x.java.api.messages(org.apache.plc4x.java.api.messages) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) RequestTransactionManager(org.apache.plc4x.java.spi.transaction.RequestTransactionManager) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) PlcValue(org.apache.plc4x.java.api.value.PlcValue)

Aggregations

DefaultPlcWriteResponse (org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse)8 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)7 CompletableFuture (java.util.concurrent.CompletableFuture)4 PlcValue (org.apache.plc4x.java.api.value.PlcValue)4 HashMap (java.util.HashMap)3 DefaultPlcReadResponse (org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse)3 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)3 Duration (java.time.Duration)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Map (java.util.Map)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)2 org.apache.plc4x.java.api.messages (org.apache.plc4x.java.api.messages)2 org.apache.plc4x.java.api.value (org.apache.plc4x.java.api.value)2 DefaultPlcReadRequest (org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest)2 DefaultPlcWriteRequest (org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest)2 RequestTransactionManager (org.apache.plc4x.java.spi.transaction.RequestTransactionManager)2 Either (io.vavr.control.Either)1