mbus-client 0.6.0

Modbus client stack for embedded and std environments with TCP, RTU, and ASCII transport support for modbus-rs project
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Application Layer Traits
//!
//! This module defines the core traits used to bridge the Modbus protocol stack with
//! user-defined application logic. It follows a callback-based (observer) pattern
//! where the stack notifies the application of successful responses or failures.
//!
//! Each trait corresponds to a functional group of Modbus services (Coils, Registers, etc.).
//!
//! ## Callback Contract (applies to all traits in this file)
//!
//! - Callbacks are dispatched from `ClientServices::poll()`. No callback is invoked unless
//!   the application actively calls `poll()`.
//! - A successful callback means the response was fully parsed and validated against the
//!   queued request context (transaction id, unit/slave address, and operation metadata).
//! - For a single request, either:
//!   - one success callback is invoked from the corresponding response trait, or
//!   - one failure callback is invoked via [`RequestErrorNotifier::request_failed`].
//! - After either callback path runs, the request is removed from the internal queue.
//! - Callback implementations should remain lightweight and non-blocking. If heavy work is
//!   needed (database writes, UI updates, IPC), enqueue that work into your own task queue.
//! - `txn_id` is always the original id supplied by the caller, including Serial modes where
//!   transaction ids are not transmitted on the wire.

use mbus_core::{
    errors::MbusError,
    function_codes::public::{DiagnosticSubFunction, EncapsulatedInterfaceType},
    transport::UnitIdOrSlaveAddr,
};

#[cfg(feature = "coils")]
use crate::services::coil::Coils;
#[cfg(feature = "diagnostics")]
use crate::services::diagnostic::DeviceIdentificationResponse;
#[cfg(feature = "discrete-inputs")]
use crate::services::discrete_input::DiscreteInputs;
#[cfg(feature = "fifo")]
use crate::services::fifo_queue::FifoQueue;
#[cfg(feature = "file-record")]
use crate::services::file_record::SubRequestParams;
#[cfg(feature = "registers")]
use crate::services::register::Registers;

/// Trait for receiving notifications about failed Modbus requests.
///
/// This is used to handle timeouts, connection issues, or Modbus exception responses
/// at the application level, allowing the implementor to gracefully recover or alert the user.
pub trait RequestErrorNotifier {
    /// Called by the client stack whenever a previously queued request cannot be completed.
    ///
    /// The `error` parameter identifies the exact failure cause. The following variants are
    /// delivered by the stack's internal `poll()` and `handle_timeouts()` logic:
    ///
    /// - **`MbusError::ModbusException(code)`** — The remote device replied with a Modbus
    ///   exception frame (`function code 0x80 + FC`). The server understood the request but
    ///   refused to execute it (e.g. illegal data address, illegal function). Delivered
    ///   immediately inside the `poll()` call that received the exception response, before
    ///   any retry logic runs.
    ///
    /// - **`MbusError::NoRetriesLeft`** — The response timeout expired and every configured
    ///   retry attempt was exhausted. `handle_timeouts()` waits `response_timeout_ms`
    ///   milliseconds after each send, schedules each retry according to the configured
    ///   `BackoffStrategy` and `JitterStrategy`, and fires this error only after the last
    ///   retry attempt has itself timed out without a response. The request is permanently
    ///   removed from the queue.
    ///
    /// - **`MbusError::SendFailed`** — A scheduled retry was due (its backoff timestamp was
    ///   reached inside `handle_timeouts()`), but the call to `transport.send()` returned an
    ///   error (e.g. the TCP connection or serial port was lost between the original send and
    ///   the retry). The request is dropped immediately; remaining retries in the budget are
    ///   not consumed.
    ///
    /// # Notes
    /// - Each call corresponds to exactly one transaction. After this call the request is
    ///   permanently removed from the internal expected-response queue and will not be retried
    ///   again. No further callbacks will be issued for the same `txn_id`.
    /// - The `txn_id` is always the value supplied when the request was originally enqueued,
    ///   even for Serial transports that do not transmit a transaction ID on the wire.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request.
    /// - `unit_id_slave_addr`: The target Modbus unit ID (TCP) or slave address (Serial).
    /// - `error`: The specific [`MbusError`] variant describing the failure (see above).
    fn request_failed(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        error: MbusError,
    );
}

