Skip to content

Commit

Permalink
Allow subclasses to provide a TransactionSequence (#89)
Browse files Browse the repository at this point in the history
Refactor to use subclassing instead of a constructor parameter for customizing the TransactionSequence.
  • Loading branch information
kevinherron authored Nov 15, 2024
1 parent a978cb4 commit 339785a
Showing 1 changed file with 18 additions and 12 deletions.
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 Expand Up @@ -239,6 +243,8 @@ public interface TransactionSequence {
/**
* Return the next 2-byte transaction identifier. Range is [0, 65535] by default.
*
* <p>Implementations must be safe for use by multiple threads.
*
* @return the next 2-byte transaction identifier.
*/
int next();
Expand Down

0 comments on commit 339785a

Please sign in to comment.