icsneoc2 0.1002002.0-rc.4

High-level Rust interface for Intrepid Control Systems vehicle network adapters
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
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
//! Device discovery, connection, and communication.
//!
//! [`Device`] is the central type in this crate. It wraps an opaque C
//! library handle and exposes methods for opening, configuring, and
//! communicating with Intrepid Control Systems hardware over CAN, CAN FD,
//! LIN, Ethernet, and other automotive networks.
//!
//! # Lifecycle
//!
//! ```no_run
//! use icsneoc2::{Device, OpenOptions};
//!
//! // Discover and open the first connected device
//! let device = Device::open_first(0, OpenOptions::DEFAULT)?;
//! println!("{}", device.description()?);
//!
//! // Device is automatically closed and freed on drop.
//! # Ok::<(), icsneoc2::Error>(())
//! ```

use std::ffi::CString;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::sync::Arc;

use crate::enums::OpenOptions;
use crate::sys::icsneoc2_device_t;
use crate::sys::{self, icsneoc2_message_t};

use crate::error::{Error, Result};
use crate::event::Event;
use crate::functions::{api_error, check, ffi_string};
use crate::message::Message;
use crate::settings::Settings;

// ---------------------------------------------------------------------------
// DeviceInfoList — owned linked list returned by Device::enumerate
// ---------------------------------------------------------------------------

/// Owns the linked list of found devices returned by `Device::enumerate`.
/// Freed automatically on drop via `icsneoc2_enumeration_free`.
pub struct DeviceInfoList {
    head: *mut sys::icsneoc2_device_info_t,
}

unsafe impl Send for DeviceInfoList {}

impl Drop for DeviceInfoList {
    fn drop(&mut self) {
        if !self.head.is_null() {
            unsafe { sys::icsneoc2_enumeration_free(self.head) };
        }
    }
}

impl DeviceInfoList {
    pub fn iter(&self) -> DeviceInfoIter<'_> {
        DeviceInfoIter {
            current: self.head,
            _phantom: PhantomData,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.head.is_null()
    }
}

impl<'a> IntoIterator for &'a DeviceInfoList {
    type Item = DeviceInfo<'a>;
    type IntoIter = DeviceInfoIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over a [`DeviceInfoList`].
pub struct DeviceInfoIter<'a> {
    current: *mut sys::icsneoc2_device_info_t,
    _phantom: PhantomData<&'a DeviceInfoList>,
}

impl<'a> Iterator for DeviceInfoIter<'a> {
    type Item = DeviceInfo<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.current.is_null() {
            return None;
        }
        let info = DeviceInfo {
            ptr: self.current,
            _phantom: PhantomData,
        };
        self.current = unsafe { sys::icsneoc2_device_info_next(self.current) };
        Some(info)
    }
}

/// A reference to one node in a [`DeviceInfoList`].
pub struct DeviceInfo<'a> {
    ptr: *mut sys::icsneoc2_device_info_t,
    _phantom: PhantomData<&'a DeviceInfoList>,
}

impl<'a> DeviceInfo<'a> {
    pub(crate) fn as_ptr(&self) -> *mut sys::icsneoc2_device_info_t {
        self.ptr
    }

    /// Serial number string (e.g. `"RS2043"`).
    pub fn serial(&self) -> Result<String> {
        ffi_string(64, |buf, len| unsafe {
            sys::icsneoc2_device_info_serial_get(self.ptr, buf, len)
        })
    }

    /// Raw device type discriminant.
    pub fn device_type(&self) -> Result<sys::Devicetype> {
        let mut raw: sys::icsneoc2_devicetype_t = 0;
        check(unsafe { sys::icsneoc2_device_info_type_get(self.ptr, &raw mut raw) })?;
        Ok(sys::Devicetype::try_from(raw)?)
    }

    /// Human-readable device type name (e.g. `"neoVI FIRE 3"`).
    pub fn device_type_name(&self) -> Result<String> {
        ffi_string(64, |buf, len| unsafe {
            sys::icsneoc2_device_info_type_name_get(self.ptr, buf, len)
        })
    }

