Skip to content
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

Allow subclasses to provide a TransactionSequence #89

Merged
merged 2 commits into from
Nov 15, 2024
Merged
Changes from 1 commit
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 @@ -35,25 +35,16 @@ public class ModbusTcpClient extends ModbusClient {

private final Map<Integer, ResponsePromise> promises = new ConcurrentHashMap<>();

private final AtomicReference<TransactionSequence> transactionSequence = new AtomicReference<>();

private final ModbusClientConfig config;
private final ModbusTcpClientTransport transport;
private final TransactionSequence transactionSequence;

public ModbusTcpClient(ModbusClientConfig config, ModbusTcpClientTransport transport) {
this(config, transport, new DefaultTransactionSequence());
}

public ModbusTcpClient(
ModbusClientConfig config,
ModbusTcpClientTransport transport,
TransactionSequence transactionSequence
) {

super(transport);

this.config = config;
this.transport = transport;
this.transactionSequence = transactionSequence;

transport.receive(this::onFrameReceived);
}
Expand Down Expand Up @@ -116,7 +107,10 @@ public CompletionStage<ModbusResponsePdu> sendAsync(int unitId, ModbusRequestPdu
}

private CompletionStage<ByteBuffer> sendBufferAsync(int unitId, ByteBuffer buffer) {
int transactionId = transactionSequence.next();
TransactionSequence sequence = transactionSequence.updateAndGet(
ts -> ts != null ? ts : createTransactionSequence()
);
int transactionId = sequence.next();

var header = new MbapHeader(
transactionId,
Expand Down Expand Up @@ -189,6 +183,16 @@ private void onFrameReceived(ModbusTcpFrame frame) {
}
}

/**
* Create and return the {@link TransactionSequence} that will be used to generate transaction
* ids.
*
* @return the {@link TransactionSequence} that will be used to generate transaction ids.
*/
protected TransactionSequence createTransactionSequence() {
return new DefaultTransactionSequence();
}

/**
* Create a new {@link ModbusTcpClient} using the given {@link ModbusTcpClientTransport} and a
* {@link ModbusClientConfig} with the default values.
Expand Down