mbus-ffi 0.13.0

Native C FFI and browser WASM bindings for modbus-rs client APIs, with optional generated server bindings
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
684
685
686
687
688
689
690
691
692
693
694
695
//! C-facing callback types for the Modbus server FFI.
//!
//! ## Design Principles
//!
//! - One `*Req` struct per Modbus function code (or FC group member).
//! - **Input fields** come from the master request (parsed by the Rust server stack).
//! - **Output fields** (`out_*`) are pre-populated by Rust before the callback is
//!   invoked; C writes the response values directly into them.
//! - Output buffer fields (`out_data`, `out_events`, `out_server_id`) point **into
//!   Rust-owned stack buffers** that are valid only for the duration of the callback.
//!   C **MUST NOT** retain these pointers after the callback returns.
//! - C returns [`MbusServerExceptionCode`] to signal success or a Modbus exception.
//!   `Ok(0)` means the request was handled; any other value causes the server to
//!   send a Modbus exception response to the client.
//!
//! ## Safety
//!
//! All `*mut`/`*const` pointer fields in request structs are guaranteed non-null by
//! the Rust layer when a callback is invoked. C code should not pass NULL for these
//! fields when populating response outputs.
//!
//! ## Lifetime of output pointers
//!
//! ```text
//! Rust calls callback ──► C writes to out_data ──► Rust reads out_byte_count ──► done
//!                     ↑                                                       ↑
//!                     │                            Pointer is valid only here │
//! ```

use core::ffi::c_void;

// ── Exception codes ───────────────────────────────────────────────────────────

/// Exception code returned by every C server callback.
///
/// Maps 1-to-1 with the Modbus standard exception codes:
///
/// | Value | Name | When to return |
/// |-------|------|----------------|
/// | `0` | `Ok` | Request handled successfully. The server sends a normal response. |
/// | `1` | `IllegalFunction` | This function code is not supported by your server implementation. |
/// | `2` | `IllegalDataAddress` | The requested `address` or `quantity` is outside the server's valid range. |
/// | `3` | `IllegalDataValue` | A value in the request data field is not acceptable (e.g. out-of-range register value). |
/// | `4` | `ServerDeviceFailure` | An unrecoverable error occurred while processing the request (hardware fault, internal error). |
///
/// # Notes
/// - `Ok = 0` is a **non-standard sentinel** used only by this C API.  It is
///   never sent on the wire; the server translates it to a normal success response.
/// - For **write** function codes (FC05, FC06, FC0F, FC10, FC15, FC16, FC17),
///   `Ok` means the write was accepted and committed.  The server echoes the
///   request back to the master as specified by the Modbus protocol.
/// - For **read** function codes (FC01–FC04, FC07, FC0B, FC0C, FC11, FC14, FC17,
///   FC18, FC2B), `Ok` means the `out_*` fields have been populated with valid
///   response data.
/// - If you detect a timing violation in application logic (e.g. a sensor timed
///   out), return `ServerDeviceFailure`; do **not** return `FramingError` — that
///   is a transport-level status only returned by the `recv` callback.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MbusServerExceptionCode {
    /// No exception — the callback handled the request successfully.
    Ok = 0,
    /// FC is not supported / not implemented by this server.
    IllegalFunction = 1,
    /// Address or offset is outside the server's valid range.
    IllegalDataAddress = 2,
    /// A data value in the request is not acceptable.
    IllegalDataValue = 3,
    /// The server could not complete the request due to an internal failure.
    ServerDeviceFailure = 4,
}

// ── Per-FC request structs ────────────────────────────────────────────────────
//
// Naming convention:
//   MbusServer<FunctionName>Req     — flattened request + pre-allocated output fields.
//
// Output fields:
//   - Scalar outputs  : plain value fields (e.g. `out_byte_count: u8`). C writes the value.
//   - Buffer outputs  : `out_data: *mut u8, out_data_len: usize`. C writes into the supplied
//                       Rust buffer (at most `out_data_len` bytes) then sets the `out_byte_count`
//                       field to how many bytes were written.
//   - Pointer outputs : `*const` slice fields (e.g. for write FCs) hold immutable data from
//                       the master request. C reads them and must not retain them.