    /// Full device description (e.g. `"neoVI FIRE 3 RS2043"`).
    pub fn description(&self) -> Result<String> {
        ffi_string(128, |buf, len| unsafe {
            sys::icsneoc2_device_info_description_get(self.ptr, buf, len)
        })
    }
}

#[derive(Debug)]
struct DeviceInner {
    ptr: NonNull<sys::icsneoc2_device_t>,
}

unsafe impl Send for DeviceInner {}
unsafe impl Sync for DeviceInner {}

impl Drop for DeviceInner {
    fn drop(&mut self) {
        let raw = unsafe { sys::icsneoc2_device_close(self.ptr.as_ptr()) };
        match sys::Error::try_from(raw) {
            Ok(sys::Error::Success) => {}
            Ok(code) => eprintln!("Failed to close device: {}", api_error(code)),
            Err(e) => eprintln!("Failed to close device: {e}"),
        }
        let raw = unsafe { sys::icsneoc2_device_free(self.ptr.as_ptr()) };
        match sys::Error::try_from(raw) {
            Ok(sys::Error::Success) => {}
            Ok(code) => eprintln!("Failed to free device: {}", api_error(code)),
            Err(e) => eprintln!("Failed to free device: {e}"),
        }
    }
}

/// A handle to an Intrepid Control Systems vehicle network adapter.
///
/// `Device` is cheaply cloneable (via [`Arc`]) and thread-safe. When the last
/// clone is dropped the device is automatically closed and the underlying
/// handle is freed.
///
/// # Lifecycle
///
/// There are three ways to obtain a `Device`:
///
/// 1. **Two-step** — enumerate, create, then open when ready:
///    ```no_run
///    # use icsneoc2::*;
///    let list = Device::enumerate(0)?;
///    let info = list.iter().next().unwrap();
///    let device = Device::from_info(&info)?;
///    device.open(OpenOptions::DEFAULT)?;
///    # Ok::<(), Error>(())
///    ```
///
/// 2. **Open first** — one-liner that opens the first device found:
///    ```no_run
///    # use icsneoc2::*;
///    let device = Device::open_first(0, OpenOptions::DEFAULT)?;
///    # Ok::<(), Error>(())
///    ```
///
/// 3. **Open by serial** — find a specific device by serial number:
///    ```no_run
///    # use icsneoc2::*;
///    let device = Device::open_serial("RS2043", OpenOptions::DEFAULT)?;
///    # Ok::<(), Error>(())
///    ```
#[derive(Debug, Clone)]
pub struct Device {
    inner: Arc<DeviceInner>,
}

impl Device {
    /// Returns a mutable raw pointer to the underlying `icsneoc2_device_t`.
    ///
    /// Useful for passing the device handle to FFI functions not yet wrapped
    /// by this crate.
    pub fn as_mut_ptr(&self) -> *mut icsneoc2_device_t {
        self.inner.ptr.as_ptr()
    }

