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;
}
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);
}
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);
}
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;
}
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);
}
}
Aggregations