#[cfg(feature = "traffic")]
/// Direction of raw Modbus frame traffic observed by the client stack.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrafficDirection {
    /// Outgoing request ADU sent by the client.
    Tx,
    /// Incoming response ADU received by the client.
    Rx,
}

#[cfg(feature = "traffic")]
/// Optional raw-frame traffic notifications emitted by the client stack.
///
/// This trait is opt-in and enabled only with the `traffic` feature. A
/// blanket no-op implementation is provided for all app types so applications
/// are never forced to implement it.
pub trait TrafficNotifier {
    /// Called when a request frame is sent.
    fn on_tx_frame(&mut self, _txn_id: u16, _unit_id_slave_addr: UnitIdOrSlaveAddr, _frame: &[u8]) {
    }

    /// Called when a response frame is received.
    fn on_rx_frame(&mut self, _txn_id: u16, _unit_id_slave_addr: UnitIdOrSlaveAddr, _frame: &[u8]) {
    }

    /// Called when sending a request frame failed.
    fn on_tx_error(
        &mut self,
        _txn_id: u16,
        _unit_id_slave_addr: UnitIdOrSlaveAddr,
        _error: MbusError,
        _frame: &[u8],
    ) {
    }

    /// Called when processing/receiving a response frame failed.
    fn on_rx_error(
        &mut self,
        _txn_id: u16,
        _unit_id_slave_addr: UnitIdOrSlaveAddr,
        _error: MbusError,
        _frame: &[u8],
    ) {
    }
}

/// Trait defining the expected response handling for coil-related Modbus operations.
///
/// Implementors of this trait to deliver the responses to the application layer,
/// allowing application developers to process the coil data and update their application state accordingly.
///
/// ## When Each Callback Is Fired
/// - `read_coils_response`: after a successful FC 0x01 response for a multi-coil read.
/// - `read_single_coil_response`: convenience callback when quantity was 1.
/// - `write_single_coil_response`: after a successful FC 0x05 echo/ack response.
/// - `write_multiple_coils_response`: after a successful FC 0x0F response containing
///   start address and quantity written by the server.
///
/// ## Data Semantics
/// - Address values are Modbus data-model addresses exactly as acknowledged by the server.
/// - Boolean coil values follow Modbus conventions: `true` = ON (`0xFF00` in FC 0x05 request),
///   `false` = OFF (`0x0000`).
#[cfg(feature = "coils")]
pub trait CoilResponse {
    /// Handles a Read Coils response by invoking the appropriate application callback with the coil states.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `coils`: A wrapper containing the bit-packed boolean statuses of the requested coils.
    fn read_coils_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        coils: &Coils,
    );

    /// Handles a Read Single Coil response.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The exact address of the single coil that was read.
    /// - `value`: The boolean state of the coil (`true` = ON, `false` = OFF).
    fn read_single_coil_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: bool,
    );

    /// Handles a Write Single Coil response, confirming the state change.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The address of the coil that was successfully written.
    /// - `value`: The boolean state applied to the coil (`true` = ON, `false` = OFF).
    fn write_single_coil_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: bool,
    );

    /// Handles a Write Multiple Coils response, confirming the bulk state change.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The starting address where the bulk write began.
    /// - `quantity`: The total number of consecutive coils updated.
    fn write_multiple_coils_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        quantity: u16,
    );
}

/// Trait defining the expected response handling for FIFO Queue Modbus operations.
///
/// ## When Callback Is Fired
/// - `read_fifo_queue_response` is invoked after a successful FC 0x18 response.
///
/// ## Data Semantics
/// - `fifo_queue` contains values in server-returned order.
/// - Quantity in the payload may vary between calls depending on device state.
///
/// ## Implementation Guidance
///   non-blocking because it runs in the `poll()` execution path.
#[cfg(feature = "fifo")]
pub trait FifoQueueResponse {
    /// Handles a Read FIFO Queue response.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `fifo_queue`: A `FifoQueue` struct containing the values pulled from the queue.
    fn read_fifo_queue_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        fifo_queue: &FifoQueue,
    );
}