    /// Returns a [`Settings`] view for this device.
    ///
    /// The returned handle borrows the device so it cannot be dropped while
    /// settings are being inspected or modified.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let settings = device.settings();
    /// let baudrate = settings.baudrate(Netid::Dwcan01)?;
    /// println!("HSCAN baudrate: {baudrate}");
    /// # Ok::<(), Error>(())
    /// ```
    pub fn settings(&self) -> Settings<'_> {
        Settings::new(self.as_mut_ptr())
    }

    /// Enumerates connected devices, returning an owned linked list.
    ///
    /// Pass `0` to enumerate all device types, or a specific
    /// [`icsneoc2_devicetype_t`](sys::icsneoc2_devicetype_t) to filter.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let list = Device::enumerate(0)?;
    /// for info in &list {
    ///     println!("{}", info.description()?);
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn enumerate(device_type: sys::icsneoc2_devicetype_t) -> Result<DeviceInfoList> {
        let mut head: *mut sys::icsneoc2_device_info_t = std::ptr::null_mut();
        check(unsafe { sys::icsneoc2_device_enumerate(device_type, &raw mut head) })?;
        Ok(DeviceInfoList { head })
    }

    /// Creates a device handle from an enumeration node without opening it.
    ///
    /// The returned handle must be opened with [`Device::open`] before it can
    /// communicate with the hardware. The handle is freed automatically on
    /// drop via `icsneoc2_device_free`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let list = Device::enumerate(0)?;
    /// for info in &list {
    ///     let device = Device::from_info(&info)?;
    ///     // Inspect settings before going online
    ///     device.open(OpenOptions::ENABLE_AUTO_UPDATE)?;
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn from_info(info: &DeviceInfo<'_>) -> Result<Self> {
        let mut device: *mut icsneoc2_device_t = std::ptr::null_mut();
        check(unsafe { sys::icsneoc2_device_create(info.as_ptr(), &raw mut device) })?;
        Ok(Device {
            inner: Arc::new(DeviceInner {
                ptr: NonNull::new(device).ok_or_else(|| {
                    Error::MemoryError(
                        "icsneoc2_device_create() returned a null pointer".to_string(),
                    )
                })?,
            }),
        })
    }

    /// Opens a previously created device handle.
    ///
    /// After a successful call the device is ready to communicate. The device
    /// is automatically closed and freed on drop.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let list = Device::enumerate(0)?;
    /// let info = list.iter().next().unwrap();
    /// let device = Device::from_info(&info)?;
    /// device.open(OpenOptions::DEFAULT)?;
    /// assert!(device.is_open()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn open(&self, options: OpenOptions) -> Result<()> {
        check(unsafe { sys::icsneoc2_device_open(self.as_mut_ptr(), options.into()) })
    }

    /// Convenience: enumerates, opens the first available device, and frees
    /// the enumeration list.
    ///
    /// Pass `0` for `device_type` to match any device.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// println!("{}", device.description()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn open_first(
        device_type: sys::icsneoc2_devicetype_t,
        options: OpenOptions,
    ) -> Result<Self> {
        let mut device: *mut icsneoc2_device_t = std::ptr::null_mut();
        check(unsafe {
            sys::icsneoc2_device_open_first(device_type, options.into(), &raw mut device)
        })?;
        Ok(Device {
            inner: Arc::new(DeviceInner {
                ptr: NonNull::new(device).ok_or_else(|| {
                    Error::MemoryError(
                        "icsneoc2_device_open_first() returned a null pointer".to_string(),
                    )
                })?,
            }),
        })
    }

    /// Convenience: enumerates, finds a device by serial number, opens it,
    /// and frees the enumeration list.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_serial("RS2043", OpenOptions::DEFAULT)?;
    /// println!("{}", device.description()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn open_serial(serial: &str, options: OpenOptions) -> Result<Self> {
        let serial_c = CString::new(serial)?;
        let mut device: *mut icsneoc2_device_t = std::ptr::null_mut();
        check(unsafe {
            sys::icsneoc2_device_open_serial(serial_c.as_ptr(), options.into(), &raw mut device)
        })?;
        Ok(Device {
            inner: Arc::new(DeviceInner {
                ptr: NonNull::new(device).ok_or_else(|| {
                    Error::MemoryError(
                        "icsneoc2_device_open_serial() returned a null pointer".to_string(),
                    )
                })?,
            }),
        })
    }

    pub fn description(&self) -> Result<String> {
        ffi_string(255, |buf, len| unsafe {
            sys::icsneoc2_device_description_get(self.as_mut_ptr(), buf, len)
        })
    }

    /// Retrieves pending events for this device.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// for event in device.events()? {
    ///     println!("{event}");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn events(&self) -> Result<Vec<Event>> {
        crate::event::events(Some(self))
    }

    /// Sets the online state of the device.
    ///
    /// Pass `true` to go online (start acknowledging bus traffic), or `false`
    /// to go offline.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::ENABLE_AUTO_UPDATE)?;
    /// device.go_online(true)?;
    /// assert!(device.is_online()?);
    /// device.go_online(false)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn go_online(&self, go_online: bool) -> Result<()> {
        check(unsafe { sys::icsneoc2_device_go_online(self.as_mut_ptr(), go_online) })
    }

    /// Returns `true` if the device is currently online.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// if device.is_online()? {
    ///     println!("Device is online");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn is_online(&self) -> Result<bool> {
        let mut value = false;
        check(unsafe { sys::icsneoc2_device_is_online(self.as_mut_ptr(), &raw mut value) })?;
        Ok(value)
    }

    /// Returns `true` if this device supports going online.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// if device.is_online_supported()? {
    ///     device.go_online(true)?;
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn is_online_supported(&self) -> Result<bool> {
        let mut value = false;
        check(unsafe {
            sys::icsneoc2_device_is_online_supported(self.as_mut_ptr(), &raw mut value)
        })?;
        Ok(value)
    }

    /// Returns `true` if the device handle is valid.
    ///
    /// Returns `false` (rather than an error) when the device is invalid.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// assert!(device.is_valid()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn is_valid(&self) -> Result<bool> {
        let raw = unsafe { sys::icsneoc2_device_is_valid(self.as_mut_ptr()) };
        match sys::Error::try_from(raw) {
            Ok(sys::Error::Success) => Ok(true),
            Ok(sys::Error::InvalidDevice) => Ok(false),
            Ok(code) => Err(api_error(code)),
            Err(e) => Err(Error::from(e)),
        }
    }

    /// Returns `true` if the device is currently open.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let list = Device::enumerate(0)?;
    /// let info = list.iter().next().unwrap();
    /// let device = Device::from_info(&info)?;
    /// assert!(!device.is_open()?);
    /// device.open(OpenOptions::DEFAULT)?;
    /// assert!(device.is_open()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn is_open(&self) -> Result<bool> {
        let mut value = false;
        check(unsafe { sys::icsneoc2_device_is_open(self.as_mut_ptr(), &raw mut value) })?;
        Ok(value)
    }

    /// Reconnects to a device that was disconnected.
    ///
    /// This is useful if the device was physically disconnected and
    /// reconnected, or if the connection was lost for some reason.
    ///
    /// # Arguments
    ///
    /// * `options` — Open options to use when reconnecting.
    /// * `timeout_ms` — How long (in milliseconds) to keep retrying before
    ///   giving up.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// // ... device gets disconnected ...
    /// device.reconnect(OpenOptions::DEFAULT, 5000)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn reconnect(&self, options: OpenOptions, timeout_ms: u32) -> Result<()> {
        check(unsafe {
            sys::icsneoc2_device_reconnect(self.as_mut_ptr(), options.into(), timeout_ms)
        })
    }

    /// Returns the current message polling limit.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// println!("Polling limit: {}", device.message_polling_limit()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn message_polling_limit(&self) -> Result<u32> {
        let mut value: u32 = 0;
        check(unsafe {
            sys::icsneoc2_device_message_polling_limit_get(self.as_mut_ptr(), &raw mut value)
        })?;
        Ok(value)
    }

    /// Sets the message polling limit.
    ///
    /// Messages exceeding this limit are truncated from the queue.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// device.set_message_polling_limit(10_000)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn set_message_polling_limit(&self, value: u32) -> Result<()> {
        check(unsafe { sys::icsneoc2_device_message_polling_limit_set(self.as_mut_ptr(), value) })
    }

    /// Gets the next message from the device.
    ///
    /// `timeout_ms` is the maximum time to wait for a message. Pass `0` for
    /// a non-blocking call.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// // Block up to 3 seconds for the first message
    /// if let Ok(msg) = device.message(3000) {
    ///     println!("netid: {:?}", msg.netid()?);
    /// }
    /// // Drain remaining messages non-blocking
    /// while let Ok(msg) = device.message(0) {
    ///     println!("netid: {:?}", msg.netid()?);
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn message(&self, timeout_ms: u32) -> Result<Message> {
        let mut ptr: *mut icsneoc2_message_t = std::ptr::null_mut();
        check(unsafe {
            sys::icsneoc2_device_message_get(self.as_mut_ptr(), &raw mut ptr, timeout_ms)
        })?;
        unsafe { Message::from_owned_ptr(ptr) }
    }

    /// Transmits a message on the bus.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let msg = Message::new(MessageType::Can)?;
    /// msg.set_netid(Netid::Dwcan01)?;
    /// msg.set_can_props(Some(0x10), None)?;
    /// msg.set_data(&[0xDE, 0xAD])?;
    /// device.transmit(&msg)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn transmit(&self, msg: &Message) -> Result<()> {
        check(unsafe { sys::icsneoc2_device_message_transmit(self.as_mut_ptr(), msg.as_mut_ptr()) })
    }

    /// Returns the device's real-time clock value as a Unix epoch timestamp.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let epoch = device.rtc()?;
    /// println!("RTC: {epoch}");
    /// # Ok::<(), Error>(())
    /// ```
    pub fn rtc(&self) -> Result<i64> {
        let mut value: i64 = 0;
        check(unsafe { sys::icsneoc2_device_rtc_get(self.as_mut_ptr(), &raw mut value) })?;
        Ok(value)
    }

    /// Sets the device's real-time clock to the given Unix epoch timestamp.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let now = std::time::SystemTime::now()
    ///     .duration_since(std::time::UNIX_EPOCH)
    ///     .unwrap()
    ///     .as_secs() as i64;
    /// device.set_rtc(now)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn set_rtc(&self, value: i64) -> Result<()> {
        check(unsafe { sys::icsneoc2_device_rtc_set(self.as_mut_ptr(), value) })
    }

    /// Returns the serial number string (e.g. `"RS2043"`).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// println!("Serial: {}", device.serial()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn serial(&self) -> Result<String> {
        ffi_string(255, |buf, len| unsafe {
            sys::icsneoc2_device_serial_get(self.as_mut_ptr(), buf, len)
        })
    }

    /// Returns `true` if this device supports TC10 wake/sleep.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// if device.supports_tc10()? {
    ///     println!("TC10 supported");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn supports_tc10(&self) -> Result<bool> {
        let mut value = false;
        check(unsafe { sys::icsneoc2_device_supports_tc10(self.as_mut_ptr(), &raw mut value) })?;
        Ok(value)
    }

    /// Returns the timestamp resolution of the device in nanoseconds.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// println!("Timestamp resolution: {}ns", device.timestamp_resolution()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn timestamp_resolution(&self) -> Result<u32> {
        let mut value: u32 = 0;
        check(unsafe {
            sys::icsneoc2_device_timestamp_resolution_get(self.as_mut_ptr(), &raw mut value)
        })?;
        Ok(value)
    }

    pub fn device_type(&self) -> Result<sys::Devicetype> {
        let mut raw: sys::icsneoc2_devicetype_t = 0;
        check(unsafe { sys::icsneoc2_device_type_get(self.as_mut_ptr(), &raw mut raw) })?;
        Ok(sys::Devicetype::try_from(raw)?)
    }

    /// Returns the human-readable device type name (e.g. `"neoVI FIRE 3"`).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// println!("{}", device.device_type_name()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn device_type_name(&self) -> Result<String> {
        Ok(self.device_type()?.to_string())
    }

    // -----------------------------------------------------------------------
    // Digital I/O
    // -----------------------------------------------------------------------

    /// Reads the current state of a digital I/O pin.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let state = device.digital_io(IoType::Misc, 0)?;
    /// println!("Pin state: {state}");
    /// # Ok::<(), Error>(())
    /// ```
    pub fn digital_io(&self, io_type: sys::IoType, number: u32) -> Result<bool> {
        let mut value = false;
        check(unsafe {
            sys::icsneoc2_device_digital_io_get(
                self.as_mut_ptr(),
                sys::icsneoc2_io_type_t::from(io_type),
                number,
                &raw mut value,
            )
        })?;
        Ok(value)
    }

    /// Sets the state of a digital I/O pin.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// device.set_digital_io(IoType::Misc, 0, true)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn set_digital_io(&self, io_type: sys::IoType, number: u32, value: bool) -> Result<()> {
        check(unsafe {
            sys::icsneoc2_device_digital_io_set(
                self.as_mut_ptr(),
                sys::icsneoc2_io_type_t::from(io_type),
                number,
                value,
            )
        })
    }

    // -----------------------------------------------------------------------
    // Supported networks
    // -----------------------------------------------------------------------

    /// Returns the list of network IDs that this device can receive on.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// for netid in device.supported_rx_networks()? {
    ///     println!("RX: {netid}");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn supported_rx_networks(&self) -> Result<Vec<sys::Netid>> {
        // First call: query the count
        let mut count: usize = 0;
        check(unsafe {
            sys::icsneoc2_device_supported_rx_networks_get(
                self.as_mut_ptr(),
                std::ptr::null_mut(),
                &raw mut count,
            )
        })?;
        if count == 0 {
            return Ok(vec![]);
        }
        // Second call: fill array
        let mut raw: Vec<sys::icsneoc2_netid_t> = vec![0; count];
        check(unsafe {
            sys::icsneoc2_device_supported_rx_networks_get(
                self.as_mut_ptr(),
                raw.as_mut_ptr(),
                &raw mut count,
            )
        })?;
        raw.truncate(count);
        raw.into_iter()
            .map(|v| Ok(sys::Netid::try_from(v)?))
            .collect()
    }

    /// Returns the list of network IDs that this device can transmit on.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// for netid in device.supported_tx_networks()? {
    ///     println!("TX: {netid}");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn supported_tx_networks(&self) -> Result<Vec<sys::Netid>> {
        let mut count: usize = 0;
        check(unsafe {
            sys::icsneoc2_device_supported_tx_networks_get(
                self.as_mut_ptr(),
                std::ptr::null_mut(),
                &raw mut count,
            )
        })?;
        if count == 0 {
            return Ok(vec![]);
        }
        let mut raw: Vec<sys::icsneoc2_netid_t> = vec![0; count];
        check(unsafe {
            sys::icsneoc2_device_supported_tx_networks_get(
                self.as_mut_ptr(),
                raw.as_mut_ptr(),
                &raw mut count,
            )
        })?;
        raw.truncate(count);
        raw.into_iter()
            .map(|v| Ok(sys::Netid::try_from(v)?))
            .collect()
    }

    // -----------------------------------------------------------------------
    // Disk
    // -----------------------------------------------------------------------

    /// Returns `true` if the device supports disk formatting.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// if device.supports_disk_formatting()? {
    ///     println!("Disk formatting supported");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn supports_disk_formatting(&self) -> Result<bool> {
        let mut value = false;
        check(unsafe {
            sys::icsneoc2_device_supports_disk_formatting(self.as_mut_ptr(), &raw mut value)
        })?;
        Ok(value)
    }

    /// Returns the number of disk slots on the device.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// println!("Disk slots: {}", device.disk_count()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn disk_count(&self) -> Result<usize> {
        let mut value: usize = 0;
        check(unsafe { sys::icsneoc2_device_disk_count_get(self.as_mut_ptr(), &raw mut value) })?;
        Ok(value)
    }

    /// Returns the [`DiskDetails`](crate::DiskDetails) handle for inspecting
    /// or configuring disk parameters.
    ///
    /// The returned handle is freed automatically on drop.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let details = device.disk_details()?;
    /// println!("Layout: {:?}", details.layout()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn disk_details(&self) -> Result<crate::disk::DiskDetails> {
        let mut ptr: *mut sys::icsneoc2_disk_details_t = std::ptr::null_mut();
        check(unsafe { sys::icsneoc2_device_disk_details_get(self.as_mut_ptr(), &raw mut ptr) })?;
        NonNull::new(ptr)
            .map(crate::disk::DiskDetails::new)
            .ok_or_else(|| {
                Error::MemoryError(
                    "icsneoc2_device_disk_details_get returned a null pointer".to_string(),
                )
            })
    }

    /// Formats the device's disk using the given [`DiskDetails`](crate::DiskDetails) configuration.
    ///
    /// `progress` is an optional callback invoked with `(sectors_formatted, total_sectors)`.
    /// Return [`sys::DiskFormatDirective::Continue`] to keep going or
    /// [`sys::DiskFormatDirective::Stop`] to abort.
    ///
    /// # Safety
    /// `user_data` must be valid for the duration of the format operation if
    /// the progress callback dereferences it.
    pub unsafe fn format_disk(
        &self,
        details: &crate::disk::DiskDetails,
        progress: sys::icsneoc2_disk_format_progress_fn,
        user_data: *mut std::ffi::c_void,
    ) -> Result<()> {
        check(unsafe {
            sys::icsneoc2_device_format_disk(
                self.as_mut_ptr(),
                details.as_ptr(),
                progress,
                user_data,
            )
        })
    }

    // -----------------------------------------------------------------------
    // CoreMini scripting
    // -----------------------------------------------------------------------

    /// Returns `true` if this device supports CoreMini scripts.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// if device.supports_coremini_script()? {
    ///     println!("CoreMini supported");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn supports_coremini_script(&self) -> Result<bool> {
        let mut value = false;
        check(unsafe {
            sys::icsneoc2_device_supports_coremini_script(self.as_mut_ptr(), &raw mut value)
        })?;
        Ok(value)
    }

    /// Starts a CoreMini script from the given memory type (flash or SD).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// device.script_start(MemoryType::Flash)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn script_start(&self, memory_type: sys::MemoryType) -> Result<()> {
        check(unsafe {
            sys::icsneoc2_device_script_start(
                self.as_mut_ptr(),
                sys::icsneoc2_memory_type_t::from(memory_type),
            )
        })
    }

    /// Stops any running CoreMini script.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// device.script_stop()?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn script_stop(&self) -> Result<()> {
        check(unsafe { sys::icsneoc2_device_script_stop(self.as_mut_ptr()) })
    }

    /// Clears a CoreMini script from the given memory type (flash or SD).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// device.script_clear(MemoryType::Flash)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn script_clear(&self, memory_type: sys::MemoryType) -> Result<()> {
        check(unsafe {
            sys::icsneoc2_device_script_clear(
                self.as_mut_ptr(),
                sys::icsneoc2_memory_type_t::from(memory_type),
            )
        })
    }

    /// Prepares the device for a script load operation.
    ///
    /// Returns a status code from the device.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let status = device.script_prepare_load()?;
    /// println!("Prepare status: {status}");
    /// # Ok::<(), Error>(())
    /// ```
    pub fn script_prepare_load(&self) -> Result<i8> {
        let mut status: i8 = 0;
        check(unsafe {
            sys::icsneoc2_device_script_prepare_load(self.as_mut_ptr(), &raw mut status)
        })?;
        Ok(status)
    }

    /// Uploads a CoreMini script to the device from a file path.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// device.coremini_upload_file(
    ///     std::path::Path::new("/path/to/script.bin"),
    ///     MemoryType::Flash,
    /// )?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn coremini_upload_file(
        &self,
        path: &std::path::Path,
        memory_type: sys::MemoryType,
    ) -> Result<()> {
        let path_c = CString::new(path.to_str().ok_or_else(|| {
            Error::StringConversionError("path contains invalid UTF-8".to_string())
        })?)?;
        check(unsafe {
            sys::icsneoc2_device_coremini_upload_file(
                self.as_mut_ptr(),
                path_c.as_ptr(),
                sys::icsneoc2_memory_type_t::from(memory_type),
            )
        })
    }

    /// Uploads a CoreMini script to the device from a memory buffer.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let script_data = std::fs::read("/path/to/script.bin")?;
    /// device.coremini_upload(&script_data, MemoryType::Flash)?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn coremini_upload(&self, data: &[u8], memory_type: sys::MemoryType) -> Result<()> {
        check(unsafe {
            sys::icsneoc2_device_coremini_upload(
                self.as_mut_ptr(),
                data.as_ptr(),
                data.len(),
                sys::icsneoc2_memory_type_t::from(memory_type),
            )
        })
    }

    /// Returns the [`ScriptStatus`](crate::ScriptStatus) for the currently
    /// loaded script.
    ///
    /// The returned handle is freed automatically on drop.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use icsneoc2::*;
    /// let device = Device::open_first(0, OpenOptions::DEFAULT)?;
    /// let status = device.script_status()?;
    /// println!("Running: {}", status.is_running()?);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn script_status(&self) -> Result<crate::script::ScriptStatus> {
        let mut ptr: *mut sys::icsneoc2_script_status_t = std::ptr::null_mut();
        check(unsafe { sys::icsneoc2_device_script_status_get(self.as_mut_ptr(), &raw mut ptr) })?;
        NonNull::new(ptr)
            .map(crate::script::ScriptStatus::new)
            .ok_or_else(|| {
                Error::MemoryError(
                    "icsneoc2_device_script_status_get returned a null pointer".to_string(),
                )
            })
    }
}