digitalpetri / modbus

Modbus TCP, Modbus RTU/TCP, and Modbus RTU/Serial for Java 17+.
Eclipse Public License 2.0
653 stars 222 forks source link

Sending requests simultaneously #52

Closed kalwinskidawid closed 1 year ago

kalwinskidawid commented 1 year ago

Hi, Can I send multiple inquiries in parallel? I have sth like that:


    private void test(){
    this.readHoldingRegisters(0x1,0x1)->thenCompose(response-> {
    if(response.getRegisters().getUnsignedShort(0) != 255)
                final CompletableFuture<ReadHoldingRegistersResponse> firstPart =
                        this.readHoldingRegisters(firstPartStartAddress - 0x9c40, firstPartEndAddress - firstPartStartAddress);
                final CompletableFuture<ReadHoldingRegistersResponse> secondPart =
                        this.readHoldingRegisters(secondPartStartAddress - 0x9c40, secondPartEndAddress - secondPartStartAddress);

                List<CompletableFuture<ReadHoldingRegistersResponse>> test  =Stream.of(firstPart,secondPart)
                        .collect(Collectors.toList());
                 //...create object etc 
    });
    }
    private CompletableFuture<ReadHoldingRegistersResponse> readHoldingRegisters(final int offset, final int length){
        return this.connection.sendRequest(new ReadHoldingRegistersRequest(offset, length), super.getSlaveId());
    }

Usually after ->thenCompose, only the first part will be called and from it I will get the answer, while from the second part I will not get the answer. If I comment the first part request then I'll get response from sencond part. But I can't get to the point where both answer in parallel. What's wrong?

kalwinskidawid commented 1 year ago

Or is it a problem with the simulator? If I do Thread.sleep(1000), between firstPart and secondPart then everything works fine. I use ModbusTool

kevinherron commented 1 year ago

The library has no limit on sending concurrent requests, however in the real world not all Modbus TCP devices will support it.

I'm not sure about your simulator, maybe look at a Wireshark capture to see if without the Thread.sleep call 2 requests are sent before receiving the response will cause the device to not respond to the first.

kalwinskidawid commented 1 year ago

Thanks for info, probably I should check it at real Modbus device. Okay then I have to create synchronous requests or .thenCompose. What exaclty do ReferenceCountUtil.release(response) ? Should I use after every received response or I can skip it?