/// Trait defining the expected response handling for File Record Modbus operations.
///
/// ## When Each Callback Is Fired
/// - `read_file_record_response`: after successful FC 0x14 response parsing.
/// - `write_file_record_response`: after successful FC 0x15 acknowledgement.
///
/// ## Data Semantics
/// - For read responses, each `SubRequestParams` entry reflects one returned record chunk.
/// - Per Modbus spec, the response does not echo `file_number` or `record_number`; those
///   fields are therefore reported as `0` in callback data and should not be used as identity.
#[cfg(feature = "file-record")]
pub trait FileRecordResponse {
    /// Handles a Read File Record response.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `data`: A slice containing the sub-request responses. Note that `file_number` and `record_number`
    ///
    /// are not returned by the server in the response PDU and will be set to 0 in the parameters.
    fn read_file_record_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        data: &[SubRequestParams],
    );

    /// Handles a Write File Record response, confirming the write was successful.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    fn write_file_record_response(&mut self, txn_id: u16, unit_id_slave_addr: UnitIdOrSlaveAddr);
}

/// Defines callbacks for handling responses to Modbus register-related requests.
///
/// Implementors of this trait can process the data received from a Modbus server
/// and update their application state accordingly. Each method corresponds to a
/// specific Modbus register operation response.
///
/// ## Callback Mapping
/// - FC 0x03: `read_multiple_holding_registers_response`, `read_single_holding_register_response`
/// - FC 0x04: `read_multiple_input_registers_response`, `read_single_input_register_response`
/// - FC 0x06: `write_single_register_response`
/// - FC 0x10: `write_multiple_registers_response`
/// - FC 0x16: `mask_write_register_response`
/// - FC 0x17: `read_write_multiple_registers_response`
///
/// ## Data Semantics
/// - Register values are 16-bit words (`u16`) already decoded from Modbus big-endian byte pairs.
/// - Address and quantity values are echoed/validated values corresponding to the original request.
#[cfg(feature = "registers")]
pub trait RegisterResponse {
    /// Handles a response for a `Read Input Registers` (FC 0x04) request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `registers`: A `Registers` struct containing the values of the read input registers.
    fn read_multiple_input_registers_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        registers: &Registers,
    );

    /// Handles a response for a `Read Single Input Register` (FC 0x04) request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The address of the register that was read.
    /// - `value`: The value of the read register.
    fn read_single_input_register_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: u16,
    );

    /// Handles a response for a `Read Holding Registers` (FC 0x03) request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `registers`: A `Registers` struct containing the values of the read holding registers.
    fn read_multiple_holding_registers_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        registers: &Registers,
    );

    /// Handles a response for a `Write Single Register` (FC 0x06) request, confirming a successful write.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The address of the register that was written.
    /// - `value`: The value that was written to the register.
    fn write_single_register_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: u16,
    );

    /// Handles a response for a `Write Multiple Registers` (FC 0x10) request, confirming a successful write.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `starting_address`: The starting address of the registers that were written.
    /// - `quantity`: The number of registers that were written.
    fn write_multiple_registers_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        starting_address: u16,
        quantity: u16,
    );

    /// Handles a response for a `Read/Write Multiple Registers` (FC 0x17) request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `registers`: A `Registers` struct containing the values of the registers that were read.
    fn read_write_multiple_registers_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        registers: &Registers,
    );

    /// Handles a response for a single register read request.
    ///
    /// This is a convenience callback for when only one register is requested.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The address of the register that was read.
    /// - `value`: The value of the read register.
    fn read_single_register_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: u16,
    );

    /// Handles a response for a single holding register write request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The address of the register that was written.
    /// - `value`: The value that was written to the register.
    fn read_single_holding_register_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: u16,
    );

    /// Handles a response for a `Mask Write Register` (FC 0x16) request, confirming a successful operation.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    fn mask_write_register_response(&mut self, txn_id: u16, unit_id_slave_addr: UnitIdOrSlaveAddr);
}