// ── FC01 / FC02 / FC03 / FC04 — Read handlers with packed byte output ─────────

/// Request context for FC 0x01 — Read Coils.
///
/// C reads `address` and `quantity`; writes packed coil bits into `out_data` (at most
/// `out_data_len` bytes) and sets `out_byte_count` to the number of bytes written.
#[cfg(feature = "coils")]
#[repr(C)]
pub struct MbusServerReadCoilsReq {
    /// Slave/unit address of the request.
    pub unit_id: u8,
    /// Transaction ID (MBAP) or 0 for serial.
    pub txn_id: u16,
    /// Starting coil address.
    pub address: u16,
    /// Number of coils to read.
    pub quantity: u16,
    /// Buffer to write packed coil bytes into (Rust-allocated, valid for callback duration).
    pub out_data: *mut u8,
    /// Capacity of `out_data` in bytes.
    pub out_data_len: usize,
    /// C must set this to the number of bytes written into `out_data`.
    pub out_byte_count: u8,
}

/// C callback type for FC 0x01.
#[cfg(feature = "coils")]
pub type MbusServerReadCoilsFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadCoilsReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

/// Request context for FC 0x02 — Read Discrete Inputs.
#[cfg(feature = "discrete-inputs")]
#[repr(C)]
pub struct MbusServerReadDiscreteInputsReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub address: u16,
    pub quantity: u16,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    pub out_byte_count: u8,
}

/// C callback type for FC 0x02.
#[cfg(feature = "discrete-inputs")]
pub type MbusServerReadDiscreteInputsFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadDiscreteInputsReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

/// Request context for FC 0x03 — Read Holding Registers.
///
/// `out_data` receives big-endian register bytes (2 bytes per register).
/// `out_byte_count` must be set to `quantity * 2` on success.
#[cfg(feature = "holding-registers")]
#[repr(C)]
pub struct MbusServerReadHoldingRegistersReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub address: u16,
    pub quantity: u16,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    pub out_byte_count: u8,
}

/// C callback type for FC 0x03.
#[cfg(feature = "holding-registers")]
pub type MbusServerReadHoldingRegistersFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadHoldingRegistersReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

/// Request context for FC 0x04 — Read Input Registers.
#[cfg(feature = "input-registers")]
#[repr(C)]
pub struct MbusServerReadInputRegistersReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub address: u16,
    pub quantity: u16,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    pub out_byte_count: u8,
}

/// C callback type for FC 0x04.
#[cfg(feature = "input-registers")]
pub type MbusServerReadInputRegistersFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadInputRegistersReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC05 / FC06 — Write single (no output data) ───────────────────────────────

/// Request context for FC 0x05 — Write Single Coil.
#[cfg(feature = "coils")]
#[repr(C)]
pub struct MbusServerWriteSingleCoilReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub address: u16,
    /// `true` = force coil ON, `false` = force coil OFF.
    pub value: bool,
}

/// C callback type for FC 0x05.
#[cfg(feature = "coils")]
pub type MbusServerWriteSingleCoilFn = Option<
    unsafe extern "C" fn(
        req: *const MbusServerWriteSingleCoilReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

/// Request context for FC 0x06 — Write Single Register.
#[cfg(feature = "holding-registers")]
#[repr(C)]
pub struct MbusServerWriteSingleRegisterReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub address: u16,
    pub value: u16,
}

