@@ -35,25 +35,16 @@ public class ModbusTcpClient extends ModbusClient {
35
35
36
36
private final Map <Integer , ResponsePromise > promises = new ConcurrentHashMap <>();
37
37
38
+ private final AtomicReference <TransactionSequence > transactionSequence = new AtomicReference <>();
39
+
38
40
private final ModbusClientConfig config ;
39
41
private final ModbusTcpClientTransport transport ;
40
- private final TransactionSequence transactionSequence ;
41
42
42
43
public ModbusTcpClient (ModbusClientConfig config , ModbusTcpClientTransport transport ) {
43
- this (config , transport , new DefaultTransactionSequence ());
44
- }
45
-
46
- public ModbusTcpClient (
47
- ModbusClientConfig config ,
48
- ModbusTcpClientTransport transport ,
49
- TransactionSequence transactionSequence
50
- ) {
51
-
52
44
super (transport );
53
45
54
46
this .config = config ;
55
47
this .transport = transport ;
56
- this .transactionSequence = transactionSequence ;
57
48
58
49
transport .receive (this ::onFrameReceived );
59
50
}
@@ -116,7 +107,10 @@ public CompletionStage<ModbusResponsePdu> sendAsync(int unitId, ModbusRequestPdu
116
107
}
117
108
118
109
private CompletionStage <ByteBuffer > sendBufferAsync (int unitId , ByteBuffer buffer ) {
119
- int transactionId = transactionSequence .next ();
110
+ TransactionSequence sequence = transactionSequence .updateAndGet (
111
+ ts -> ts != null ? ts : createTransactionSequence ()
112
+ );
113
+ int transactionId = sequence .next ();
120
114
121
115
var header = new MbapHeader (
122
116
transactionId ,
@@ -189,6 +183,16 @@ private void onFrameReceived(ModbusTcpFrame frame) {
189
183
}
190
184
}
191
185
186
+ /**
187
+ * Create and return the {@link TransactionSequence} that will be used to generate transaction
188
+ * ids.
189
+ *
190
+ * @return the {@link TransactionSequence} that will be used to generate transaction ids.
191
+ */
192
+ protected TransactionSequence createTransactionSequence () {
193
+ return new DefaultTransactionSequence ();
194
+ }
195
+
192
196
/**
193
197
* Create a new {@link ModbusTcpClient} using the given {@link ModbusTcpClientTransport} and a
194
198
* {@link ModbusClientConfig} with the default values.
@@ -239,6 +243,8 @@ public interface TransactionSequence {
239
243
/**
240
244
* Return the next 2-byte transaction identifier. Range is [0, 65535] by default.
241
245
*
246
+ * <p>Implementations must be safe for use by multiple threads.
247
+ *
242
248
* @return the next 2-byte transaction identifier.
243
249
*/
244
250
int next ();
0 commit comments