/// Defines callbacks for handling responses to Modbus discrete input-related requests.
///
/// Implementors of this trait can process the data received from a Modbus server
/// and update their application state accordingly.
///
/// ## When Each Callback Is Fired
/// - `read_multiple_discrete_inputs_response`: after successful FC 0x02 with quantity > 1.
/// - `read_single_discrete_input_response`: convenience callback when quantity was 1.
///
/// ## Data Semantics
/// - `DiscreteInputs` stores bit-packed values; use helper methods on the type instead of
///   manually decoding bit offsets in application code.
#[cfg(feature = "discrete-inputs")]
pub trait DiscreteInputResponse {
    /// Handles a response for a `Read Discrete Inputs` (FC 0x02) request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `discrete_inputs`: A `DiscreteInputs` struct containing the states of the read inputs.
    fn read_multiple_discrete_inputs_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        discrete_inputs: &DiscreteInputs,
    );

    /// Handles a response for a single discrete input read request.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `address`: The address of the input that was read.
    /// - `value`: The boolean state of the read input.
    fn read_single_discrete_input_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: bool,
    );
}

/// Trait for handling Diagnostics-family responses.
///
/// ## Callback Mapping
/// - FC 0x2B / MEI 0x0E: `read_device_identification_response`
/// - FC 0x2B / other MEI: `encapsulated_interface_transport_response`
/// - FC 0x07: `read_exception_status_response`
/// - FC 0x08: `diagnostics_response`
/// - FC 0x0B: `get_comm_event_counter_response`
/// - FC 0x0C: `get_comm_event_log_response`
/// - FC 0x11: `report_server_id_response`
///
/// ## Data Semantics
/// - `mei_type`, `sub_function`, counters, and event buffers are already validated and decoded.
/// - Large payloads (event logs, generic encapsulated transport data) should typically be copied
///   or forwarded quickly, then processed outside the callback hot path.
#[cfg(feature = "diagnostics")]
pub trait DiagnosticsResponse {
    /// Called when a Read Device Identification response is received.
    ///
    /// Implementors can use this callback to process the device identity info (Vendor, Product Code, etc.).
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `response`: Extracted device identification strings.
    fn read_device_identification_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        response: &DeviceIdentificationResponse,
    );

    /// Called when a generic Encapsulated Interface Transport response (FC 43) is received.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The unit ID of the device that responded.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `mei_type`: The MEI type returned in the response.
    /// - `data`: The data payload returned in the response.
    fn encapsulated_interface_transport_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        mei_type: EncapsulatedInterfaceType,
        data: &[u8],
    );

    /// Called when a Read Exception Status response (FC 07) is received.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `status`: The 8-bit exception status code returned by the server.
    fn read_exception_status_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        status: u8,
    );

    /// Called when a Diagnostics response (FC 08) is received.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `sub_function`: The sub-function code confirming the diagnostic test.
    /// - `data`: Data payload returned by the diagnostic test (e.g., echoed loopback data).
    fn diagnostics_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        sub_function: DiagnosticSubFunction,
        data: &[u16],
    );

    /// Called when a Get Comm Event Counter response (FC 11) is received.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `status`: The status word indicating if the device is busy.
    /// - `event_count`: The number of successful messages processed by the device.
    fn get_comm_event_counter_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        status: u16,
        event_count: u16,
    );

    /// Called when a Get Comm Event Log response (FC 12) is received.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `status`: The status word indicating device state.
    /// - `event_count`: Number of successful messages processed.
    /// - `message_count`: Quantity of messages processed since the last restart.
    /// - `events`: Raw byte array containing the device's internal event log.
    fn get_comm_event_log_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        status: u16,
        event_count: u16,
        message_count: u16,
        events: &[u8],
    );

    /// Called when a Report Server ID response (FC 17) is received.
    ///
    /// # Parameters
    /// - `txn_id`: Transaction ID of the original request. While Modbus Serial (RTU/ASCII)
    ///   does not natively use transaction IDs, the stack preserves the ID provided in
    ///   the request and returns it here to allow for asynchronous tracking.
    /// - `unit_id_slave_addr`: The target Modbus unit ID or slave address.
    ///   - `unit_id`: if transport is tcp
    ///   - `slave_addr`: if transport is serial
    /// - `data`: Raw identity/status data provided by the manufacturer.
    fn report_server_id_response(
        &mut self,
        txn_id: u16,
        unit_id_slave_addr: UnitIdOrSlaveAddr,
        data: &[u8],
    );
}