/// C callback type for FC 0x06.
#[cfg(feature = "holding-registers")]
pub type MbusServerWriteSingleRegisterFn = Option<
    unsafe extern "C" fn(
        req: *const MbusServerWriteSingleRegisterReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC07 — Read Exception Status ─────────────────────────────────────────────

/// Request context for FC 0x07 — Read Exception Status.
///
/// C sets `out_status` to the 8-bit exception status byte.
#[cfg(feature = "diagnostics")]
#[repr(C)]
pub struct MbusServerReadExceptionStatusReq {
    pub unit_id: u8,
    pub txn_id: u16,
    /// C must set this to the 8-bit exception status byte.
    pub out_status: u8,
}

/// C callback type for FC 0x07.
#[cfg(feature = "diagnostics")]
pub type MbusServerReadExceptionStatusFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadExceptionStatusReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC08 — Diagnostics ───────────────────────────────────────────────────────

/// Request context for FC 0x08 — Diagnostics.
///
/// `sub_function` is the raw 16-bit sub-function code (see Modbus spec §6.8).
/// C sets `out_result` to the 16-bit data echo/result.
#[cfg(feature = "diagnostics")]
#[repr(C)]
pub struct MbusServerDiagnosticsReq {
    pub unit_id: u8,
    pub txn_id: u16,
    /// Raw sub-function code (e.g. 0x0000 = Return Query Data, 0x0002 = Return Diagnostic Register).
    pub sub_function: u16,
    /// Data word from the request.
    pub data: u16,
    /// C must set this to the 16-bit result/echo value.
    pub out_result: u16,
}

/// C callback type for FC 0x08.
#[cfg(feature = "diagnostics")]
pub type MbusServerDiagnosticsFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerDiagnosticsReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC0B — Get Comm Event Counter ─────────────────────────────────────────────

/// Request context for FC 0x0B — Get Comm Event Counter.
///
/// C sets `out_status` (status word) and `out_event_count`.
#[cfg(feature = "diagnostics")]
#[repr(C)]
pub struct MbusServerGetCommEventCounterReq {
    pub unit_id: u8,
    pub txn_id: u16,
    /// C must set this to the status word.
    pub out_status: u16,
    /// C must set this to the event counter value.
    pub out_event_count: u16,
}

/// C callback type for FC 0x0B.
#[cfg(feature = "diagnostics")]
pub type MbusServerGetCommEventCounterFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerGetCommEventCounterReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC0C — Get Comm Event Log ─────────────────────────────────────────────────

/// Request context for FC 0x0C — Get Comm Event Log.
///
/// C writes event bytes into `out_events` (max `out_events_len` bytes) and
/// sets the four output scalar fields.
#[cfg(feature = "diagnostics")]
#[repr(C)]
pub struct MbusServerGetCommEventLogReq {
    pub unit_id: u8,
    pub txn_id: u16,
    /// Buffer for event log bytes (Rust-allocated, valid for callback duration).
    pub out_events: *mut u8,
    /// Capacity of `out_events`.
    pub out_events_len: usize,
    /// C must set to the Status word.
    pub out_status: u16,
    /// C must set to the Event Count.
    pub out_event_count: u16,
    /// C must set to the Message Count.
    pub out_message_count: u16,
    /// C must set to the number of events written into `out_events`.
    pub out_num_events: u8,
}

/// C callback type for FC 0x0C.
#[cfg(feature = "diagnostics")]
pub type MbusServerGetCommEventLogFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerGetCommEventLogReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC0F — Write Multiple Coils ───────────────────────────────────────────────

/// Request context for FC 0x0F — Write Multiple Coils.
///
/// `values` is a packed bit array from the master (LSB of first byte = coil at
/// `starting_address`). Valid for the duration of the callback only.
#[cfg(feature = "coils")]
#[repr(C)]
pub struct MbusServerWriteMultipleCoilsReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub starting_address: u16,
    pub quantity: u16,
    /// Packed coil bits from the master (read-only, valid for callback duration).
    pub values: *const u8,
    /// Number of bytes in `values`.
    pub values_len: usize,
}

