mbrtu_ffi/lib.rs
1//! C FFI bindings for the `mbrtu` Modbus RTU decoder.
2//!
3//! Exposes a decode-only subset of `mbrtu`'s API: decode a single frame
4//! from a raw byte buffer into an opaque handle, then read its fields via
5//! an `mbrtu_request_as_<type>`/`mbrtu_response_as_<type>` function that
6//! fills a plain C struct. Request and response decoding are separate
7//! entry points because Modbus can't tell the two apart from the bytes
8//! alone (see `mbrtu`'s own `message` module docs) - the caller must
9//! already know which one it's looking at. See `include/mbrtu.h` for the
10//! generated C declarations.
11//!
12//! This crate is a plain (non-`no_std`) library: it targets host
13//! environments linking a shared or static C library, not the embedded
14//! `no_alloc` use case `mbrtu` itself supports. Embedded consumers should
15//! use the `mbrtu` Rust crate directly.
16
17use std::ffi::c_char;
18use std::ptr;
19
20use mbrtu::message::{
21 ExceptionResponse, ReadCoilsRequest, ReadCoilsResponse, ReadHoldingRegistersRequest,
22 ReadHoldingRegistersResponse, WriteSingleRegister,
23};
24use mbrtu::{ModbusRequest, ModbusResponse};
25
26/// Largest number of registers a single Read Holding Registers response
27/// can carry, per the Modbus spec.
28pub const MBRTU_FFI_MAX_REGISTERS: usize = 125;
29/// Bytes needed to hold the largest possible Read Coils response's packed
30/// bits, per the Modbus spec (2000 coils / 8 bits per byte).
31pub const MBRTU_FFI_MAX_COIL_BYTES: usize = 250;
32
33/// Opaque handle to a decoded Modbus RTU request, owned by the caller
34/// until freed with [`mbrtu_request_free`].
35pub struct MbrtuFfiRequest {
36 address: u8,
37 request: ModbusRequest,
38}
39
40/// Opaque handle to a decoded Modbus RTU response, owned by the caller
41/// until freed with [`mbrtu_response_free`].
42pub struct MbrtuFfiResponse {
43 address: u8,
44 response: ModbusResponse,
45}
46
47/// Error codes returned by [`mbrtu_decode_request`]/[`mbrtu_decode_response`].
48#[repr(u8)]
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum MbrtuFfiError {
51 /// No error.
52 Ok = 0,
53 /// The `buf` pointer was NULL.
54 NullInput = 1,
55 /// The frame itself was malformed (too short, bad CRC-16).
56 Frame = 2,
57 /// The function code is unknown/undecoded for the requested
58 /// direction, or the data was malformed for that function code.
59 Message = 3,
60}
61
62impl From<mbrtu::MbrtuError> for MbrtuFfiError {
63 fn from(e: mbrtu::MbrtuError) -> Self {
64 match e {
65 mbrtu::MbrtuError::Frame(_) => Self::Frame,
66 // covers Message(_) and any future non_exhaustive variant
67 _ => Self::Message,
68 }
69 }
70}
71
72fn set_error(out_error: *mut MbrtuFfiError, code: MbrtuFfiError) {
73 if !out_error.is_null() {
74 // SAFETY: caller guarantees `out_error` is a valid write target or NULL.
75 unsafe {
76 out_error.write(code);
77 }
78 }
79}
80
81/// Decodes a single Modbus RTU frame from `buf` (`len` bytes long) as a
82/// request. `buf` must contain exactly one frame - Modbus RTU has no
83/// length field of its own, so there's no trailing-bytes case to skip
84/// past the way a preamble-based protocol's decoder would.
85///
86/// On success, returns a non-NULL handle (free it with
87/// [`mbrtu_request_free`] when done) and, if `out_error` is non-NULL,
88/// writes [`MbrtuFfiError::Ok`] through it. On failure, returns NULL and,
89/// if `out_error` is non-NULL, writes the reason through it.
90///
91/// # Safety
92/// `buf` must be NULL or valid for reads of `len` bytes. `out_error` must
93/// be NULL or a pointer valid for a single write.
94#[unsafe(no_mangle)]
95pub unsafe extern "C" fn mbrtu_decode_request(
96 buf: *const u8,
97 len: usize,
98 out_error: *mut MbrtuFfiError,
99) -> *mut MbrtuFfiRequest {
100 if buf.is_null() {
101 set_error(out_error, MbrtuFfiError::NullInput);
102 return ptr::null_mut();
103 }
104 // SAFETY: caller guarantees `buf` is valid for reads of `len` bytes.
105 let bytes = unsafe { core::slice::from_raw_parts(buf, len) };
106
107 let frame = match mbrtu::Frame::parse(bytes) {
108 Ok(frame) => frame,
109 Err(e) => {
110 set_error(out_error, MbrtuFfiError::from(mbrtu::MbrtuError::from(e)));
111 return ptr::null_mut();
112 }
113 };
114 match ModbusRequest::decode(frame.function_code(), frame.data()) {
115 Ok(request) => {
116 set_error(out_error, MbrtuFfiError::Ok);
117 Box::into_raw(Box::new(MbrtuFfiRequest {
118 address: frame.address(),
119 request,
120 }))
121 }
122 Err(e) => {
123 set_error(out_error, MbrtuFfiError::from(mbrtu::MbrtuError::from(e)));
124 ptr::null_mut()
125 }
126 }
127}
128
129/// Decodes a single Modbus RTU frame from `buf` (`len` bytes long) as a
130/// response. See [`mbrtu_decode_request`] for the framing/error contract,
131/// which is otherwise identical - except that a frame with the broadcast
132/// address (`0`) is rejected with [`MbrtuFfiError::Frame`], since Modbus
133/// RTU never sends a response to a broadcast request.
134///
135/// # Safety
136/// `buf` must be NULL or valid for reads of `len` bytes. `out_error` must
137/// be NULL or a pointer valid for a single write.
138#[unsafe(no_mangle)]
139pub unsafe extern "C" fn mbrtu_decode_response(
140 buf: *const u8,
141 len: usize,
142 out_error: *mut MbrtuFfiError,
143) -> *mut MbrtuFfiResponse {
144 if buf.is_null() {
145 set_error(out_error, MbrtuFfiError::NullInput);
146 return ptr::null_mut();
147 }
148 // SAFETY: caller guarantees `buf` is valid for reads of `len` bytes.
149 let bytes = unsafe { core::slice::from_raw_parts(buf, len) };
150
151 let frame = match mbrtu::Frame::parse_response(bytes) {
152 Ok(frame) => frame,
153 Err(e) => {
154 set_error(out_error, MbrtuFfiError::from(mbrtu::MbrtuError::from(e)));
155 return ptr::null_mut();
156 }
157 };
158 match ModbusResponse::decode(frame.function_code(), frame.data()) {
159 Ok(response) => {
160 set_error(out_error, MbrtuFfiError::Ok);
161 Box::into_raw(Box::new(MbrtuFfiResponse {
162 address: frame.address(),
163 response,
164 }))
165 }
166 Err(e) => {
167 set_error(out_error, MbrtuFfiError::from(mbrtu::MbrtuError::from(e)));
168 ptr::null_mut()
169 }
170 }
171}
172
173/// Frees a handle returned by [`mbrtu_decode_request`]. Passing NULL is a
174/// no-op.
175///
176/// # Safety
177/// `req` must be NULL or a pointer previously returned by
178/// [`mbrtu_decode_request`] that has not already been freed.
179#[unsafe(no_mangle)]
180pub unsafe extern "C" fn mbrtu_request_free(req: *mut MbrtuFfiRequest) {
181 if !req.is_null() {
182 // SAFETY: caller guarantees `req` is a live handle from `mbrtu_decode_request`.
183 drop(unsafe { Box::from_raw(req) });
184 }
185}
186
187/// Frees a handle returned by [`mbrtu_decode_response`]. Passing NULL is
188/// a no-op.
189///
190/// # Safety
191/// `resp` must be NULL or a pointer previously returned by
192/// [`mbrtu_decode_response`] that has not already been freed.
193#[unsafe(no_mangle)]
194pub unsafe extern "C" fn mbrtu_response_free(resp: *mut MbrtuFfiResponse) {
195 if !resp.is_null() {
196 // SAFETY: caller guarantees `resp` is a live handle from `mbrtu_decode_response`.
197 drop(unsafe { Box::from_raw(resp) });
198 }
199}
200
201/// The request's unit/slave address, or `0` for a NULL handle.
202///
203/// # Safety
204/// `req` must be NULL or a valid, non-freed handle from [`mbrtu_decode_request`].
205#[unsafe(no_mangle)]
206pub unsafe extern "C" fn mbrtu_request_address(req: *const MbrtuFfiRequest) -> u8 {
207 // SAFETY: caller guarantees `req` is a valid handle or NULL.
208 unsafe { req.as_ref() }.map_or(0, |r| r.address)
209}
210
211/// The request's function code, or `0xFF` for a NULL handle.
212///
213/// # Safety
214/// `req` must be NULL or a valid, non-freed handle from [`mbrtu_decode_request`].
215#[unsafe(no_mangle)]
216pub unsafe extern "C" fn mbrtu_request_function_code(req: *const MbrtuFfiRequest) -> u8 {
217 // SAFETY: caller guarantees `req` is a valid handle or NULL.
218 unsafe { req.as_ref() }.map_or(0xFF, |r| r.request.function_code())
219}
220
221/// The response's unit/slave address, or `0` for a NULL handle.
222///
223/// # Safety
224/// `resp` must be NULL or a valid, non-freed handle from [`mbrtu_decode_response`].
225#[unsafe(no_mangle)]
226pub unsafe extern "C" fn mbrtu_response_address(resp: *const MbrtuFfiResponse) -> u8 {
227 // SAFETY: caller guarantees `resp` is a valid handle or NULL.
228 unsafe { resp.as_ref() }.map_or(0, |r| r.address)
229}
230
231/// The response's function code (with the high bit set for an exception
232/// response), or `0xFF` for a NULL handle.
233///
234/// # Safety
235/// `resp` must be NULL or a valid, non-freed handle from [`mbrtu_decode_response`].
236#[unsafe(no_mangle)]
237pub unsafe extern "C" fn mbrtu_response_function_code(resp: *const MbrtuFfiResponse) -> u8 {
238 // SAFETY: caller guarantees `resp` is a valid handle or NULL.
239 unsafe { resp.as_ref() }.map_or(0xFF, |r| r.response.function_code())
240}
241
242/// Read Holding Registers (function code 3) request: which registers to
243/// read.
244#[repr(C)]
245#[derive(Debug, Clone, Copy)]
246pub struct MbrtuReadHoldingRegistersRequest {
247 /// Address of the first register to read.
248 pub starting_address: u16,
249 /// Number of registers to read.
250 pub quantity: u16,
251}
252
253impl From<ReadHoldingRegistersRequest> for MbrtuReadHoldingRegistersRequest {
254 fn from(m: ReadHoldingRegistersRequest) -> Self {
255 Self {
256 starting_address: m.starting_address,
257 quantity: m.quantity,
258 }
259 }
260}
261
262/// Read Holding Registers (function code 3) response: the register
263/// values read. `registers[..count]` are meaningful; the rest are unused
264/// padding.
265#[repr(C)]
266#[derive(Debug, Clone, Copy)]
267pub struct MbrtuReadHoldingRegistersResponse {
268 /// Number of valid entries in `registers`.
269 pub count: u8,
270 /// Register values, indexed in request order.
271 pub registers: [u16; MBRTU_FFI_MAX_REGISTERS],
272}
273
274impl From<ReadHoldingRegistersResponse> for MbrtuReadHoldingRegistersResponse {
275 fn from(m: ReadHoldingRegistersResponse) -> Self {
276 Self {
277 count: m.count,
278 registers: m.registers,
279 }
280 }
281}
282
283/// Read Coils (function code 1) request: which coils to read.
284#[repr(C)]
285#[derive(Debug, Clone, Copy)]
286pub struct MbrtuReadCoilsRequest {
287 /// Address of the first coil to read.
288 pub starting_address: u16,
289 /// Number of coils to read.
290 pub quantity: u16,
291}
292
293impl From<ReadCoilsRequest> for MbrtuReadCoilsRequest {
294 fn from(m: ReadCoilsRequest) -> Self {
295 Self {
296 starting_address: m.starting_address,
297 quantity: m.quantity,
298 }
299 }
300}
301
302/// Read Coils (function code 1) response: the coil values read, packed
303/// one bit per coil (LSB of `bits[0]` is the first requested coil).
304/// `bits[..byte_count]` are meaningful.
305#[repr(C)]
306#[derive(Debug, Clone, Copy)]
307pub struct MbrtuReadCoilsResponse {
308 /// Number of valid bytes in `bits`.
309 pub byte_count: u8,
310 /// Packed coil bits.
311 pub bits: [u8; MBRTU_FFI_MAX_COIL_BYTES],
312}
313
314impl From<ReadCoilsResponse> for MbrtuReadCoilsResponse {
315 fn from(m: ReadCoilsResponse) -> Self {
316 Self {
317 byte_count: m.byte_count,
318 bits: m.bits,
319 }
320 }
321}
322
323/// Write Single Register (function code 6) request or response - the two
324/// share an identical wire shape (the response echoes the confirmed
325/// address and value).
326#[repr(C)]
327#[derive(Debug, Clone, Copy)]
328pub struct MbrtuWriteSingleRegister {
329 /// Address of the register written.
330 pub address: u16,
331 /// Value written.
332 pub value: u16,
333}
334
335impl From<WriteSingleRegister> for MbrtuWriteSingleRegister {
336 fn from(m: WriteSingleRegister) -> Self {
337 Self {
338 address: m.address,
339 value: m.value,
340 }
341 }
342}
343
344/// An exception response: the function code that failed (high bit
345/// already cleared) and why.
346#[repr(C)]
347#[derive(Debug, Clone, Copy)]
348pub struct MbrtuExceptionResponse {
349 /// The function code that failed (e.g. `0x03`, not `0x83`).
350 pub function_code: u8,
351 /// Raw exception code (see the Modbus Application Protocol
352 /// specification, section 7, for the standard meanings).
353 pub exception_code: u8,
354}
355
356impl From<ExceptionResponse> for MbrtuExceptionResponse {
357 fn from(m: ExceptionResponse) -> Self {
358 Self {
359 function_code: m.function_code,
360 exception_code: m.exception_code.into(),
361 }
362 }
363}
364
365/// Reads `req`'s request as Read Holding Registers into `out`, returning
366/// `true` on a match. Returns `false` without writing to `out` if `req`
367/// is NULL or holds a different function code.
368///
369/// # Safety
370/// `req` must be NULL or a valid, non-freed handle from [`mbrtu_decode_request`].
371/// `out` must be a valid write target.
372#[unsafe(no_mangle)]
373pub unsafe extern "C" fn mbrtu_request_as_read_holding_registers(
374 req: *const MbrtuFfiRequest,
375 out: *mut MbrtuReadHoldingRegistersRequest,
376) -> bool {
377 // SAFETY: caller guarantees `req` is a valid handle or NULL.
378 let Some(r) = (unsafe { req.as_ref() }) else {
379 return false;
380 };
381 let ModbusRequest::ReadHoldingRegisters(inner) = r.request else {
382 return false;
383 };
384 // SAFETY: caller guarantees `out` is a valid write target.
385 unsafe {
386 out.write(inner.into());
387 }
388 true
389}
390
391/// Reads `req`'s request as Read Coils into `out`, returning `true` on a
392/// match. Returns `false` without writing to `out` if `req` is NULL or
393/// holds a different function code.
394///
395/// # Safety
396/// `req` must be NULL or a valid, non-freed handle from [`mbrtu_decode_request`].
397/// `out` must be a valid write target.
398#[unsafe(no_mangle)]
399pub unsafe extern "C" fn mbrtu_request_as_read_coils(
400 req: *const MbrtuFfiRequest,
401 out: *mut MbrtuReadCoilsRequest,
402) -> bool {
403 // SAFETY: caller guarantees `req` is a valid handle or NULL.
404 let Some(r) = (unsafe { req.as_ref() }) else {
405 return false;
406 };
407 let ModbusRequest::ReadCoils(inner) = r.request else {
408 return false;
409 };
410 // SAFETY: caller guarantees `out` is a valid write target.
411 unsafe {
412 out.write(inner.into());
413 }
414 true
415}
416
417/// Reads `req`'s request as Write Single Register into `out`, returning
418/// `true` on a match. Returns `false` without writing to `out` if `req`
419/// is NULL or holds a different function code.
420///
421/// # Safety
422/// `req` must be NULL or a valid, non-freed handle from [`mbrtu_decode_request`].
423/// `out` must be a valid write target.
424#[unsafe(no_mangle)]
425pub unsafe extern "C" fn mbrtu_request_as_write_single_register(
426 req: *const MbrtuFfiRequest,
427 out: *mut MbrtuWriteSingleRegister,
428) -> bool {
429 // SAFETY: caller guarantees `req` is a valid handle or NULL.
430 let Some(r) = (unsafe { req.as_ref() }) else {
431 return false;
432 };
433 let ModbusRequest::WriteSingleRegister(inner) = r.request else {
434 return false;
435 };
436 // SAFETY: caller guarantees `out` is a valid write target.
437 unsafe {
438 out.write(inner.into());
439 }
440 true
441}
442
443/// Reads `resp`'s response as Read Holding Registers into `out`,
444/// returning `true` on a match. Returns `false` without writing to `out`
445/// if `resp` is NULL or holds a different function code.
446///
447/// # Safety
448/// `resp` must be NULL or a valid, non-freed handle from [`mbrtu_decode_response`].
449/// `out` must be a valid write target.
450#[unsafe(no_mangle)]
451pub unsafe extern "C" fn mbrtu_response_as_read_holding_registers(
452 resp: *const MbrtuFfiResponse,
453 out: *mut MbrtuReadHoldingRegistersResponse,
454) -> bool {
455 // SAFETY: caller guarantees `resp` is a valid handle or NULL.
456 let Some(r) = (unsafe { resp.as_ref() }) else {
457 return false;
458 };
459 let ModbusResponse::ReadHoldingRegisters(inner) = r.response else {
460 return false;
461 };
462 // SAFETY: caller guarantees `out` is a valid write target.
463 unsafe {
464 out.write(inner.into());
465 }
466 true
467}
468
469/// Reads `resp`'s response as Read Coils into `out`, returning `true` on
470/// a match. Returns `false` without writing to `out` if `resp` is NULL or
471/// holds a different function code.
472///
473/// # Safety
474/// `resp` must be NULL or a valid, non-freed handle from [`mbrtu_decode_response`].
475/// `out` must be a valid write target.
476#[unsafe(no_mangle)]
477pub unsafe extern "C" fn mbrtu_response_as_read_coils(
478 resp: *const MbrtuFfiResponse,
479 out: *mut MbrtuReadCoilsResponse,
480) -> bool {
481 // SAFETY: caller guarantees `resp` is a valid handle or NULL.
482 let Some(r) = (unsafe { resp.as_ref() }) else {
483 return false;
484 };
485 let ModbusResponse::ReadCoils(inner) = r.response else {
486 return false;
487 };
488 // SAFETY: caller guarantees `out` is a valid write target.
489 unsafe {
490 out.write(inner.into());
491 }
492 true
493}
494
495/// Reads `resp`'s response as Write Single Register into `out`, returning
496/// `true` on a match. Returns `false` without writing to `out` if `resp`
497/// is NULL or holds a different function code.
498///
499/// # Safety
500/// `resp` must be NULL or a valid, non-freed handle from [`mbrtu_decode_response`].
501/// `out` must be a valid write target.
502#[unsafe(no_mangle)]
503pub unsafe extern "C" fn mbrtu_response_as_write_single_register(
504 resp: *const MbrtuFfiResponse,
505 out: *mut MbrtuWriteSingleRegister,
506) -> bool {
507 // SAFETY: caller guarantees `resp` is a valid handle or NULL.
508 let Some(r) = (unsafe { resp.as_ref() }) else {
509 return false;
510 };
511 let ModbusResponse::WriteSingleRegister(inner) = r.response else {
512 return false;
513 };
514 // SAFETY: caller guarantees `out` is a valid write target.
515 unsafe {
516 out.write(inner.into());
517 }
518 true
519}
520
521/// Reads `resp`'s response as an exception into `out`, returning `true`
522/// on a match. Returns `false` without writing to `out` if `resp` is NULL
523/// or holds a normal (non-exception) response.
524///
525/// # Safety
526/// `resp` must be NULL or a valid, non-freed handle from [`mbrtu_decode_response`].
527/// `out` must be a valid write target.
528#[unsafe(no_mangle)]
529pub unsafe extern "C" fn mbrtu_response_as_exception(
530 resp: *const MbrtuFfiResponse,
531 out: *mut MbrtuExceptionResponse,
532) -> bool {
533 // SAFETY: caller guarantees `resp` is a valid handle or NULL.
534 let Some(r) = (unsafe { resp.as_ref() }) else {
535 return false;
536 };
537 let ModbusResponse::Exception(inner) = r.response else {
538 return false;
539 };
540 // SAFETY: caller guarantees `out` is a valid write target.
541 unsafe {
542 out.write(inner.into());
543 }
544 true
545}
546
547/// This crate's version string, as a NUL-terminated C string with static
548/// lifetime.
549#[unsafe(no_mangle)]
550pub extern "C" fn mbrtu_version() -> *const c_char {
551 const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
552 VERSION.as_ptr().cast::<c_char>()
553}