libmodbus-rs 0.4.3

Binding to libmodbus. Libmodbus is a free software library to send/receive data with a device which respects the Modbus protocol. This library can use a serial port or an Ethernet connection. http://libmodbus.org/
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
use enums::ErrorRecoveryMode;
use errors::*;
use libc::{c_int, c_uint};
use libmodbus_sys;
use std::io::Error;


/// Safe interface for [libmodbus](http://libmodbus.org)
///
/// The different parts of libmodbus are implemented as traits. The modules of this crate contains these
/// traits and a implementation with a, hopefully safe, interface.
///
pub struct Modbus {
    pub ctx: *mut libmodbus_sys::modbus_t,
}

impl Modbus {
    /// `connect` - establish a Modbus connection
    ///
    /// The [`connect()`](#method.connect) function shall establish a connection to a Modbus server,
    /// a network or a bus.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// assert!(modbus.connect().is_ok())
    /// ```
    pub fn connect(&self) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_connect(self.ctx) {
                -1 => bail!(Error::last_os_error()),
                _ => Ok(0),
            }
        }
    }

    /// `flush` - flush non-transmitted data
    /// The [`flush()`](#method.flush) function shall discard data received but not read to the socket or file
    /// descriptor associated to the context ctx.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Examples
    ///
    /// ```
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// assert!(modbus.flush().is_ok());
    /// ```
    pub fn flush(&self) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_flush(self.ctx) {
                -1 => bail!(Error::last_os_error()),
                _ => Ok(0),
            }
        }
    }

    /// `set_slave` - set slave number in the context
    ///
    /// The [`set_slave()`](#method.set_slave) function shall set the slave number in the libmodbus context.
    /// The behavior depends of network and the role of the device:
    ///
    /// RTU
    ///     Define the slave ID of the remote device to talk in master mode or set the internal slave ID in slave mode.
    /// According to the protocol, a Modbus device must only accept message holding its slave number or the special
    /// broadcast number.
    /// TCP
    ///     The slave number is only required in TCP if the message must reach a device on a serial network.
    ///     Some not compliant devices or software (such as modpoll) uses the slave ID as unit identifier,
    ///     that’s incorrect (cf page 23 of Modbus Messaging Implementation Guide v1.0b) but without the slave value,
    ///     the faulty remote device or software drops the requests!
    ///     The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to restore the default value.
    ///     The broadcast address is MODBUS_BROADCAST_ADDRESS.
    ///     This special value must be use when you want all Modbus devices of the network receive the request.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Parameters
    ///
    /// * `slave`   - new slave ID
    ///
    /// # Examples
    ///
    /// ```
    /// use libmodbus_rs::{Modbus, ModbusRTU};
    ///
    /// const YOUR_DEVICE_ID: u8 = 1;
    /// let mut modbus = Modbus::new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1).unwrap();
    ///
    /// assert!(modbus.set_slave(YOUR_DEVICE_ID).is_ok());
    /// ```
    pub fn set_slave(&mut self, slave: u8) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_set_slave(self.ctx, slave as c_int) {
                -1 => bail!(Error::last_os_error()),
                _ => Ok(0),
            }
        }
    }

    /// `set_debug` - set debug flag of the context
    ///
    /// The [`set_debug()`](#method.set_debug) function shall set the debug flag of the modbus_t context by using the
    /// argument flag.
    /// By default, the boolean flag is set to FALSE. When the flag value is set to TRUE, many verbose messages are
    /// displayed on stdout and stderr.
    /// For example, this flag is useful to display the bytes of the Modbus messages.
    ///
    /// ```bash
    /// [00][14][00][00][00][06][12][03][00][6B][00][03]
    /// Waiting for a confirmation…
    /// <00><14><00><00><00><09><12><03><06><02><2B><00><00><00><00>
    /// ```
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Parameters
    ///
    /// * `flag`    - `true` of `false`, enables or disables debug mode
    ///
    /// # Examples
    ///
    /// ```
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    ///
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// assert!(modbus.set_debug(true).is_ok());
    /// ```
    pub fn set_debug(&mut self, flag: bool) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_set_debug(self.ctx, flag as c_int) {
                -1 => bail!(Error::last_os_error()),
                _ => Ok(0),
            }
        }
    }

    /// `get_byte_timeout` - get timeout between bytes
    ///
    /// [`get_byte_timeout()`](#method.get_byte_timeout) function returns a tupple with the timeout interval between
    /// two consecutive bytes of the same message `Result<(timeout_sec, timeout_usec)>`.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Parameters
    ///
    /// * `timeout_sec`  - timeout sec
    /// * `timeout_usec` - timeout usec
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// let mut timeout_sec = 0;
    /// let mut timeout_usec = 0;
    ///
    /// assert!(modbus.get_byte_timeout(&mut timeout_sec, &mut timeout_usec).is_ok());
    /// ```
    pub fn get_byte_timeout(&self, timeout_sec: *mut u32, timeout_usec: *mut u32) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_get_byte_timeout(self.ctx, timeout_sec, timeout_usec) {
                -1 => bail!(Error::last_os_error()),
                0 => Ok(0),
                _ => unreachable!(),
            }
        }
    }

    /// `set_byte_timeout` - set timeout between bytes
    ///
    /// The [`set_byte_timeout()`](#method.set_byte_timeout) function shall set the timeout interval between two
    /// consecutive bytes of the same message.
    /// The timeout is an upper bound on the amount of time elapsed before select() returns, if the time elapsed is
    /// longer than the defined timeout,
    /// an ETIMEDOUT error will be raised by the function waiting for a response.
    ///
    /// The value of **timeout_usec** argument must be in the range 0 to 999999.
    ///
    /// If both **timeout_sec** and **timeout_usec** are zero, this timeout will not be used at all. In this case,
    /// [`set_byte_timeout()`](#method.set_byte_timeout)
    /// governs the entire handling of the response, the full confirmation response must be received before expiration
    /// of the response timeout.
    /// When a byte timeout is set, the response timeout is only used to wait for until the first byte of the response.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Parameters
    ///
    /// * `timeout_sec`  - timeout sec
    /// * `timeout_usec` - timeout usec
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// let timeout_sec = 1;
    /// let timeout_usec = 500;
    ///
    /// assert!(modbus.set_byte_timeout(timeout_sec, timeout_usec).is_ok());
    /// ```
    pub fn set_byte_timeout(&mut self, timeout_sec: u32, timeout_usec: u32) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_set_byte_timeout(self.ctx, timeout_sec, timeout_usec) {
                -1 => bail!(Error::last_os_error()),
                0 => Ok(0),
                _ => unreachable!(),
            }
        }
    }

    /// `get_response_timeout` - get timeout for response
    ///
    /// The [`get_response_timeout()`](#method.get_response_timeout) function shall return the timeout interval used to
    /// wait for a response
    /// in the **timeout_sec** and **timeout_usec** arguments.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Parameters
    ///
    /// * `timeout_sec`  - timeout sec
    /// * `timeout_usec` - timeout usec
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// let mut timeout_sec = 0;
    /// let mut timeout_usec = 0;
    ///
    /// assert!(modbus.get_response_timeout(&mut timeout_sec, &mut timeout_usec).is_ok());
    /// ```
    pub fn get_response_timeout(&self, timeout_sec: *mut u32, timeout_usec: *mut u32) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_get_response_timeout(self.ctx, timeout_sec, timeout_usec) {
                -1 => bail!(Error::last_os_error()),
                0 => Ok(0),
                _ => unreachable!(),
            }
        }
    }

    /// `set_response_timeout` - set timeout for response
    ///
    /// The [`set_response_timeout()`](#method.set_response_timeout) function shall set the timeout interval used to
    /// wait for a response.
    /// When a byte timeout is set, if elapsed time for the first byte of response is longer than the given timeout,
    /// an ETIMEDOUT error will be raised by the function waiting for a response. When byte timeout is disabled,
    /// the full confirmation response must be received before expiration of the response timeout.
    ///
    /// The value of **timeout_usec** argument must be in the range 0 to 999999.
    ///
    /// If both **timeout_sec** and **timeout_usec** are zero, this timeout will not be used at all. In this case,
    /// [`set_response_timeout()`](#method.set_response_timeout)
    /// governs the entire handling of the response, the full confirmation response must be received before expiration
    /// of the response timeout.
    /// When a byte timeout is set, the response timeout is only used to wait for until the first byte of the response.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Parameters
    ///
    /// * `timeout_sec`  - timeout sec
    /// * `timeout_usec` - timeout usec
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// let timeout_sec = 1;
    /// let timeout_usec = 500;
    ///
    /// assert!(modbus.set_response_timeout(timeout_sec, timeout_usec).is_ok());
    /// ```
    pub fn set_response_timeout(&mut self, timeout_sec: u32, timeout_usec: u32) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_set_response_timeout(self.ctx, timeout_sec, timeout_usec) {
                -1 => bail!(Error::last_os_error()),
                0 => Ok(0),
                _ => unreachable!(),
            }
        }
    }

    /// `set_error_recovery` - set the error recovery mode
    ///
    /// The [`set_error_recovery()`](#method.set_error_recovery) function shall set the error recovery mode to apply
    /// when the connection fails or
    /// the byte received is not expected. The argument error_recovery may be bitwise-or’ed with zero or more of the
    /// following constants.
    ///
    /// By default there is no error recovery (MODBUS_ERROR_RECOVERY_NONE) so the application is responsible for
    /// controlling the error values
    /// returned by libmodbus functions and for handling them if necessary.
    ///
    /// When MODBUS_ERROR_RECOVERY_LINK is set, the library will attempt an reconnection after a delay defined by
    /// response timeout of the libmodbus context.
    /// This mode will try an infinite close/connect loop until success on send call and will just try one time to
    /// re-establish the connection on
    /// select/read calls (if the connection was down, the values to read are certainly not available any more after
    /// reconnection, except for slave/server).
    /// This mode will also run flush requests after a delay based on  the current response timeout in some situations
    /// (eg. timeout of select call).
    /// The reconnection attempt can hang for several seconds if the network to the remote target unit is down.
    ///
    /// When MODBUS_ERROR_RECOVERY_PROTOCOL is set, a sleep and flush sequence will be used to clean up the ongoing
    /// communication, this can
    /// occurs when the message length is invalid, the TID is wrong or the received function code is not the expected
    /// one.
    /// The response timeout delay will be used to sleep.
    ///
    /// The modes are mask values and so they are complementary.
    ///
    /// It’s not recommended to enable error recovery for slave/server.
    ///
    /// # Return value
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    /// The C library sets errno to one of the values of [ErrorRecoveryMode]().
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use libmodbus_rs::{Modbus, ModbusTCP, ErrorRecoveryMode};
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// //assert!(modbus.set_error_recovery(ErrorRecoveryMode::LINK | ErrorRecoveryMode::PROTOCOL))
    /// ```
    pub fn set_error_recovery(&mut self, error_recovery_mode: ErrorRecoveryMode)
                              -> Result<i32>
    {
        unimplemented!()
        // unsafe {
        //     let error_recovery_mode = error_recovery_mode;
        //     match libmodbus_sys::modbus_set_error_recovery(self.ctx, error_recovery_mode.into()) {
        //         -1 => bail!(Error::last_os_error()),
        //         0 => Ok(0),
        //         _ => unreachable!(),
        //     }
        // }
    }

    // TODO: Add examples from: http://zzeroo.github.io/libmodbus-rs/libmodbus/modbus_set_socket.html
    /// `set_socket` - set socket of the context
    ///
    /// The [`set_socket()`](#method.set_socket) function shall set the socket or file descriptor in the libmodbus
    /// context.
    /// This function is useful for managing multiple client connections to the same server.
    ///
    /// # Return values
    ///
    /// The function return a Result containing a `0i32` if successful. Otherwise it contains an Error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// assert_eq!(modbus.set_socket(1337).unwrap(), 0);
    /// ```
    pub fn set_socket(&mut self, socket: i32) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_set_socket(self.ctx, socket) {
                -1 => bail!(Error::last_os_error()),
                0 => Ok(0),
                _ => unreachable!(),
            }
        }
    }

    /// `get_socket` - set socket of the context
    ///
    /// The [`get_socket()`](#method.get_socket) function shall return the current socket or file descriptor of the
    /// libmodbus context.
    ///
    /// # Return value
    ///
    /// The function returns a Result containing the current socket or file descriptor of the context if successful. Otherwise it contains an Error.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// let socket = modbus.get_socket().unwrap();
    /// ```
    pub fn get_socket(&self) -> Result<i32> {
        unsafe {
            match libmodbus_sys::modbus_get_socket(self.ctx) {
                -1 => bail!(Error::last_os_error()),
                socket => Ok(socket),
            }
        }
    }

    /// `get_header_length` - retrieve the current header length
    ///
    /// The [`get_header_length()`](#method.get_header_length) function shall retrieve the current header length from
    /// the backend.
    /// This function is convenient to manipulate a message and so its limited to low-level operations.
    ///
    /// # Return values
    ///
    /// The header length as integer value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    /// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    /// assert_eq!(modbus.get_header_length(), 7);
    /// ```
    pub fn get_header_length(&self) -> i32 {
        unsafe {
            libmodbus_sys::modbus_get_header_length(self.ctx)
        }
    }

    /// `close` - close a Modbus connection
    ///
    /// The [`close()`](#method.close) function shall close the connection established with the backend set in the
    /// context.
    ///
    /// **It should not nessesary to call these function. Because rusts drop trait handles that for you!**
    ///
    /// # Examples
    ///
    /// ```
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    ///
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// match modbus.connect() {
    ///     Ok(_) => {  }
    ///     Err(e) => println!("Error: {}", e),
    /// }
    ///
    /// modbus.close();
    /// modbus.free();
    /// ```
    pub fn close(&self) {
        unsafe {
            libmodbus_sys::modbus_close(self.ctx);
        }
    }

    /// `free` - free a libmodbus context
    ///
    /// The [`free()`](#method.free) function shall free an allocated modbus_t structure.
    ///
    /// **It should not nessesary to call these function. Because rusts drop trait handles that for you!**
    ///
    /// # Examples
    ///
    /// ```
    /// use libmodbus_rs::{Modbus, ModbusTCP};
    ///
    /// let mut modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
    ///
    /// match modbus.connect() {
    ///     Ok(_) => {  }
    ///     Err(e) => println!("Error: {}", e),
    /// }
    ///
    /// modbus.close();
    /// modbus.free();
    /// ```
    pub fn free(&mut self) {
        unsafe {
            libmodbus_sys::modbus_free(self.ctx);
        }
    }
}

/// `set_bits_from_byte` - set many bits from a single byte value
///
/// The [`set_bits_from_byte()`](#method.set_bits_from_byte) function shall set many bits from a single byte.
/// All 8 bits from the byte value will be written to dest array starting at index position.
///
/// # Parameters
///
/// `dest` - destination slice
/// `index` - starting position where the bit should written
/// `value` - set many bits from a single byte. All 8 bits from the byte `value` will be written to `dest` slice starting at `index` position.
///
/// # Examples
///
/// ```rust
/// use libmodbus_rs::{Modbus, ModbusMapping, ModbusTCP};
/// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
/// let modbus_mapping = ModbusMapping::new(5, 5, 5, 5).unwrap();
///
/// assert_eq!(modbus_mapping.get_input_bits_mut(), [0u8, 0, 0, 0, 0]);
/// libmodbus_rs::set_bits_from_byte(modbus_mapping.get_input_bits_mut(), 2, 0b1111_1111);
/// assert_eq!(modbus_mapping.get_input_bits_mut(), [0u8, 0, 1, 1, 1]);
/// ```
pub fn set_bits_from_byte(dest: &mut [u8], index: u32, value: u8) {
    unsafe {
        libmodbus_sys::modbus_set_bits_from_byte(dest.as_mut_ptr(), index as c_int, value)
    }
}

/// `set_bits_from_bytes` -  set many bits from an array of bytes
///
/// The [`set_bits_from_bytes()`](#method.set_bits_from_bytes) function shall set many bits from a single byte.
/// All 8 bits from the byte value will be written to dest array starting at index position.
///
/// # Parameters
///
/// `dest` - destination slice
/// `index` - starting position where the bit should written
/// `num_bit`   - how many bits should written
/// `bytes` - All the bits of the `bytes` parameter, read from the first position of the vec `bytes` are written as bits in the `dest` vec,
///     starting at position `index`
///
/// # Examples
///
/// ```rust
/// use libmodbus_rs::{Modbus, ModbusMapping, ModbusTCP};
/// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
/// let modbus_mapping = ModbusMapping::new(5, 5, 5, 5).unwrap();
///
/// assert_eq!(modbus_mapping.get_input_bits_mut(), [0u8, 0, 0, 0, 0]);
/// libmodbus_rs::set_bits_from_bytes(modbus_mapping.get_input_bits_mut(), 0, 2, &[0b0000_1111]);
/// assert_eq!(modbus_mapping.get_input_bits_mut(), [1u8, 1, 0, 0, 0]);
/// ```
pub fn set_bits_from_bytes(dest: &mut [u8], index: u32, num_bit: u16, bytes: &[u8]) {
    unsafe {
        libmodbus_sys::modbus_set_bits_from_bytes(dest.as_mut_ptr(), index as c_int, num_bit as c_uint, bytes.as_ptr())
    }
}

/// `get_byte_from_bits` - get the value from many bit
///
/// The [`get_byte_from_bits()`](#method.get_byte_from_bits) function shall extract a value from many bits.
/// All num_bit bits from src at position index will be read as a single value. To obtain a full byte, set num_bit to 8.
///
/// # Return value
///
/// The function shall return a byte containing the bits read.
///
/// # Parameters
///
/// `src`       - bits source
/// `index`     - starting position where the bit will be read
/// `num_bit`   - All `num_bit` bits from `src` at position `index` will be read as a single value. To obtain a full byte, set `num_bit` to 8.
///
/// # Examples
///
/// ```rust
/// use libmodbus_rs::{Modbus, ModbusMapping, ModbusTCP};
/// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap();
/// let modbus_mapping = ModbusMapping::new(5, 5, 5, 5).unwrap();
///
/// assert_eq!(libmodbus_rs::get_byte_from_bits(&[0b1111_1111], 0 ,8), 255);
/// ```
pub fn get_byte_from_bits(src: &[u8], index: u8, num_bit: u8) -> u8 {
    unsafe {
        libmodbus_sys::modbus_get_byte_from_bits(src.as_ptr(), index as c_int, num_bit as c_uint)
    }
}

/// `get_float_abcd` - get a float value from 2 registers in ABCD byte order
///
/// The [`get_float_abcd()`](#method.get_float_abcd) function shall get a float from 4 bytes in usual Modbus format.
/// The src slice mut contain two 16 bits values, for example, if the first word is set to 0x0020 and the
/// second to 0xF147, the float value will be read as 123456.0.
///
/// # Return value
///
/// The function shall return a float.
///
/// # Parameters
///
/// `src`   - slice of two 16 bits values
///
/// # Examples
///
/// ```rust
/// assert_eq!(libmodbus_rs::get_float_abcd(&[0x0020, 0xF147]), 123456.0);
/// ```
pub fn get_float_abcd(src: &[u16; 2]) -> f32 {
    unsafe {
        libmodbus_sys::modbus_get_float_abcd(src.as_ptr())
    }
}

/// `set_float_abcd` - set a float value in 2 registers using ABCD byte order
///
/// The [`set_float_abcd()`](#method.set_float_abcd) function shall set a float to 4 bytes in usual Modbus format.
/// The dest slice must contain two 16 bits values to be able to store the full result of the conversion.
///
/// # Parameters
///
/// `src`   - float to 4 bytes (f32)
/// `dest`  - slice must contain two 16 bits values
///
/// # Examples
///
/// ```rust
/// let mut dest = vec![0; 2];
/// libmodbus_rs::set_float_abcd(123456.0, &mut dest);
/// assert_eq!(&dest, &[0x0020, 0xF147]);
/// ```
pub fn set_float_abcd(src: f32, dest: &mut [u16]) { // &mut [u16; 2] is not working here
    unsafe {
        libmodbus_sys::modbus_set_float_abcd(src, dest.as_mut_ptr())
    }
}

/// `get_float_badc` - get a float value from 2 registers in BADC byte order
///
/// The [`get_float_badc()`](#method.get_float_badc) function shall get a float from 4 bytes with swapped bytes (BADC instead of ABCD).
/// The src slice mut contain two 16 bits values, for example, if the first word is set to 0x2000 and the second to 0x47F1,
/// the float value will be read as 123456.0.
///
/// # Return value
///
/// The function shall return a float.
///
/// # Parameters
///
/// `src`   - slice of two 16 bits values
///
/// # Examples
///
/// ```rust
/// assert_eq!(libmodbus_rs::get_float_badc(&[0x2000, 0x47F1]), 123456.0);
/// ```
pub fn get_float_badc(src: &[u16; 2]) -> f32 {
    unsafe {
        libmodbus_sys::modbus_get_float_badc(src.as_ptr())
    }
}

/// `set_float_badc` - set a float value in 2 registers using BADC byte order
///
/// The [`set_float_badc()`](#method.set_float_badc) function shall set a float to 4 bytes in swapped bytes Modbus format (BADC insted of ABCD).
/// The dest slice must contain two 16 bits values to be able to store the full result of the conversion.
///
/// # Parameters
///
/// `src`   - float to 4 bytes (f32)
/// `dest`  - slice must contain two 16 bits values
///
/// # Examples
///
/// ```rust
/// let mut dest = vec![0; 2];
/// libmodbus_rs::set_float_badc(123456.0, &mut dest);
/// assert_eq!(&dest, &[0x2000, 0x47F1]);
/// ```
pub fn set_float_badc(src: f32, dest: &mut [u16]) { // &mut [u16; 2] is not working here
    unsafe {
        libmodbus_sys::modbus_set_float_badc(src, dest.as_mut_ptr())
    }
}

/// `get_float_cdab` - get a float value from 2 registers in CDAB byte order
///
/// The [`get_float_cdab()`](#method.get_float_cdab) function shall get a float from 4 bytes with swapped bytes (CDAB instead of ABCD).
/// The src slice mut contain two 16 bits values, for example, if the first word is set to 0x2000 and the second to 0x47F1,
/// the float value will be read as 123456.0.
///
/// # Return value
///
/// The function shall return a float.
///
/// # Parameters
///
/// `src`   - slice of two 16 bits values
///
/// # Examples
///
/// ```rust
/// assert_eq!(libmodbus_rs::get_float_cdab(&[0xF147, 0x0020]), 123456.0);
/// ```
pub fn get_float_cdab(src: &[u16; 2]) -> f32 {
    unsafe {
        libmodbus_sys::modbus_get_float_cdab(src.as_ptr())
    }
}

/// `set_float_cdab` - set a float value in 2 registers using CDAB byte order
///
/// The [`set_float_cdab()`](#method.set_float_cdab) function shall set a float to 4 bytes in swapped bytes Modbus format (CDAB insted of ABCD).
/// The dest slice must contain two 16 bits values to be able to store the full result of the conversion.
///
/// # Parameters
///
/// `src`   - float to 4 bytes (f32)
/// `dest`  - slice must contain two 16 bits values
///
/// # Examples
///
/// ```rust
/// let mut dest = vec![0; 2];
/// libmodbus_rs::set_float_cdab(123456.0, &mut dest);
/// assert_eq!(&dest, &[0xF147, 0x0020]);
/// ```
pub fn set_float_cdab(src: f32, dest: &mut [u16]) { // &mut [u16; 2] is not working here
    unsafe {
        libmodbus_sys::modbus_set_float_cdab(src, dest.as_mut_ptr())
    }
}

/// `get_float_dcba` - get a float value from 2 registers in DCBA byte order
///
/// The [`get_float_dcba()`](#method.get_float_dcba) function shall get a float from 4 bytes with swapped bytes (DCBA instead of ABCD).
/// The src slice mut contain two 16 bits values, for example, if the first word is set to 0x2000 and the second to 0x47F1,
/// the float value will be read as 123456.0.
///
/// # Return value
///
/// The function shall return a float.
///
/// # Parameters
///
/// `src`   - slice of two 16 bits values
///
/// # Examples
///
/// ```rust
/// assert_eq!(libmodbus_rs::get_float_dcba(&[0x47F1, 0x2000]), 123456.0);
/// ```
pub fn get_float_dcba(src: &[u16; 2]) -> f32 {
    unsafe {
        libmodbus_sys::modbus_get_float_dcba(src.as_ptr())
    }
}

/// `set_float_dcba` - set a float value in 2 registers using DCBA byte order
///
/// The [`set_float_dcba()`](#method.set_float_dcba) function shall set a float to 4 bytes in swapped bytes Modbus format (DCBA insted of ABCD).
/// The dest slice must contain two 16 bits values to be able to store the full result of the conversion.
///
/// # Parameters
///
/// `src`   - float to 4 bytes (f32)
/// `dest`  - slice must contain two 16 bits values
///
/// # Examples
///
/// ```rust
/// let mut dest = vec![0; 2];
/// libmodbus_rs::set_float_dcba(123456.0, &mut dest);
/// assert_eq!(&dest, &[0x47F1, 0x2000]);
/// ```
pub fn set_float_dcba(src: f32, dest: &mut [u16]) { // &mut [u16; 2] is not working here
    unsafe {
        libmodbus_sys::modbus_set_float_dcba(src, dest.as_mut_ptr())
    }
}


impl Drop for Modbus {
    fn drop(&mut self) {
        self.close();
        self.free();
    }
}