/// C callback type for FC 0x0F.
#[cfg(feature = "coils")]
pub type MbusServerWriteMultipleCoilsFn = Option<
    unsafe extern "C" fn(
        req: *const MbusServerWriteMultipleCoilsReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC10 — Write Multiple Registers ──────────────────────────────────────────

/// Request context for FC 0x10 — Write Multiple Registers.
///
/// `values` contains the decoded `u16` register values (big-endian already parsed).
/// Valid for the duration of the callback only.
#[cfg(feature = "holding-registers")]
#[repr(C)]
pub struct MbusServerWriteMultipleRegistersReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub starting_address: u16,
    /// Decoded register values from the master (read-only, valid for callback duration).
    pub values: *const u16,
    /// Number of elements in `values`.
    pub values_len: usize,
}

/// C callback type for FC 0x10.
#[cfg(feature = "holding-registers")]
pub type MbusServerWriteMultipleRegistersFn = Option<
    unsafe extern "C" fn(
        req: *const MbusServerWriteMultipleRegistersReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC11 — Report Server ID ───────────────────────────────────────────────────

/// Request context for FC 0x11 — Report Server ID.
///
/// C writes vendor/device identification bytes into `out_server_id` and sets
/// `out_byte_count` and `out_run_indicator_status`.
#[cfg(feature = "diagnostics")]
#[repr(C)]
pub struct MbusServerReportServerIdReq {
    pub unit_id: u8,
    pub txn_id: u16,
    /// Buffer for server ID bytes (Rust-allocated).
    pub out_server_id: *mut u8,
    /// Capacity of `out_server_id`.
    pub out_server_id_len: usize,
    /// C must set to the number of Server ID bytes written.
    pub out_byte_count: u8,
    /// C must set to the Run Indicator Status byte (0x00 = OFF, 0xFF = ON).
    pub out_run_indicator_status: u8,
}

/// C callback type for FC 0x11.
#[cfg(feature = "diagnostics")]
pub type MbusServerReportServerIdFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReportServerIdReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC14 — Read File Record ───────────────────────────────────────────────────

/// Request context for FC 0x14 — Read File Record (one sub-request at a time).
///
/// C writes record data bytes into `out_data` and sets `out_byte_count`.
#[cfg(feature = "file-record")]
#[repr(C)]
pub struct MbusServerReadFileRecordReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub file_number: u16,
    pub record_number: u16,
    pub record_length: u16,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    /// C must set to the number of bytes written into `out_data`.
    pub out_byte_count: u8,
}

/// C callback type for FC 0x14.
#[cfg(feature = "file-record")]
pub type MbusServerReadFileRecordFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadFileRecordReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC15 — Write File Record ──────────────────────────────────────────────────

/// Request context for FC 0x15 — Write File Record (one sub-request at a time).
///
/// `record_data` contains decoded `u16` words. Valid for the callback duration only.
#[cfg(feature = "file-record")]
#[repr(C)]
pub struct MbusServerWriteFileRecordReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub file_number: u16,
    pub record_number: u16,
    pub record_length: u16,
    /// Decoded record data words (read-only, valid for callback duration).
    pub record_data: *const u16,
    pub record_data_len: usize,
}

/// C callback type for FC 0x15.
#[cfg(feature = "file-record")]
pub type MbusServerWriteFileRecordFn = Option<
    unsafe extern "C" fn(
        req: *const MbusServerWriteFileRecordReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC16 — Mask Write Register ────────────────────────────────────────────────

/// Request context for FC 0x16 — Mask Write Register.
#[cfg(feature = "holding-registers")]
#[repr(C)]
pub struct MbusServerMaskWriteRegisterReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub address: u16,
    pub and_mask: u16,
    pub or_mask: u16,
}

