Skip to content

[Bug]: Modbus: Reading Coils as an array returns only the first value #2060

Open
@IsmoLeszczynski

Description

@IsmoLeszczynski

What happened?

When defining a ModbusTag with array size > 1, the ModbusOptimizer.processReadResponses(...) ModbusTagCoil logic returns only the first bit as the result. The array logic works correctly for registers, but the customized coil logic is missing the array handling:

// Calculate the byte that contains the response for this Coil
byte[] responseData = response.getResponseData();
int bitPosition = coilTag.getAddress() - response.startingAddress;
int bytePosition = bitPosition / 8;
int bitPositionInByte = bitPosition % 8;
boolean isBitSet = (responseData[bytePosition] & (1 << bitPositionInByte)) != 0;
values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.OK, new PlcBOOL(isBitSet)));

What it should do is check for the for the modbusTag.getNumberOfElements() and generate the PlcList when needed. My current development version fixes this as follows:

if (modbusTag.getNumberOfElements() > 1) {
  PlcList bitValues = new PlcList();
  for (int i = 0; i < modbusTag.getNumberOfElements(); i++) {
    int bitPosition = modbusTag.getAddress() - response.startingAddress + i;
    boolean isBitSet = getIsBitSet(bitPosition, responseData);
    bitValues.add(new PlcBOOL(isBitSet));
  }
  values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.OK, bitValues));
} else {
  int bitPosition = modbusTag.getAddress() - response.startingAddress;
  boolean isBitSet = getIsBitSet(bitPosition, responseData);
  values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.OK, new PlcBOOL(isBitSet)));
}
private static boolean getIsBitSet(int bitPosition, byte[] responseData) {
  int bytePosition = bitPosition / 8;
  int bitPositionInByte = bitPosition % 8;
  boolean isBitSet = (responseData[bytePosition] & (1 << bitPositionInByte)) != 0;
  return isBitSet;
}

Version

v0.13.0-SNAPSHOT

Programming Languages

  • plc4c
  • plc4go
  • plc4j
  • plc4net
  • plc4py

Protocols

  • AB-Ethernet
  • ADS /AMS
  • BACnet/IP
  • C-Bus
  • CANopen
  • EtherNet/IP
  • Firmata
  • IEC-69870
  • KNXnet/IP
  • Modbus
  • OPC-UA
  • Profinet
  • S7
  • S7-light

Metadata

Metadata

Assignees

Labels

Modbushttps://plc4x.apache.org/users/protocols/modbus.htmljavaPull requests that update Java code

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions