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
//! `CServerApp` — the Rust-side bridge between `mbus-server` and C callbacks.
//!
//! `CServerApp` implements all eight server handler traits by dispatching each
//! incoming Modbus request to the corresponding C function pointer in
//! [`MbusServerHandlers`].  When a slot is `None` (NULL in C), the default
//! trait behaviour applies: the server returns `IllegalFunction`.
//!
//! ## Exception mapping
//!
//! The `mbus-server` runtime converts `MbusError` → `ExceptionCode` via
//! `FunctionCode::exception_code_for_error`. The mapping used here:
//!
//! | `MbusServerExceptionCode` | `MbusError` returned  | Resulting Modbus exception  |
//! |---------------------------|-----------------------|-----------------------------|
//! | `Ok (0)`                  | `Ok(data)`            | no exception                |
//! | `IllegalFunction (1)`     | `InvalidFunctionCode` | `0x01` IllegalFunction      |
//! | `IllegalDataAddress (2)`  | `InvalidAddress`      | `0x02` IllegalDataAddress   |
//! | `IllegalDataValue (3)`    | `InvalidValue`        | `0x03` IllegalDataValue     |
//! | `ServerDeviceFailure (4)` | `Unexpected`          | `0x04` ServerDeviceFailure  |
//!
//! ## Feature gates
//!
//! Each trait implementation is gated by the corresponding `mbus-ffi` feature
//! (`coils`, `discrete-inputs`, `registers`, `fifo`, `file-record`, `diagnostics`)
//! so that unused handler code is not compiled when building with a minimal
//! feature set (e.g. `--features c-server,coils`).

use mbus_core::errors::MbusError;
#[cfg(feature = "diagnostics")]
use mbus_core::function_codes::public::DiagnosticSubFunction;
use mbus_core::transport::UnitIdOrSlaveAddr;
use mbus_server::ServerCoilHandler;
use mbus_server::ServerDiagnosticsHandler;
use mbus_server::ServerDiscreteInputHandler;
use mbus_server::ServerExceptionHandler;
use mbus_server::ServerFifoHandler;
use mbus_server::ServerFileRecordHandler;
use mbus_server::ServerHoldingRegisterHandler;
use mbus_server::ServerInputRegisterHandler;

use super::callbacks::*;

// ── Exception mapping helper ──────────────────────────────────────────────────

/// Maps a C exception code to the `MbusError` that produces the correct Modbus
/// exception response when processed by `FunctionCode::exception_code_for_error`.
#[inline(always)]
fn exception_to_error(exc: MbusServerExceptionCode) -> MbusError {
    match exc {
        // Ok is never expected here — callers only pass non-Ok values.
        MbusServerExceptionCode::Ok => MbusError::Unexpected,
        MbusServerExceptionCode::IllegalFunction => MbusError::InvalidFunctionCode,
        MbusServerExceptionCode::IllegalDataAddress => MbusError::InvalidAddress,
        MbusServerExceptionCode::IllegalDataValue => MbusError::InvalidValue,
        MbusServerExceptionCode::ServerDeviceFailure => MbusError::Unexpected,
    }
}

// ── CServerApp ────────────────────────────────────────────────────────────────

/// Modbus server application backed by C function-pointer callbacks.
///
/// Implements all eight `mbus-server` handler traits. Each trait method checks
/// whether the corresponding callback slot is populated; if not, it returns
/// `InvalidFunctionCode` which the server converts to `IllegalFunction`.
///
/// # Safety
///
/// `CServerApp` stores a `MbusServerHandlers` which may contain raw pointers/fn
/// ptrs. It is the caller's responsibility to ensure:
/// - All registered callbacks are valid function pointers for the lifetime of
///   the server.
/// - The `userdata` pointer (if non-null) outlives the server.
/// - No callback re-enters the server's poll loop.
pub struct CServerApp {
    pub(super) handlers: MbusServerHandlers,
}

impl CServerApp {
    pub(super) fn new(handlers: MbusServerHandlers) -> Self {
        Self { handlers }
    }
}

// ── ServerExceptionHandler — default no-op ────────────────────────────────────

impl ServerExceptionHandler for CServerApp {}

// ── ServerCoilHandler ─────────────────────────────────────────────────────────

#[cfg(feature = "coils")]
impl ServerCoilHandler for CServerApp {
    fn read_coils_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        quantity: u16,
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_coils else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadCoilsReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            quantity,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }

    fn write_single_coil_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: bool,
    ) -> Result<(), MbusError> {
        let Some(cb) = self.handlers.on_write_single_coil else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let req = MbusServerWriteSingleCoilReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            value,
        };
        let exc = unsafe { cb(&req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(())
    }

    fn write_multiple_coils_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        starting_address: u16,
        quantity: u16,
        values: &[u8],
    ) -> Result<(), MbusError> {
        let Some(cb) = self.handlers.on_write_multiple_coils else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let req = MbusServerWriteMultipleCoilsReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            starting_address,
            quantity,
            values: values.as_ptr(),
            values_len: values.len(),
        };
        let exc = unsafe { cb(&req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(())
    }
}

// When the `coils` feature is not enabled, provide a blank impl
// so that `CServerApp` still satisfies the `ModbusAppHandler` supertrait.
#[cfg(not(feature = "coils"))]
impl ServerCoilHandler for CServerApp {}

// ── ServerDiscreteInputHandler ────────────────────────────────────────────────

#[cfg(feature = "discrete-inputs")]
impl ServerDiscreteInputHandler for CServerApp {
    fn read_discrete_inputs_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        quantity: u16,
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_discrete_inputs else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadDiscreteInputsReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            quantity,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }
}

// When the `discrete-inputs` feature is not enabled, provide a blank impl
// so that `CServerApp` still satisfies the `ModbusAppHandler` supertrait.
#[cfg(not(feature = "discrete-inputs"))]
impl ServerDiscreteInputHandler for CServerApp {}

// ── ServerHoldingRegisterHandler ──────────────────────────────────────────────

#[cfg(feature = "holding-registers")]
impl ServerHoldingRegisterHandler for CServerApp {
    fn read_multiple_holding_registers_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        quantity: u16,
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_holding_registers else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadHoldingRegistersReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            quantity,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }

    fn write_single_register_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        value: u16,
    ) -> Result<(), MbusError> {
        let Some(cb) = self.handlers.on_write_single_register else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let req = MbusServerWriteSingleRegisterReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            value,
        };
        let exc = unsafe { cb(&req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(())
    }

    fn write_multiple_registers_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        starting_address: u16,
        values: &[u16],
    ) -> Result<(), MbusError> {
        let Some(cb) = self.handlers.on_write_multiple_registers else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let req = MbusServerWriteMultipleRegistersReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            starting_address,
            values: values.as_ptr(),
            values_len: values.len(),
        };
        let exc = unsafe { cb(&req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(())
    }

    fn mask_write_register_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        and_mask: u16,
        or_mask: u16,
    ) -> Result<(), MbusError> {
        let Some(cb) = self.handlers.on_mask_write_register else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let req = MbusServerMaskWriteRegisterReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            and_mask,
            or_mask,
        };
        let exc = unsafe { cb(&req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn read_write_multiple_registers_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        read_address: u16,
        read_quantity: u16,
        write_address: u16,
        write_values: &[u16],
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_write_multiple_registers else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadWriteMultipleRegistersReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            read_address,
            read_quantity,
            write_address,
            write_values: write_values.as_ptr(),
            write_values_len: write_values.len(),
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }
}

// ── ServerInputRegisterHandler ────────────────────────────────────────────────

#[cfg(feature = "input-registers")]
impl ServerInputRegisterHandler for CServerApp {
    fn read_multiple_input_registers_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        address: u16,
        quantity: u16,
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_input_registers else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadInputRegistersReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            address,
            quantity,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }
}

// When the `holding-registers` feature is not enabled, provide blank impls
// so that `CServerApp` still satisfies the `ModbusAppHandler` supertrait.
#[cfg(not(feature = "holding-registers"))]
impl ServerHoldingRegisterHandler for CServerApp {}
#[cfg(not(feature = "input-registers"))]
impl ServerInputRegisterHandler for CServerApp {}

// ── ServerFifoHandler ─────────────────────────────────────────────────────────

#[cfg(feature = "fifo")]
impl ServerFifoHandler for CServerApp {
    fn read_fifo_queue_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        pointer_address: u16,
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_fifo_queue else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadFifoQueueReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            pointer_address,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }
}

// When the `fifo` feature is not enabled, provide a blank impl
// so that `CServerApp` still satisfies the `ModbusAppHandler` supertrait.
#[cfg(not(feature = "fifo"))]
impl ServerFifoHandler for CServerApp {}

// ── ServerFileRecordHandler ───────────────────────────────────────────────────

#[cfg(feature = "file-record")]
impl ServerFileRecordHandler for CServerApp {
    fn read_file_record_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        file_number: u16,
        record_number: u16,
        record_length: u16,
        out: &mut [u8],
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_file_record else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadFileRecordReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            file_number,
            record_number,
            record_length,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_byte_count)
    }

    fn write_file_record_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        file_number: u16,
        record_number: u16,
        record_length: u16,
        record_data: &[u16],
    ) -> Result<(), MbusError> {
        let Some(cb) = self.handlers.on_write_file_record else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let req = MbusServerWriteFileRecordReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            file_number,
            record_number,
            record_length,
            record_data: record_data.as_ptr(),
            record_data_len: record_data.len(),
        };
        let exc = unsafe { cb(&req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(())
    }
}

// When the `file-record` feature is not enabled, provide a blank impl
// so that `CServerApp` still satisfies the `ModbusAppHandler` supertrait.
#[cfg(not(feature = "file-record"))]
impl ServerFileRecordHandler for CServerApp {}

// ── ServerDiagnosticsHandler ──────────────────────────────────────────────────

#[cfg(feature = "diagnostics")]
impl ServerDiagnosticsHandler for CServerApp {
    fn read_exception_status_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
    ) -> Result<u8, MbusError> {
        let Some(cb) = self.handlers.on_read_exception_status else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadExceptionStatusReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            out_status: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_status)
    }

    fn diagnostics_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        sub_function: DiagnosticSubFunction,
        data: u16,
    ) -> Result<u16, MbusError> {
        let Some(cb) = self.handlers.on_diagnostics else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerDiagnosticsReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            sub_function: sub_function as u16,
            data,
            out_result: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok(req.out_result)
    }

    fn get_comm_event_counter_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
    ) -> Result<(u16, u16), MbusError> {
        let Some(cb) = self.handlers.on_get_comm_event_counter else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerGetCommEventCounterReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            out_status: 0,
            out_event_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok((req.out_status, req.out_event_count))
    }

    fn get_comm_event_log_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        out_events: &mut [u8],
    ) -> Result<(u16, u16, u16, u8), MbusError> {
        let Some(cb) = self.handlers.on_get_comm_event_log else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerGetCommEventLogReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            out_events: out_events.as_mut_ptr(),
            out_events_len: out_events.len(),
            out_status: 0,
            out_event_count: 0,
            out_message_count: 0,
            out_num_events: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok((
            req.out_status,
            req.out_event_count,
            req.out_message_count,
            req.out_num_events,
        ))
    }

    fn report_server_id_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        out_server_id: &mut [u8],
    ) -> Result<(u8, u8), MbusError> {
        let Some(cb) = self.handlers.on_report_server_id else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReportServerIdReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            out_server_id: out_server_id.as_mut_ptr(),
            out_server_id_len: out_server_id.len(),
            out_byte_count: 0,
            out_run_indicator_status: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok((req.out_byte_count, req.out_run_indicator_status))
    }

    fn read_device_identification_request(
        &mut self,
        txn_id: u16,
        unit_id_or_slave_addr: UnitIdOrSlaveAddr,
        read_device_id_code: u8,
        start_object_id: u8,
        out: &mut [u8],
    ) -> Result<(u8, u8, bool, u8), MbusError> {
        let Some(cb) = self.handlers.on_read_device_identification else {
            return Err(MbusError::InvalidFunctionCode);
        };
        let mut req = MbusServerReadDeviceIdentificationReq {
            unit_id: unit_id_or_slave_addr.get(),
            txn_id,
            read_device_id_code,
            start_object_id,
            out_data: out.as_mut_ptr(),
            out_data_len: out.len(),
            out_conformity_level: 0,
            out_more_follows_object_id: 0,
            out_has_more: false,
            out_next_object_id: 0,
            out_byte_count: 0,
        };
        let exc = unsafe { cb(&mut req, self.handlers.userdata) };
        if exc != MbusServerExceptionCode::Ok {
            return Err(exception_to_error(exc));
        }
        Ok((
            req.out_conformity_level,
            req.out_more_follows_object_id,
            req.out_has_more,
            req.out_next_object_id,
        ))
    }
}

// When the `diagnostics` feature is not enabled, provide a blank impl
// so that `CServerApp` still satisfies the `ModbusAppHandler` supertrait.
#[cfg(not(feature = "diagnostics"))]
impl ServerDiagnosticsHandler for CServerApp {}

// ── TrafficNotifier (no-op when server-traffic feature is active) ─────────────

#[cfg(feature = "server-traffic")]
impl mbus_server::TrafficNotifier for CServerApp {}