/// C callback type for FC 0x16.
#[cfg(feature = "holding-registers")]
pub type MbusServerMaskWriteRegisterFn = Option<
    unsafe extern "C" fn(
        req: *const MbusServerMaskWriteRegisterReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC17 — Read/Write Multiple Registers ──────────────────────────────────────

/// Request context for FC 0x17 — Read/Write Multiple Registers.
///
/// C writes the read result into `out_data` (big-endian register bytes) and sets
/// `out_byte_count`. `write_values` contains the decoded write values from the master.
#[cfg(feature = "holding-registers")]
#[repr(C)]
pub struct MbusServerReadWriteMultipleRegistersReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub read_address: u16,
    pub read_quantity: u16,
    pub write_address: u16,
    /// Decoded write values from the master (read-only, valid for callback duration).
    pub write_values: *const u16,
    pub write_values_len: usize,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    /// C must set to the number of bytes written into `out_data`.
    pub out_byte_count: u8,
}

/// C callback type for FC 0x17.
#[cfg(feature = "holding-registers")]
pub type MbusServerReadWriteMultipleRegistersFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadWriteMultipleRegistersReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC18 — Read FIFO Queue ────────────────────────────────────────────────────

/// Request context for FC 0x18 — Read FIFO Queue.
#[cfg(feature = "fifo")]
#[repr(C)]
pub struct MbusServerReadFifoQueueReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub pointer_address: u16,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    /// C must set to the number of bytes written.
    pub out_byte_count: u8,
}

/// C callback type for FC 0x18.
#[cfg(feature = "fifo")]
pub type MbusServerReadFifoQueueFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadFifoQueueReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── FC2B/0x0E — Read Device Identification ────────────────────────────────────

/// Request context for FC 0x2B / MEI 0x0E — Read Device Identification.
///
/// C writes object data into `out_data` and sets all `out_*` fields.
#[cfg(feature = "diagnostics")]
#[repr(C)]
pub struct MbusServerReadDeviceIdentificationReq {
    pub unit_id: u8,
    pub txn_id: u16,
    pub read_device_id_code: u8,
    pub start_object_id: u8,
    pub out_data: *mut u8,
    pub out_data_len: usize,
    /// C must set to the conformity level byte.
    pub out_conformity_level: u8,
    /// C must set to the "more follows" object ID (0x00 if none).
    pub out_more_follows_object_id: u8,
    /// C must set to `true` if more objects follow (segmentation).
    pub out_has_more: bool,
    /// C must set to the next Object ID to request (only valid when `out_has_more` is true).
    pub out_next_object_id: u8,
    /// C must set to the number of bytes written into `out_data`.
    pub out_byte_count: u8,
}

/// C callback type for FC 0x2B / MEI 0x0E.
#[cfg(feature = "diagnostics")]
pub type MbusServerReadDeviceIdentificationFn = Option<
    unsafe extern "C" fn(
        req: *mut MbusServerReadDeviceIdentificationReq,
        userdata: *mut c_void,
    ) -> MbusServerExceptionCode,
>;

// ── MbusServerHandlers ────────────────────────────────────────────────────────

/// Master callback table for a C Modbus server application.
///
/// Pass a populated instance to `mbus_tcp_server_new`,
/// `mbus_serial_rtu_server_new`, or `mbus_serial_ascii_server_new`.
///
/// ## NULL slots
/// Any callback slot left as `NULL` causes the server to respond with
/// `ExceptionCode::IllegalFunction` (0x01) for that function code.
/// You do not need to implement callbacks for function codes your device
/// does not support.
///
/// ## Return value contract
/// Every callback returns `MbusServerExceptionCode`.  The server uses this to
/// decide what to send on the wire:
///
/// | Return value | Wire response |
/// |---|---|
/// | `Ok` | Normal success response (echo or `out_*` data). |
/// | `IllegalFunction` | Exception response 0x01. |
/// | `IllegalDataAddress` | Exception response 0x02. |
/// | `IllegalDataValue` | Exception response 0x03. |
/// | `ServerDeviceFailure` | Exception response 0x04. |
///
/// ## Timing — serial servers
/// Callbacks are invoked from within `mbus_serial_server_poll`.  The stack
/// does **not** call the `recv` callback while a callback is running, so you
/// cannot observe a t1.5/t3.5 violation from inside a handler.  Timing
/// violations are detected and reported exclusively through the `recv`
/// transport callback before dispatch (see the `serial_server` module docs).
///
/// ## Lifetime of pointer fields
/// All `*mut` and `*const` pointer fields in the `*Req` structs are valid only
/// for the duration of the callback invocation.  Do **not** retain them.
///
/// ## Example (C)
///
/// ```c
/// static MbusServerHandlers g_handlers = {
///     .userdata             = &my_app_state,
///     .on_read_holding_registers = my_read_hr_handler,
///     .on_write_single_register  = my_write_sr_handler,
///     // All other slots are NULL → server returns IllegalFunction.
/// };
/// ```
#[repr(C)]
pub struct MbusServerHandlers {
    /// Opaque pointer passed to every callback.
    pub userdata: *mut c_void,

    // ── Coil handlers (FC01, FC05, FC0F) ─────────────────────────────────────
    #[cfg(feature = "coils")]
    pub on_read_coils: MbusServerReadCoilsFn,
    #[cfg(feature = "coils")]
    pub on_write_single_coil: MbusServerWriteSingleCoilFn,
    #[cfg(feature = "coils")]
    pub on_write_multiple_coils: MbusServerWriteMultipleCoilsFn,

    // ── Discrete Input handlers (FC02) ────────────────────────────────────────
    #[cfg(feature = "discrete-inputs")]
    pub on_read_discrete_inputs: MbusServerReadDiscreteInputsFn,

    // ── Holding Register handlers (FC03, FC06, FC10, FC16, FC17) ─────────────
    #[cfg(feature = "holding-registers")]
    pub on_read_holding_registers: MbusServerReadHoldingRegistersFn,
    #[cfg(feature = "holding-registers")]
    pub on_write_single_register: MbusServerWriteSingleRegisterFn,
    #[cfg(feature = "holding-registers")]
    pub on_write_multiple_registers: MbusServerWriteMultipleRegistersFn,
    #[cfg(feature = "holding-registers")]
    pub on_mask_write_register: MbusServerMaskWriteRegisterFn,
    #[cfg(feature = "holding-registers")]
    pub on_read_write_multiple_registers: MbusServerReadWriteMultipleRegistersFn,

    // ── Input Register handlers (FC04) ────────────────────────────────────────
    #[cfg(feature = "input-registers")]
    pub on_read_input_registers: MbusServerReadInputRegistersFn,

    // ── FIFO Queue handlers (FC18) ────────────────────────────────────────────
    #[cfg(feature = "fifo")]
    pub on_read_fifo_queue: MbusServerReadFifoQueueFn,

    // ── File Record handlers (FC14, FC15) ─────────────────────────────────────
    #[cfg(feature = "file-record")]
    pub on_read_file_record: MbusServerReadFileRecordFn,
    #[cfg(feature = "file-record")]
    pub on_write_file_record: MbusServerWriteFileRecordFn,

    // ── Diagnostics handlers (FC07, FC08, FC0B, FC0C, FC11, FC2B) ────────────
    #[cfg(feature = "diagnostics")]
    pub on_read_exception_status: MbusServerReadExceptionStatusFn,
    #[cfg(feature = "diagnostics")]
    pub on_diagnostics: MbusServerDiagnosticsFn,
    #[cfg(feature = "diagnostics")]
    pub on_get_comm_event_counter: MbusServerGetCommEventCounterFn,
    #[cfg(feature = "diagnostics")]
    pub on_get_comm_event_log: MbusServerGetCommEventLogFn,
    #[cfg(feature = "diagnostics")]
    pub on_report_server_id: MbusServerReportServerIdFn,
    #[cfg(feature = "diagnostics")]
    pub on_read_device_identification: MbusServerReadDeviceIdentificationFn,
}