Skip to content

feat(plc4j/modbus): ModbusOptimizer fixes for discrete-input and endianness #2055

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ protected PlcReadResponse processReadResponses(PlcReadRequest readRequest, Map<P
}
// Go through all responses till we find one where that contains the current tag's data.
for (Response response : responses.get(tagType)) {
if(modbusTag instanceof ModbusTagCoil) {
if((modbusTag instanceof ModbusTagCoil) || (modbusTag instanceof ModbusTagDiscreteInput)) {
if(response.matchesCoil(modbusTag)) {
// If this response was invalid, return all associated addresses as equally invalid.
// TODO: Possibly it would be worth doing a single item request for each of these
Expand All @@ -204,12 +204,11 @@ protected PlcReadResponse processReadResponses(PlcReadRequest readRequest, Map<P
break;
}

// Coils are read completely different from registers.
ModbusTagCoil coilTag = (ModbusTagCoil) modbusTag;
// Coils and Discrete Inputs are read completely different from registers.

// Calculate the byte that contains the response for this Coil
byte[] responseData = response.getResponseData();
int bitPosition = coilTag.getAddress() - response.startingAddress;
int bitPosition = modbusTag.getAddress() - response.startingAddress;
int bytePosition = bitPosition / 8;
int bitPositionInByte = bitPosition % 8;
boolean isBitSet = (responseData[bytePosition] & (1 << bitPositionInByte)) != 0;
Expand All @@ -229,12 +228,14 @@ else if (response.matchesRegister(modbusTag)) {
break;
}

var byteOrder = modbusTag.getByteOrder() != null ? modbusTag.getByteOrder() : modbusContext.getByteOrder();

byte[] responseData = response.getResponseDataForTag(modbusTag);
ReadBuffer readBuffer = getReadBuffer(responseData, modbusContext.getByteOrder());
ReadBuffer readBuffer = getReadBuffer(responseData, byteOrder);
try {
PlcValue plcValue = DataItem.staticParse(readBuffer, modbusTag.getDataType(),
modbusTag.getNumberOfElements(),
modbusContext.getByteOrder() == ModbusByteOrder.BIG_ENDIAN);
byteOrder == ModbusByteOrder.BIG_ENDIAN);
values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.OK, plcValue));
} catch (ParseException e) {
values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.INTERNAL_ERROR, null));
Expand Down