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 Plc4xAbEthProtocol method decodeReadResponse.
private PlcResponse decodeReadResponse(CIPEncapsulationReadResponse plcReadResponse, PlcRequestContainer requestContainer) {
PlcReadRequest plcReadRequest = (PlcReadRequest) requestContainer.getRequest();
Map<String, ResponseItem<PlcValue>> values = new HashMap<>();
for (String fieldName : plcReadRequest.getFieldNames()) {
AbEthField field = (AbEthField) plcReadRequest.getField(fieldName);
PlcResponseCode responseCode = decodeResponseCode(plcReadResponse.getResponse().getStatus());
PlcValue plcValue = null;
if (responseCode == PlcResponseCode.OK) {
try {
switch(field.getFileType()) {
case // output as single bytes
INTEGER:
if (plcReadResponse.getResponse() instanceof DF1CommandResponseMessageProtectedTypedLogicalRead) {
DF1CommandResponseMessageProtectedTypedLogicalRead df1PTLR = (DF1CommandResponseMessageProtectedTypedLogicalRead) plcReadResponse.getResponse();
List<Short> data = df1PTLR.getData();
if (data.size() == 1) {
plcValue = new PlcINT(data.get(0));
} else {
plcValue = IEC61131ValueHandler.of(data);
}
}
break;
case WORD:
if (plcReadResponse.getResponse() instanceof DF1CommandResponseMessageProtectedTypedLogicalRead) {
DF1CommandResponseMessageProtectedTypedLogicalRead df1PTLR = (DF1CommandResponseMessageProtectedTypedLogicalRead) plcReadResponse.getResponse();
List<Short> data = df1PTLR.getData();
if (((data.get(1) >> 7) & 1) == 0) {
// positive number
plcValue = IEC61131ValueHandler.of((data.get(1) << 8) + data.get(0));
} else {
// negative number
plcValue = IEC61131ValueHandler.of((((~data.get(1) & 0b01111111) << 8) + (~(data.get(0) - 1) & 0b11111111)) * -1);
}
}
break;
case DWORD:
if (plcReadResponse.getResponse() instanceof DF1CommandResponseMessageProtectedTypedLogicalRead) {
DF1CommandResponseMessageProtectedTypedLogicalRead df1PTLR = (DF1CommandResponseMessageProtectedTypedLogicalRead) plcReadResponse.getResponse();
List<Short> data = df1PTLR.getData();
if (((data.get(3) >> 7) & 1) == 0) {
// positive number
plcValue = IEC61131ValueHandler.of((data.get(3) << 24) + (data.get(2) << 16) + (data.get(1) << 8) + data.get(0));
} else {
// negative number
plcValue = IEC61131ValueHandler.of((((~data.get(3) & 0b01111111) << 24) + ((~(data.get(2) - 1) & 0b11111111) << 16) + ((~(data.get(1) - 1) & 0b11111111) << 8) + (~(data.get(0) - 1) & 0b11111111)) * -1);
}
}
break;
case SINGLEBIT:
if (plcReadResponse.getResponse() instanceof DF1CommandResponseMessageProtectedTypedLogicalRead) {
DF1CommandResponseMessageProtectedTypedLogicalRead df1PTLR = (DF1CommandResponseMessageProtectedTypedLogicalRead) plcReadResponse.getResponse();
List<Short> data = df1PTLR.getData();
if (field.getBitNumber() < 8) {
// read from first byte
plcValue = IEC61131ValueHandler.of((data.get(0) & (1 << field.getBitNumber())) != 0);
} else {
// read from second byte
plcValue = IEC61131ValueHandler.of((data.get(1) & (1 << (field.getBitNumber() - 8))) != 0);
}
}
break;
default:
logger.warn("Problem during decoding of field {}: Decoding of file type not implemented; " + "FieldInformation: {}", fieldName, field);
}
} catch (Exception e) {
logger.warn("Some other error occurred casting field {}, FieldInformation: {}", fieldName, field, e);
}
}
ResponseItem<PlcValue> result = new ResponseItem<>(responseCode, plcValue);
values.put(fieldName, result);
}
return new DefaultPlcReadResponse(plcReadRequest, values);
}
use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.
the class SDODownloadConversation method execute.
public void execute(CompletableFuture<PlcResponseCode> receiver) {
if (data.length > 4) {
// segmented
SDOInitiateSegmentedUploadResponse size = new SDOInitiateSegmentedUploadResponse(data.length, (byte) 0);
delegate.send(createFrame(new SDOInitiateDownloadRequest(false, true, indexAddress, size))).check(new NodeIdPredicate(answerNodeId)).onTimeout(receiver::completeExceptionally).onError((response, error) -> receiver.completeExceptionally(error)).unwrap(CANOpenFrame::getPayload).only(CANOpenSDOResponse.class).unwrap(CANOpenSDOResponse::getResponse).check(new TypeOrAbortPredicate<>(SDOInitiateDownloadResponse.class)).unwrap(payload -> unwrap(SDOInitiateDownloadResponse.class, payload)).handle(either -> {
if (either.isLeft()) {
receiver.completeExceptionally(new CANOpenAbortException("Could not initiate upload", either.getLeft().getCode()));
} else {
SDOInitiateDownloadResponse response = either.get();
if (response.getAddress().equals(indexAddress)) {
put(data, receiver, false, 0);
} else {
// TODO find proper error code in spec
SDOAbort abort = new SDOAbort(indexAddress, 1000);
delegate.sendToWire(createFrame(new SDOAbortRequest(abort)));
receiver.complete(PlcResponseCode.REMOTE_ERROR);
}
}
});
return;
}
// expedited
SDOInitiateDownloadRequest rq = new SDOInitiateDownloadRequest(true, true, indexAddress, new SDOInitiateExpeditedUploadResponse(data, (byte) 0));
delegate.send(createFrame(rq)).check(new NodeIdPredicate(answerNodeId)).onTimeout(receiver::completeExceptionally).unwrap(CANOpenFrame::getPayload).only(CANOpenSDOResponse.class).onError((response, error) -> onError(receiver, response, error)).unwrap(CANOpenSDOResponse::getResponse).check(new TypeOrAbortPredicate<>(SDOInitiateDownloadResponse.class)).unwrap(payload -> unwrap(SDOInitiateDownloadResponse.class, payload)).handle(either -> {
if (either.isLeft()) {
receiver.completeExceptionally(new CANOpenAbortException("Could not initiate upload", either.getLeft().getCode()));
} else {
SDOInitiateDownloadResponse response = either.get();
if (response.getCommand() == SDOResponseCommand.INITIATE_DOWNLOAD) {
receiver.complete(PlcResponseCode.OK);
} else {
receiver.complete(PlcResponseCode.REMOTE_ERROR);
}
}
});
}
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);
}
}
use of org.apache.plc4x.java.api.types.PlcResponseCode in project plc4x by apache.
the class ModbusRtuProtocolLogic method read.
@Override
public CompletableFuture<PlcReadResponse> read(PlcReadRequest readRequest) {
CompletableFuture<PlcReadResponse> future = new CompletableFuture<>();
DefaultPlcReadRequest request = (DefaultPlcReadRequest) readRequest;
// Example for sending a request ...
if (request.getFieldNames().size() == 1) {
String fieldName = request.getFieldNames().iterator().next();
ModbusField field = (ModbusField) request.getField(fieldName);
final ModbusPDU requestPdu = getReadRequestPdu(field);
ModbusRtuADU modbusRtuADU = new ModbusRtuADU(unitIdentifier, requestPdu, false);
RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
transaction.submit(() -> context.sendRequest(modbusRtuADU).expectResponse(ModbusRtuADU.class, requestTimeout).onTimeout(future::completeExceptionally).onError((p, e) -> future.completeExceptionally(e)).unwrap(ModbusRtuADU::getPdu).handle(responsePdu -> {
// Try to decode the response data based on the corresponding request.
PlcValue plcValue = null;
PlcResponseCode responseCode;
// Check if the response was an error response.
if (responsePdu instanceof ModbusPDUError) {
ModbusPDUError errorResponse = (ModbusPDUError) responsePdu;
responseCode = getErrorCode(errorResponse);
} else {
try {
plcValue = toPlcValue(requestPdu, responsePdu, field.getDataType());
responseCode = PlcResponseCode.OK;
} catch (ParseException e) {
// Add an error response code ...
responseCode = PlcResponseCode.INTERNAL_ERROR;
}
}
// Prepare the response.
PlcReadResponse response = new DefaultPlcReadResponse(request, Collections.singletonMap(fieldName, new ResponseItem<>(responseCode, plcValue)));
// 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;
}
Aggregations