seekdas_ffi/
lib.rs

1//! `seekdas` 的 C ABI 导出,供 C、C++、Python(cffi / ctypes)等语言调用。
2//!
3//! 构建产物:动态库 `seekdas_ffi.dll` / `libseekdas_ffi.so`、静态库 `seekdas_ffi.lib` / `libseekdas_ffi.a`;
4//! 头文件 `include/seekdas_ffi.h`(手写,与本文件一一对应,每个函数的说明写在头文件里)。
5//!
6//! # 约定
7//!
8//! - 对象都是不透明句柄:`seekdas_device`、`seekdas_config`、`seekdas_capture`、`seekdas_at`,各有成对的创建 / 释放函数。
9//! - 返回 `int` 的函数:0([`SEEKDAS_OK`])成功,负数为错误码;[`seekdas_last_error`] 给出本线程上一次错误的文字说明。
10//!   个别函数用正数返回结果(如 [`seekdas_recv`] 返回 1 表示收到一个包),头文件里逐个注明。
11//! - 结构体都是 `#[repr(C)]`,布尔量用 `uint8_t`。
12//! - 库返回的指针(采集结果的数组、数据包的数组)归库所有,有效期在头文件里注明;调用方传入的缓冲区由调用方分配。
13//! - 一个句柄同一时刻只能由一个线程使用;不同句柄可以在不同线程上使用。
14//! - Rust 一侧的 panic 不会越过边界,转成错误码 [`SEEKDAS_ERR_INTERNAL`]。
15//!
16//! 接口的含义(转换时钟、分组、滤波核等概念)见 `seekdas` crate 的文档。
17
18#![allow(non_camel_case_types)]
19#![allow(clippy::missing_safety_doc)]
20
21use std::cell::RefCell;
22use std::ffi::{c_char, c_int, CStr, CString};
23use std::panic::{catch_unwind, AssertUnwindSafe};
24use std::time::Duration;
25
26use seekdas::at::{AtClient, ConvSource, SerialAtClient};
27use seekdas::{monitor, AcqConfig, AcqStatus, Capture, Channel, ChannelMask, ConvChannel, Device, DeviceConfig, Edge, EdgeDetector, Error, Kernel, Range, RegIo,
28              Result, RunState, Stream, Target, Trigger, Window};
29
30/// 成功。
31pub const SEEKDAS_OK: c_int = 0;
32/// 套接字或串口 I/O 错误。
33pub const SEEKDAS_ERR_IO: c_int = -1;
34/// 设备在规定时间内没有应答。
35pub const SEEKDAS_ERR_TIMEOUT: c_int = -2;
36/// 收到的数据不符合协议。
37pub const SEEKDAS_ERR_PROTOCOL: c_int = -3;
38/// 设备对 AT 指令回答了 ERROR。
39pub const SEEKDAS_ERR_AT: c_int = -4;
40/// AT 应答无法解析。
41pub const SEEKDAS_ERR_PARSE: c_int = -5;
42/// 参数无效(含空指针)。
43pub const SEEKDAS_ERR_ARGUMENT: c_int = -6;
44/// 设备报告了错误状态(丢点等)。
45pub const SEEKDAS_ERR_DEVICE: c_int = -7;
46/// 库内部错误。
47pub const SEEKDAS_ERR_INTERNAL: c_int = -8;
48/// 设备正在采集(触发运行中):不能启动新的采集或修改配置。
49pub const SEEKDAS_ERR_BUSY: c_int = -9;
50
51thread_local! {
52    static LAST_ERROR: RefCell<CString> = RefCell::new(CString::default());
53}
54
55fn set_error(msg: String) {
56    let c = CString::new(msg.replace('\0', " ")).unwrap_or_default();
57    LAST_ERROR.with(|e| *e.borrow_mut() = c);
58}
59
60fn code(e: &Error) -> c_int {
61    match e {
62        Error::Io(_) => SEEKDAS_ERR_IO,
63        Error::Timeout(_) => SEEKDAS_ERR_TIMEOUT,
64        Error::Protocol(_) => SEEKDAS_ERR_PROTOCOL,
65        Error::At { .. } => SEEKDAS_ERR_AT,
66        Error::Parse(_) => SEEKDAS_ERR_PARSE,
67        Error::InvalidArgument(_) => SEEKDAS_ERR_ARGUMENT,
68        Error::Device(_) => SEEKDAS_ERR_DEVICE,
69        Error::Busy(_) => SEEKDAS_ERR_BUSY,
70    }
71}
72
73/// run the body; errors and panics become a negative code and a message for seekdas_last_error()
74fn guard(f: impl FnOnce() -> Result<c_int>) -> c_int {
75    match catch_unwind(AssertUnwindSafe(f)) {
76        Ok(Ok(v)) => v,
77        Ok(Err(e)) => {
78            set_error(e.to_string());
79            code(&e)
80        }
81        Err(_) => {
82            set_error("internal error (panic) in the seekdas library".into());
83            SEEKDAS_ERR_INTERNAL
84        }
85    }
86}
87
88fn arg(what: &str) -> Error {
89    Error::InvalidArgument(what.to_string())
90}
91
92unsafe fn obj<'a, T>(p: *mut T, what: &str) -> Result<&'a mut T> {
93    p.as_mut().ok_or_else(|| arg(&format!("{what}: null pointer")))
94}
95
96unsafe fn text<'a>(p: *const c_char, what: &str) -> Result<&'a str> {
97    if p.is_null() {
98        return Err(arg(&format!("{what}: null pointer")));
99    }
100    CStr::from_ptr(p).to_str().map_err(|_| arg(&format!("{what}: not UTF-8")))
101}
102
103/// copy a string into a caller buffer, always NUL-terminated, truncated if needed
104unsafe fn put_str(s: &str, buf: *mut c_char, size: usize) {
105    if buf.is_null() || size == 0 {
106        return;
107    }
108    let n = s.len().min(size - 1);
109    std::ptr::copy_nonoverlapping(s.as_ptr(), buf as *mut u8, n);
110    *buf.add(n) = 0;
111}
112
113fn channel(index: c_int) -> Result<Channel> {
114    usize::try_from(index).map_err(|_| arg("channel index 0..=11")).and_then(Channel::new)
115}
116
117fn window(index: c_int) -> Result<Window> {
118    usize::try_from(index).map_err(|_| arg("window 0..=2")).and_then(Window::from_index)
119}
120
121// ---------------------------------------------------------------- general
122
123/// 本线程上一次失败的说明(英文,UTF-8,NUL 结尾)。指针在本线程下一次调用库函数之前有效。
124#[no_mangle]
125pub extern "C" fn seekdas_last_error() -> *const c_char {
126    LAST_ERROR.with(|e| e.borrow().as_ptr())
127}
128
129/// 库版本,如 "0.1.0"。
130#[no_mangle]
131pub extern "C" fn seekdas_version() -> *const c_char {
132    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
133}
134
135/// 用典型灵敏度把 ADC 码换算成伏;`range_volts` 为 10、5 或 2,无效时返回 NaN。
136#[no_mangle]
137pub extern "C" fn seekdas_code_to_volts(range_volts: c_int, code: f64) -> f64 {
138    u32::try_from(range_volts).ok().and_then(|v| Range::from_volts(v).ok()).map_or(f64::NAN, |r| r.code_to_volts(code))
139}
140
141// ---------------------------------------------------------------- device
142
143/// 光口上的一台设备。
144pub struct seekdas_device {
145    dev: *mut Device,
146    stream: Option<Stream<'static>>,
147    /// points of the run started by seekdas_trigger_start, collected by seekdas_trigger_wait (and seekdas_recv)
148    pending: Option<Capture>,
149    values: Vec<i16>,
150    times: Vec<u64>,
151    sources: Vec<u8>,
152    bad: Vec<u8>,
153}
154
155impl seekdas_device {
156    /// the device; while a stream is open it is reached through the stream, which borrows it
157    fn io(&mut self) -> &mut Device {
158        match &mut self.stream {
159            Some(s) => s.device(),
160            // SAFETY: `dev` comes from Box::into_raw and is freed only in Drop; no stream borrows it here
161            None => unsafe { &mut *self.dev },
162        }
163    }
164
165    /// Busy error while the device runs; checked before a stream of this handle is dropped
166    fn ensure_idle(&mut self) -> Result<()> {
167        if AcqStatus::read(self.io())?.busy {
168            return Err(Error::Busy("an acquisition is running; wait until it is done or stop it first".into()));
169        }
170        Ok(())
171    }
172
173    /// start a run with the configuration in the device; drops the previous stream of this handle
174    fn start_stream(&mut self) -> Result<()> {
175        self.ensure_idle()?;
176        self.stream = None;
177        self.pending = None;
178        // SAFETY: the device lives on the heap until the handle is dropped, and the handle drops the stream first;
179        // while the stream exists the device is only reached through it (seekdas_device::io)
180        let device: &'static mut Device = unsafe { &mut *self.dev };
181        self.stream = Some(device.start()?);
182        Ok(())
183    }
184}
185
186impl Drop for seekdas_device {
187    fn drop(&mut self) {
188        self.stream = None;
189        self.pending = None;
190        // SAFETY: the stream that borrowed the device is gone
191        unsafe { drop(Box::from_raw(self.dev)) };
192    }
193}
194
195/// 设备标识。
196#[repr(C)]
197#[derive(Default)]
198pub struct seekdas_device_info {
199    pub version_major: u8,
200    pub version_minor: u8,
201    pub version_patch: u16,
202    pub channels: u8,
203    pub slots: u8,
204    /// "2026-12-01"
205    pub build_date: [c_char; 12],
206    /// "09:05:53"
207    pub build_time: [c_char; 12],
208}
209
210/// 板级状态。
211#[repr(C)]
212#[derive(Default)]
213pub struct seekdas_board_status {
214    pub power_good: u8,
215    pub running: u8,
216    pub selftest_done: u8,
217    pub selftest_passed: u8,
218    pub adc_aligned: [u8; 3],
219    pub fifo_errors: [u8; 3],
220    pub lasers: [u8; 2],
221    pub selftest_failed_items: u16,
222    pub raw: u32,
223}
224
225/// 网络状态。
226#[repr(C)]
227#[derive(Default)]
228pub struct seekdas_net_status {
229    pub link_up: u8,
230    pub next_seq: u32,
231    pub acked_seq: u32,
232    pub packets_sent: u32,
233    pub retransmitted: u32,
234    pub nacks_received: u32,
235    pub acks_received: u32,
236    pub ddr_write_errors: u32,
237    pub arp_failures: u32,
238    pub ddr_read_errors: u32,
239}
240
241/// 采集计数器。
242#[repr(C)]
243#[derive(Default, Clone, Copy)]
244pub struct seekdas_acq_status {
245    pub busy: u8,
246    pub done: u8,
247    pub points: u32,
248    pub group_points: [u32; 2],
249    pub lost: u32,
250    pub late: u32,
251    pub dropped: u32,
252    pub rejected: u8,
253}
254
255/// 接收统计。
256#[repr(C)]
257#[derive(Default, Clone, Copy)]
258pub struct seekdas_stream_stats {
259    pub packets: u64,
260    pub bytes: u64,
261    pub duplicates: u64,
262    pub nacks_sent: u64,
263    pub seqs_requested: u64,
264    pub acks_sent: u64,
265    pub heartbeats: u64,
266    pub retransmitted: u64,
267}
268
269/// 一次运行的汇总。
270#[repr(C)]
271#[derive(Default, Clone, Copy)]
272pub struct seekdas_summary {
273    pub device: seekdas_acq_status,
274    pub stream: seekdas_stream_stats,
275}
276
277/// 统计窗口读数。
278#[repr(C)]
279#[derive(Default, Clone, Copy)]
280pub struct seekdas_window_stats {
281    pub mean: f64,
282    pub rms: f64,
283    pub min: f64,
284    pub max: f64,
285}
286
287fn acq_status(s: &seekdas::AcqStatus) -> seekdas_acq_status {
288    seekdas_acq_status { busy: s.busy as u8, done: s.done as u8, points: s.points, group_points: s.group_points, lost: s.lost, late: s.late, dropped: s.dropped,
289                         rejected: s.rejected as u8 }
290}
291
292fn summary(s: &seekdas::RunSummary) -> seekdas_summary {
293    let t = &s.stream;
294    seekdas_summary {
295        device: acq_status(&s.device),
296        stream: seekdas_stream_stats {
297            packets: t.packets, bytes: t.bytes, duplicates: t.duplicates, nacks_sent: t.nacks_sent, seqs_requested: t.seqs_requested,
298            acks_sent: t.acks_sent, heartbeats: t.heartbeats, retransmitted: t.retransmitted,
299        },
300    }
301}
302
303fn wstats(w: &seekdas::WindowStats) -> seekdas_window_stats {
304    seekdas_window_stats { mean: w.mean, rms: w.rms, min: w.min, max: w.max }
305}
306
307unsafe fn open_impl(cfg: DeviceConfig, out: *mut *mut seekdas_device) -> Result<c_int> {
308    let out = obj(out, "dev")?;
309    let dev = Box::into_raw(Box::new(Device::open_with(cfg)?));
310    *out = Box::into_raw(Box::new(seekdas_device { dev, stream: None, pending: None, values: Vec::new(), times: Vec::new(), sources: Vec::new(), bad: Vec::new() }));
311    Ok(SEEKDAS_OK)
312}
313
314#[no_mangle]
315pub unsafe extern "C" fn seekdas_open(ip: *const c_char, host_port: u16, dev: *mut *mut seekdas_device) -> c_int {
316    guard(|| {
317        let mut cfg = DeviceConfig::new(text(ip, "ip")?.parse().map_err(|_| arg("ip: not an IPv4 address"))?);
318        cfg.host_port = host_port;
319        open_impl(cfg, dev)
320    })
321}
322
323#[no_mangle]
324pub unsafe extern "C" fn seekdas_open_ex(ip: *const c_char, ctrl_port: u16, data_port: u16, host_port: u16, set_host: c_int, reg_timeout_ms: u32,
325                                         dev: *mut *mut seekdas_device) -> c_int {
326    guard(|| {
327        let mut cfg = DeviceConfig::new(text(ip, "ip")?.parse().map_err(|_| arg("ip: not an IPv4 address"))?);
328        cfg.ctrl_port = ctrl_port;
329        cfg.data_port = data_port;
330        cfg.host_port = host_port;
331        cfg.set_host = set_host != 0;
332        if reg_timeout_ms != 0 {
333            cfg.reg_timeout = Duration::from_millis(reg_timeout_ms as u64);
334        }
335        open_impl(cfg, dev)
336    })
337}
338
339#[no_mangle]
340pub unsafe extern "C" fn seekdas_close(dev: *mut seekdas_device) {
341    if !dev.is_null() {
342        let _ = catch_unwind(AssertUnwindSafe(|| drop(Box::from_raw(dev))));
343    }
344}
345
346#[no_mangle]
347pub unsafe extern "C" fn seekdas_reg_read(dev: *mut seekdas_device, addr: u16, value: *mut u32) -> c_int {
348    guard(|| {
349        *obj(value, "value")? = obj(dev, "dev")?.io().read_reg(addr)?;
350        Ok(SEEKDAS_OK)
351    })
352}
353
354#[no_mangle]
355pub unsafe extern "C" fn seekdas_reg_read_many(dev: *mut seekdas_device, addr: u16, values: *mut u32, count: usize) -> c_int {
356    guard(|| {
357        if values.is_null() {
358            return Err(arg("values: null pointer"));
359        }
360        let v = obj(dev, "dev")?.io().read_regs(addr, count)?;
361        std::ptr::copy_nonoverlapping(v.as_ptr(), values, count);
362        Ok(SEEKDAS_OK)
363    })
364}
365
366#[no_mangle]
367pub unsafe extern "C" fn seekdas_reg_write(dev: *mut seekdas_device, addr: u16, value: u32, readback: *mut u32) -> c_int {
368    guard(|| {
369        let v = obj(dev, "dev")?.io().write_reg(addr, value)?;
370        if let Some(r) = readback.as_mut() {
371            *r = v;
372        }
373        Ok(SEEKDAS_OK)
374    })
375}
376
377#[no_mangle]
378pub unsafe extern "C" fn seekdas_get_info(dev: *mut seekdas_device, out: *mut seekdas_device_info) -> c_int {
379    guard(|| {
380        let out = obj(out, "out")?;
381        let i = obj(dev, "dev")?.io().info()?;
382        *out = seekdas_device_info { version_major: i.version.0, version_minor: i.version.1, version_patch: i.version.2, channels: i.channels, slots: i.slots, ..Default::default() };
383        put_str(&i.build_date, out.build_date.as_mut_ptr(), 12);
384        put_str(&i.build_time, out.build_time.as_mut_ptr(), 12);
385        Ok(SEEKDAS_OK)
386    })
387}
388
389#[no_mangle]
390pub unsafe extern "C" fn seekdas_sample_rate_hz(dev: *mut seekdas_device, hz: *mut f64) -> c_int {
391    guard(|| {
392        *obj(hz, "hz")? = obj(dev, "dev")?.io().sample_rate_hz()?;
393        Ok(SEEKDAS_OK)
394    })
395}
396
397#[no_mangle]
398pub unsafe extern "C" fn seekdas_board_status_get(dev: *mut seekdas_device, out: *mut seekdas_board_status) -> c_int {
399    guard(|| {
400        let b = obj(dev, "dev")?.io().board_status()?;
401        *obj(out, "out")? = seekdas_board_status {
402            power_good: b.power_good as u8, running: b.running as u8, selftest_done: b.selftest_done as u8, selftest_passed: b.selftest_passed as u8,
403            adc_aligned: b.adc_aligned.map(|v| v as u8), fifo_errors: b.fifo_errors.map(|v| v as u8), lasers: b.lasers.map(|v| v as u8),
404            selftest_failed_items: b.selftest_failed_items, raw: b.raw,
405        };
406        Ok(SEEKDAS_OK)
407    })
408}
409
410#[no_mangle]
411pub unsafe extern "C" fn seekdas_net_status_get(dev: *mut seekdas_device, out: *mut seekdas_net_status) -> c_int {
412    guard(|| {
413        let n = obj(dev, "dev")?.io().net_status()?;
414        *obj(out, "out")? = seekdas_net_status {
415            link_up: n.link_up as u8, next_seq: n.next_seq, acked_seq: n.acked_seq, packets_sent: n.packets_sent, retransmitted: n.retransmitted,
416            nacks_received: n.nacks_received, acks_received: n.acks_received, ddr_write_errors: n.ddr_write_errors, arp_failures: n.arp_failures,
417            ddr_read_errors: n.ddr_read_errors,
418        };
419        Ok(SEEKDAS_OK)
420    })
421}
422
423#[no_mangle]
424pub unsafe extern "C" fn seekdas_acq_status_get(dev: *mut seekdas_device, out: *mut seekdas_acq_status) -> c_int {
425    guard(|| {
426        *obj(out, "out")? = acq_status(&obj(dev, "dev")?.io().acq_status()?);
427        Ok(SEEKDAS_OK)
428    })
429}
430
431#[no_mangle]
432pub unsafe extern "C" fn seekdas_read_window(dev: *mut seekdas_device, window_index: c_int, channel_index: c_int, out: *mut seekdas_window_stats) -> c_int {
433    guard(|| {
434        *obj(out, "out")? = wstats(&monitor::read_window(obj(dev, "dev")?.io(), window(window_index)?, channel(channel_index)?)?);
435        Ok(SEEKDAS_OK)
436    })
437}
438
439#[no_mangle]
440pub unsafe extern "C" fn seekdas_raw_capture(dev: *mut seekdas_device, decimation_log2: u8, samples: *mut i16) -> c_int {
441    guard(|| {
442        if samples.is_null() {
443            return Err(arg("samples: null pointer"));
444        }
445        let raw = monitor::raw_capture(obj(dev, "dev")?.io(), decimation_log2)?;
446        for (c, col) in raw.samples.iter().enumerate() {
447            std::ptr::copy_nonoverlapping(col.as_ptr(), samples.add(1024 * c), 1024);
448        }
449        Ok(SEEKDAS_OK)
450    })
451}
452
453// ---------------------------------------------------------------- configuration
454
455/// 采集配置。
456pub struct seekdas_config(AcqConfig);
457
458unsafe fn edit(cfg: *mut seekdas_config, f: impl FnOnce(AcqConfig) -> Result<AcqConfig>) -> c_int {
459    guard(|| {
460        let c = obj(cfg, "cfg")?;
461        // the builder methods take the configuration by value; on an error the old one stays
462        c.0 = f(c.0.clone())?;
463        Ok(SEEKDAS_OK)
464    })
465}
466
467#[no_mangle]
468pub extern "C" fn seekdas_config_new() -> *mut seekdas_config {
469    Box::into_raw(Box::new(seekdas_config(AcqConfig::new())))
470}
471
472#[no_mangle]
473pub unsafe extern "C" fn seekdas_config_free(cfg: *mut seekdas_config) {
474    if !cfg.is_null() {
475        drop(Box::from_raw(cfg));
476    }
477}
478
479#[no_mangle]
480pub unsafe extern "C" fn seekdas_config_decimation(cfg: *mut seekdas_config, r: u8) -> c_int {
481    edit(cfg, |c| if r <= 4 { Ok(c.decimation_log2(r)) } else { Err(arg("decimation r = 0..=4")) })
482}
483
484#[no_mangle]
485pub unsafe extern "C" fn seekdas_config_bandwidth(cfg: *mut seekdas_config, bandwidth_hz: f64) -> c_int {
486    edit(cfg, |c| c.bandwidth(bandwidth_hz))
487}
488
489#[no_mangle]
490pub unsafe extern "C" fn seekdas_config_kernel_identity(cfg: *mut seekdas_config) -> c_int {
491    edit(cfg, |c| Ok(c.kernel(Kernel::identity())))
492}
493
494#[no_mangle]
495pub unsafe extern "C" fn seekdas_config_kernel_cubic(cfg: *mut seekdas_config) -> c_int {
496    edit(cfg, |c| Ok(c.kernel(Kernel::cubic())))
497}
498
499#[no_mangle]
500pub unsafe extern "C" fn seekdas_config_kernel_sinc(cfg: *mut seekdas_config, taps: u32, fc: f64, beta: f64) -> c_int {
501    edit(cfg, |c| Ok(c.kernel(Kernel::sinc(taps as usize, fc, beta)?)))
502}
503
504#[no_mangle]
505pub unsafe extern "C" fn seekdas_config_kernel_average(cfg: *mut seekdas_config, taps: u32, width: f64) -> c_int {
506    edit(cfg, |c| Ok(c.kernel(Kernel::average(taps as usize, width)?)))
507}
508
509#[no_mangle]
510pub unsafe extern "C" fn seekdas_config_kernel_least_squares(cfg: *mut seekdas_config, taps: u32, fp: f64, fs: f64, r: u8) -> c_int {
511    edit(cfg, |c| Ok(c.kernel(Kernel::least_squares(taps as usize, fp, fs, r)?)))
512}
513
514#[no_mangle]
515pub unsafe extern "C" fn seekdas_config_kernel_rows(cfg: *mut seekdas_config, coef: *const i32, taps: u32) -> c_int {
516    edit(cfg, |c| {
517        if coef.is_null() || taps == 0 || taps > 32 {
518            return Err(arg("coef: null pointer, or taps not in 4..=32"));
519        }
520        let all = std::slice::from_raw_parts(coef, 64 * taps as usize);
521        Ok(c.kernel(Kernel::from_rows(all.chunks(taps as usize).map(<[i32]>::to_vec).collect())?))
522    })
523}
524
525#[no_mangle]
526pub unsafe extern "C" fn seekdas_config_time_calibration(cfg: *mut seekdas_config, ticks: i16) -> c_int {
527    edit(cfg, |c| Ok(c.time_calibration(ticks)))
528}
529
530#[no_mangle]
531pub unsafe extern "C" fn seekdas_config_detector(cfg: *mut seekdas_config, detector: c_int, channel_index: c_int, edges: c_int, threshold: c_int,
532                                                 hysteresis: c_int, min_interval: u32) -> c_int {
533    edit(cfg, |c| {
534        if !(0..4).contains(&detector) || !(1..=3).contains(&edges) || !(-8192..=8191).contains(&threshold) || !(0..=8191).contains(&hysteresis) {
535            return Err(arg("detector 0..=3, edges 1..=3, threshold -8192..=8191, hysteresis 0..=8191"));
536        }
537        let det = EdgeDetector { channel: channel(channel_index)?, rising: edges & 1 != 0, falling: edges & 2 != 0, threshold: threshold as i16,
538                                 hysteresis: hysteresis as u16, min_interval };
539        Ok(c.detector(detector as usize, det))
540    })
541}
542
543#[no_mangle]
544pub unsafe extern "C" fn seekdas_config_generator_period(cfg: *mut seekdas_config, samples: f64) -> c_int {
545    edit(cfg, |c| if samples > 0.0 { Ok(c.generator_period(samples)) } else { Err(arg("generator period > 0")) })
546}
547
548#[no_mangle]
549pub unsafe extern "C" fn seekdas_config_generator_rate(cfg: *mut seekdas_config, points_per_second: f64) -> c_int {
550    edit(cfg, |c| if points_per_second > 0.0 { Ok(c.generator_rate(points_per_second)) } else { Err(arg("generator rate > 0")) })
551}
552
553#[no_mangle]
554pub unsafe extern "C" fn seekdas_config_group(cfg: *mut seekdas_config, group: c_int, sources: u32, channel_mask: u32, timestamps: c_int) -> c_int {
555    edit(cfg, |c| {
556        if !(0..2).contains(&group) || sources > 0x1F || channel_mask > 0xFFF {
557            return Err(arg("group 0..=1, sources 5 bits, channel mask 12 bits"));
558        }
559        Ok(c.group(group as usize, |_| seekdas::Group { sources: sources as u8, channels: ChannelMask::from_bits(channel_mask as u16), timestamps: timestamps != 0 }))
560    })
561}
562
563#[no_mangle]
564pub unsafe extern "C" fn seekdas_config_points(cfg: *mut seekdas_config, points: u32) -> c_int {
565    edit(cfg, |c| Ok(c.points(points)))
566}
567
568#[no_mangle]
569pub unsafe extern "C" fn seekdas_config_packet_beats(cfg: *mut seekdas_config, beats: u32) -> c_int {
570    edit(cfg, |c| u16::try_from(beats).map(|b| c.packet_beats(b)).map_err(|_| arg("packet beats 8..=1020")))
571}
572
573#[no_mangle]
574pub unsafe extern "C" fn seekdas_config_flush_us(cfg: *mut seekdas_config, microseconds: u32) -> c_int {
575    edit(cfg, |c| Ok(c.flush_timeout(Duration::from_micros(microseconds as u64))))
576}
577
578#[no_mangle]
579pub unsafe extern "C" fn seekdas_config_merge_delay(cfg: *mut seekdas_config, samples: u32) -> c_int {
580    edit(cfg, |c| u16::try_from(samples).map(|s| c.merge_delay(s)).map_err(|_| arg("merge delay 16..=65535")))
581}
582
583#[no_mangle]
584pub unsafe extern "C" fn seekdas_config_validate(cfg: *mut seekdas_config) -> c_int {
585    guard(|| obj(cfg, "cfg")?.0.validate().map(|_| SEEKDAS_OK))
586}
587
588#[no_mangle]
589pub unsafe extern "C" fn seekdas_kernel_for_bandwidth(bandwidth_hz: f64, r: *mut u8, taps: *mut u32, coef: *mut i32, noise_gain: *mut f64) -> c_int {
590    guard(|| {
591        let (dec, k) = Kernel::for_bandwidth(bandwidth_hz)?;
592        if let Some(p) = r.as_mut() {
593            *p = dec;
594        }
595        if let Some(p) = taps.as_mut() {
596            *p = k.taps() as u32;
597        }
598        if !coef.is_null() {
599            for (ph, row) in k.rows().iter().enumerate() {
600                std::ptr::copy_nonoverlapping(row.as_ptr(), coef.add(ph * k.taps()), k.taps());
601            }
602        }
603        if let Some(p) = noise_gain.as_mut() {
604            *p = k.noise_gain(dec);
605        }
606        Ok(SEEKDAS_OK)
607    })
608}
609
610// ---------------------------------------------------------------- acquisition: one call
611
612/// 一次采集的结果。
613pub struct seekdas_capture(Capture);
614
615#[no_mangle]
616pub unsafe extern "C" fn seekdas_configure(dev: *mut seekdas_device, cfg: *const seekdas_config) -> c_int {
617    guard(|| {
618        let cfg = cfg.as_ref().ok_or_else(|| arg("cfg: null pointer"))?;
619        obj(dev, "dev")?.io().configure(&cfg.0)?;
620        Ok(SEEKDAS_OK)
621    })
622}
623
624unsafe fn acquire_impl(dev: *mut seekdas_device, cfg: *const seekdas_config, out: *mut *mut seekdas_capture, ms: Option<u32>) -> c_int {
625    guard(|| {
626        let d = obj(dev, "dev")?;
627        let cfg = cfg.as_ref().ok_or_else(|| arg("cfg: null pointer"))?;
628        let out = obj(out, "capture")?;
629        d.ensure_idle()?;
630        d.stream = None;
631        d.pending = None;
632        let cap = match ms {
633            Some(ms) => d.io().acquire_for(&cfg.0, Duration::from_millis(ms as u64))?,
634            None => d.io().acquire(&cfg.0)?,
635        };
636        *out = Box::into_raw(Box::new(seekdas_capture(cap)));
637        Ok(SEEKDAS_OK)
638    })
639}
640
641#[no_mangle]
642pub unsafe extern "C" fn seekdas_acquire(dev: *mut seekdas_device, cfg: *const seekdas_config, capture: *mut *mut seekdas_capture) -> c_int {
643    acquire_impl(dev, cfg, capture, None)
644}
645
646#[no_mangle]
647pub unsafe extern "C" fn seekdas_acquire_for(dev: *mut seekdas_device, cfg: *const seekdas_config, duration_ms: u32, capture: *mut *mut seekdas_capture) -> c_int {
648    acquire_impl(dev, cfg, capture, Some(duration_ms))
649}
650
651#[no_mangle]
652pub unsafe extern "C" fn seekdas_capture_free(capture: *mut seekdas_capture) {
653    if !capture.is_null() {
654        drop(Box::from_raw(capture));
655    }
656}
657
658unsafe fn group<'a>(capture: *const seekdas_capture, g: c_int) -> Option<&'a seekdas::GroupData> {
659    let c = capture.as_ref()?;
660    (0..2).contains(&g).then(|| c.0.group(g as usize))
661}
662
663unsafe fn slice_out<T>(v: Option<&[T]>, count: *mut usize) -> *const T {
664    if let Some(n) = count.as_mut() {
665        *n = v.map_or(0, <[T]>::len);
666    }
667    match v {
668        Some(s) if !s.is_empty() => s.as_ptr(),
669        _ => std::ptr::null(),
670    }
671}
672
673#[no_mangle]
674pub unsafe extern "C" fn seekdas_capture_points(capture: *const seekdas_capture, g: c_int) -> usize {
675    group(capture, g).map_or(0, |d| d.len())
676}
677
678#[no_mangle]
679pub unsafe extern "C" fn seekdas_capture_channels(capture: *const seekdas_capture, g: c_int) -> u32 {
680    group(capture, g).map_or(0, |d| d.channels().bits() as u32)
681}
682
683#[no_mangle]
684pub unsafe extern "C" fn seekdas_capture_channel(capture: *const seekdas_capture, g: c_int, channel_index: c_int, count: *mut usize) -> *const i16 {
685    slice_out(group(capture, g).and_then(|d| d.channel(channel(channel_index).ok()?)), count)
686}
687
688#[no_mangle]
689pub unsafe extern "C" fn seekdas_capture_times(capture: *const seekdas_capture, g: c_int, count: *mut usize) -> *const u64 {
690    slice_out(group(capture, g).map(|d| d.times.as_slice()), count)
691}
692
693#[no_mangle]
694pub unsafe extern "C" fn seekdas_capture_sources(capture: *const seekdas_capture, g: c_int, count: *mut usize) -> *const u8 {
695    slice_out(group(capture, g).map(|d| d.sources.as_slice()), count)
696}
697
698#[no_mangle]
699pub unsafe extern "C" fn seekdas_capture_bad_points(capture: *const seekdas_capture, g: c_int, count: *mut usize) -> *const u32 {
700    slice_out(group(capture, g).map(|d| d.bad_points.as_slice()), count)
701}
702
703#[no_mangle]
704pub unsafe extern "C" fn seekdas_capture_t0(capture: *const seekdas_capture, g: c_int, t0: *mut u64) -> c_int {
705    match (group(capture, g).and_then(|d| d.t0), t0.as_mut()) {
706        (Some(t), Some(out)) => {
707            *out = t;
708            1
709        }
710        _ => 0,
711    }
712}
713
714#[no_mangle]
715pub unsafe extern "C" fn seekdas_capture_summary(capture: *const seekdas_capture, out: *mut seekdas_summary) -> c_int {
716    guard(|| {
717        let c = capture.as_ref().ok_or_else(|| arg("capture: null pointer"))?;
718        *obj(out, "out")? = summary(&c.0.summary);
719        Ok(SEEKDAS_OK)
720    })
721}
722
723#[no_mangle]
724pub unsafe extern "C" fn seekdas_capture_write_csv(capture: *const seekdas_capture, path: *const c_char) -> c_int {
725    guard(|| {
726        let c = capture.as_ref().ok_or_else(|| arg("capture: null pointer"))?;
727        let f = std::fs::File::create(text(path, "path")?)?;
728        c.0.write_csv(std::io::BufWriter::new(f))?;
729        Ok(SEEKDAS_OK)
730    })
731}
732
733// ---------------------------------------------------------------- acquisition: packet by packet
734
735/// 一个点包。
736#[repr(C)]
737pub struct seekdas_packet {
738    pub seq: u32,
739    pub first_index: u32,
740    pub t0: u64,
741    pub points: u32,
742    pub channel_mask: u32,
743    pub channels: u32,
744    pub group: u8,
745    pub last: u8,
746    pub retransmitted: u8,
747    pub has_time: u8,
748    pub run_id: u8,
749    pub values: *const i16,
750    pub times: *const u64,
751    pub sources: *const u8,
752    pub bad: *const u8,
753}
754
755#[no_mangle]
756pub unsafe extern "C" fn seekdas_start(dev: *mut seekdas_device) -> c_int {
757    guard(|| {
758        obj(dev, "dev")?.start_stream()?;
759        Ok(SEEKDAS_OK)
760    })
761}
762
763#[no_mangle]
764pub unsafe extern "C" fn seekdas_recv(dev: *mut seekdas_device, timeout_ms: u32, packet: *mut seekdas_packet) -> c_int {
765    guard(|| {
766        let d = obj(dev, "dev")?;
767        let out = obj(packet, "packet")?;
768        let stream = d.stream.as_mut().ok_or_else(|| arg("no acquisition running: call seekdas_start first"))?;
769        let Some(p) = stream.recv(Duration::from_millis(timeout_ms as u64))? else { return Ok(0) };
770        if let Some(cap) = d.pending.as_mut() {
771            cap.push(&p)?;
772        }
773        d.values.clear();
774        d.times.clear();
775        d.sources.clear();
776        d.bad.clear();
777        for pt in p.points() {
778            d.values.extend_from_slice(pt.values);
779            if p.has_time {
780                d.times.push(pt.time.unwrap_or(0));
781                d.sources.push(pt.source.unwrap_or(0));
782                d.bad.push(pt.bad as u8);
783            }
784        }
785        let ptr = |n: usize, p: *const u8| if n == 0 { std::ptr::null() } else { p };
786        *out = seekdas_packet {
787            seq: p.seq, first_index: p.first_index, t0: p.t0, points: p.len() as u32, channel_mask: p.channels.bits() as u32, channels: p.channels.len() as u32,
788            group: p.group, last: p.last as u8, retransmitted: p.retransmitted as u8, has_time: p.has_time as u8, run_id: p.run_id,
789            values: ptr(d.values.len(), d.values.as_ptr() as *const u8) as *const i16,
790            times: ptr(d.times.len(), d.times.as_ptr() as *const u8) as *const u64,
791            sources: ptr(d.sources.len(), d.sources.as_ptr()),
792            bad: ptr(d.bad.len(), d.bad.as_ptr()),
793        };
794        Ok(1)
795    })
796}
797
798#[no_mangle]
799pub unsafe extern "C" fn seekdas_stream_finished(dev: *mut seekdas_device) -> c_int {
800    guard(|| {
801        let d = obj(dev, "dev")?;
802        let s = d.stream.as_ref().ok_or_else(|| arg("no acquisition running: call seekdas_start first"))?;
803        Ok(s.is_finished() as c_int)
804    })
805}
806
807#[no_mangle]
808pub unsafe extern "C" fn seekdas_stop(dev: *mut seekdas_device) -> c_int {
809    guard(|| obj(dev, "dev")?.io().stop().map(|_| SEEKDAS_OK))
810}
811
812#[no_mangle]
813pub unsafe extern "C" fn seekdas_finish(dev: *mut seekdas_device, out: *mut seekdas_summary) -> c_int {
814    guard(|| {
815        let d = obj(dev, "dev")?;
816        let s = d.stream.take().ok_or_else(|| arg("no acquisition running"))?;
817        d.pending = None;
818        let sum = s.finish()?;
819        if let Some(o) = out.as_mut() {
820            *o = summary(&sum);
821        }
822        Ok(SEEKDAS_OK)
823    })
824}
825
826// ---------------------------------------------------------------- trigger
827
828/// 触发设置。
829pub struct seekdas_trigger(Trigger);
830
831/// 触发运行状态。
832#[repr(C)]
833#[derive(Default)]
834pub struct seekdas_trigger_state {
835    /// SEEKDAS_RUN_IDLE / RUNNING / DONE
836    pub state: i32,
837    pub running: u8,
838    pub start_allowed: u8,
839    pub complete: u8,
840    pub rejected: u8,
841    pub points: u32,
842    pub target_points: u32,
843    pub channel_mask: u32,
844    pub conv_edges: [u32; 4],
845    pub lost: u32,
846    pub late: u32,
847    pub dropped: u32,
848}
849
850unsafe fn tedit(t: *mut seekdas_trigger, f: impl FnOnce(Trigger) -> Result<Trigger>) -> c_int {
851    guard(|| {
852        let t = obj(t, "trigger")?;
853        t.0 = f(t.0.clone())?;
854        Ok(SEEKDAS_OK)
855    })
856}
857
858fn edge(code: c_int) -> Result<Edge> {
859    match code {
860        1 => Ok(Edge::Rising),
861        2 => Ok(Edge::Falling),
862        3 => Ok(Edge::Both),
863        _ => Err(arg("edge: SEEKDAS_EDGE_RISING (1), SEEKDAS_EDGE_FALLING (2) or SEEKDAS_EDGE_BOTH (3)")),
864    }
865}
866
867fn conv(channel_index: c_int, edge_code: c_int, threshold: c_int, hysteresis: c_int, min_interval: u32) -> Result<ConvChannel> {
868    if !(-8192..=8191).contains(&threshold) || !(0..=8191).contains(&hysteresis) {
869        return Err(arg("threshold -8192..=8191, hysteresis 0..=8191"));
870    }
871    Ok(ConvChannel::new(channel(channel_index)?, edge(edge_code)?, threshold as i16).hysteresis(hysteresis as u16).min_interval(min_interval))
872}
873
874#[no_mangle]
875pub extern "C" fn seekdas_trigger_new() -> *mut seekdas_trigger {
876    Box::into_raw(Box::new(seekdas_trigger(Trigger::new())))
877}
878
879#[no_mangle]
880pub unsafe extern "C" fn seekdas_trigger_free(t: *mut seekdas_trigger) {
881    if !t.is_null() {
882        drop(Box::from_raw(t));
883    }
884}
885
886#[no_mangle]
887pub unsafe extern "C" fn seekdas_trigger_target(t: *mut seekdas_trigger, channel_mask: u32, points_per_channel: u32) -> c_int {
888    tedit(t, |t| {
889        if channel_mask > 0xFFF {
890            return Err(arg("channel mask: 12 bits"));
891        }
892        t.target(ChannelMask::from_bits(channel_mask as u16), points_per_channel)
893    })
894}
895
896#[no_mangle]
897pub unsafe extern "C" fn seekdas_trigger_conv(t: *mut seekdas_trigger, channel_index: c_int, edge_code: c_int, threshold: c_int) -> c_int {
898    tedit(t, |t| t.clear_conv_channels().add_conv_channel(conv(channel_index, edge_code, threshold, 200, 0)?))
899}
900
901#[no_mangle]
902pub unsafe extern "C" fn seekdas_trigger_add_conv(t: *mut seekdas_trigger, channel_index: c_int, edge_code: c_int, threshold: c_int, hysteresis: c_int,
903                                                  min_interval: u32) -> c_int {
904    tedit(t, |t| t.add_conv_channel(conv(channel_index, edge_code, threshold, hysteresis, min_interval)?))
905}
906
907#[no_mangle]
908pub unsafe extern "C" fn seekdas_trigger_remove_conv(t: *mut seekdas_trigger, channel_index: c_int) -> c_int {
909    tedit(t, |t| Ok(t.remove_conv_channel(channel(channel_index)?)))
910}
911
912#[no_mangle]
913pub unsafe extern "C" fn seekdas_trigger_clear_conv(t: *mut seekdas_trigger) -> c_int {
914    tedit(t, |t| Ok(t.clear_conv_channels()))
915}
916
917#[no_mangle]
918pub unsafe extern "C" fn seekdas_trigger_conv_count(t: *const seekdas_trigger) -> c_int {
919    t.as_ref().map_or(0, |t| t.0.conv_channels().len() as c_int)
920}
921
922#[no_mangle]
923pub unsafe extern "C" fn seekdas_trigger_bandwidth(t: *mut seekdas_trigger, bandwidth_hz: f64) -> c_int {
924    tedit(t, |t| t.bandwidth(bandwidth_hz))
925}
926
927#[no_mangle]
928pub unsafe extern "C" fn seekdas_trigger_raw(t: *mut seekdas_trigger) -> c_int {
929    tedit(t, |t| Ok(t.raw()))
930}
931
932#[no_mangle]
933pub unsafe extern "C" fn seekdas_trigger_timestamps(t: *mut seekdas_trigger, on: c_int) -> c_int {
934    tedit(t, |t| Ok(t.timestamps(on != 0)))
935}
936
937#[no_mangle]
938pub unsafe extern "C" fn seekdas_trigger_packet_beats(t: *mut seekdas_trigger, beats: u32) -> c_int {
939    tedit(t, |t| {
940        if !(8..=1020).contains(&beats) {
941            return Err(arg("packet beats 8..=1020"));
942        }
943        Ok(t.packet_beats(beats as u16))
944    })
945}
946
947#[no_mangle]
948pub unsafe extern "C" fn seekdas_trigger_time_calibration(t: *mut seekdas_trigger, ticks: i16) -> c_int {
949    tedit(t, |t| Ok(t.time_calibration(ticks)))
950}
951
952#[no_mangle]
953pub unsafe extern "C" fn seekdas_trigger_validate(t: *const seekdas_trigger) -> c_int {
954    guard(|| {
955        t.as_ref().ok_or_else(|| arg("trigger: null pointer"))?.0.to_config()?;
956        Ok(SEEKDAS_OK)
957    })
958}
959
960#[no_mangle]
961pub unsafe extern "C" fn seekdas_trigger_start(dev: *mut seekdas_device, t: *const seekdas_trigger) -> c_int {
962    guard(|| {
963        let d = obj(dev, "dev")?;
964        let cfg = t.as_ref().ok_or_else(|| arg("trigger: null pointer"))?.0.to_config()?;
965        d.ensure_idle()?;
966        if d.pending.is_some() && d.stream.as_ref().is_some_and(|s| !s.is_finished()) {
967            return Err(Error::Busy("the data of the previous trigger has not all been received: call seekdas_trigger_wait until it returns 1, \
968                                    or seekdas_finish to drop it".into()));
969        }
970        d.io().configure(&cfg)?;
971        d.start_stream()?;
972        d.pending = Some(Capture::new());
973        Ok(SEEKDAS_OK)
974    })
975}
976
977#[no_mangle]
978pub unsafe extern "C" fn seekdas_trigger_get_state(dev: *mut seekdas_device, out: *mut seekdas_trigger_state) -> c_int {
979    guard(|| {
980        let s = obj(dev, "dev")?.io().trigger_state()?;
981        *obj(out, "out")? = seekdas_trigger_state {
982            state: match s.state { RunState::Idle => 0, RunState::Running => 1, RunState::Done => 2 },
983            running: s.running as u8,
984            start_allowed: s.start_allowed as u8,
985            complete: s.complete as u8,
986            rejected: s.rejected as u8,
987            points: s.points,
988            target_points: s.target_points,
989            channel_mask: s.channels.bits() as u32,
990            conv_edges: s.conv_edges,
991            lost: s.counters.lost,
992            late: s.counters.late,
993            dropped: s.counters.dropped,
994        };
995        Ok(SEEKDAS_OK)
996    })
997}
998
999#[no_mangle]
1000pub unsafe extern "C" fn seekdas_trigger_wait(dev: *mut seekdas_device, timeout_ms: u32, capture: *mut *mut seekdas_capture) -> c_int {
1001    guard(|| {
1002        let d = obj(dev, "dev")?;
1003        let out = obj(capture, "capture")?;
1004        let (Some(stream), Some(cap)) = (d.stream.as_mut(), d.pending.as_mut()) else {
1005            return Err(arg("no trigger started: call seekdas_trigger_start first"));
1006        };
1007        if !stream.recv_into(cap, Duration::from_millis(timeout_ms as u64))? {
1008            return Ok(0);
1009        }
1010        let stream = d.stream.take().unwrap();
1011        let cap = d.pending.take().unwrap();
1012        let cap = cap.finish(stream.finish()?)?;
1013        *out = Box::into_raw(Box::new(seekdas_capture(cap)));
1014        Ok(1)
1015    })
1016}
1017
1018#[no_mangle]
1019pub unsafe extern "C" fn seekdas_trigger_run(dev: *mut seekdas_device, t: *const seekdas_trigger, idle_timeout_ms: u32, capture: *mut *mut seekdas_capture) -> c_int {
1020    guard(|| {
1021        let out = obj(capture, "capture")?;
1022        let rc = seekdas_trigger_start(dev, t);
1023        if rc < 0 {
1024            return Ok(rc);
1025        }
1026        let d = obj(dev, "dev")?;
1027        let idle = Duration::from_millis(if idle_timeout_ms == 0 { 10_000 } else { idle_timeout_ms as u64 });
1028        let mut last = std::time::Instant::now();
1029        let mut have = 0usize;
1030        loop {
1031            let stream = d.stream.as_mut().unwrap();
1032            let cap = d.pending.as_mut().unwrap();
1033            if stream.recv_into(cap, Duration::from_millis(100))? {
1034                break;
1035            }
1036            let n = cap.group(0).len() + cap.group(1).len();
1037            if n != have {
1038                have = n;
1039                last = std::time::Instant::now();
1040            } else if last.elapsed() > idle {
1041                return Err(Error::Timeout(format!("no data for {:.1} s; {n} points received (no CONV edges?); the run is still active, \
1042                                                   call seekdas_trigger_wait to go on or seekdas_stop to end it", idle.as_secs_f64())));
1043            }
1044        }
1045        let stream = d.stream.take().unwrap();
1046        let cap = d.pending.take().unwrap();
1047        let cap = cap.finish(stream.finish()?)?;
1048        *out = Box::into_raw(Box::new(seekdas_capture(cap)));
1049        Ok(SEEKDAS_OK)
1050    })
1051}
1052
1053// ---------------------------------------------------------------- AT commands (serial port)
1054
1055/// 串口上的 AT 指令客户端。
1056pub struct seekdas_at(SerialAtClient);
1057
1058/// `ATI` 的应答。
1059#[repr(C)]
1060pub struct seekdas_at_version {
1061    pub channels: u32,
1062    pub slots: u32,
1063    pub pl_version: [c_char; 16],
1064    pub pl_build: [c_char; 24],
1065    pub app_version: [c_char; 16],
1066    pub app_build: [c_char; 32],
1067}
1068
1069/// `AT+STATUS?` 的应答。
1070#[repr(C)]
1071pub struct seekdas_at_status {
1072    pub uptime_s: f64,
1073    pub die_temperature_c: f64,
1074    pub sample_clock_mhz: f64,
1075    pub selftest: u32,
1076    pub fifo_errors: u32,
1077    pub taps: [i32; 3],
1078    pub power: [u8; 5],
1079    pub adc_aligned: [u8; 3],
1080    pub lasers: [u8; 2],
1081    pub adc_power: u8,
1082    pub receivers_active: u8,
1083    pub running: u8,
1084    pub host_ip: [c_char; 16],
1085}
1086
1087/// 一路 CONV 来源。
1088#[repr(C)]
1089#[derive(Clone, Copy)]
1090pub struct seekdas_conv_source {
1091    pub channel: i32,
1092    /// 0 或 1;-1 = 不在任何组里
1093    pub group: i32,
1094    pub threshold: i32,
1095    pub hysteresis: u32,
1096    pub rising: u8,
1097    pub falling: u8,
1098}
1099
1100/// `target` 参数:0..=11 = 一路输入;0x100 + 槽号 = 一个槽位;0x200 = 全部。
1101fn target(t: c_int) -> Result<Target> {
1102    match t {
1103        0..=11 => Ok(Target::Channel(channel(t)?)),
1104        0x100..=0x102 => Ok(Target::Slot((t - 0x100) as u8)),
1105        0x200 => Ok(Target::All),
1106        _ => Err(arg("target: 0..=11, SEEKDAS_SLOT(0..=2) or SEEKDAS_ALL")),
1107    }
1108}
1109
1110#[no_mangle]
1111pub unsafe extern "C" fn seekdas_at_open(port: *const c_char, at: *mut *mut seekdas_at) -> c_int {
1112    guard(|| {
1113        let out = obj(at, "at")?;
1114        *out = Box::into_raw(Box::new(seekdas_at(AtClient::open(text(port, "port")?)?)));
1115        Ok(SEEKDAS_OK)
1116    })
1117}
1118
1119#[no_mangle]
1120pub unsafe extern "C" fn seekdas_at_close(at: *mut seekdas_at) {
1121    if !at.is_null() {
1122        let _ = catch_unwind(AssertUnwindSafe(|| drop(Box::from_raw(at))));
1123    }
1124}
1125
1126#[no_mangle]
1127pub unsafe extern "C" fn seekdas_at_command(at: *mut seekdas_at, command: *const c_char, timeout_ms: u32, response: *mut c_char, size: usize) -> c_int {
1128    guard(|| {
1129        let a = obj(at, "at")?;
1130        let cmd = text(command, "command")?;
1131        put_str("", response, size);
1132        let r = if timeout_ms == 0 { a.0.command(cmd) } else { a.0.command_timeout(cmd, Duration::from_millis(timeout_ms as u64)) };
1133        match r {
1134            Ok(lines) => {
1135                put_str(&lines.join("\n"), response, size);
1136                Ok(SEEKDAS_OK)
1137            }
1138            Err(Error::At { command, lines }) => {
1139                put_str(&lines.join("\n"), response, size);
1140                Err(Error::At { command, lines })
1141            }
1142            Err(e) => Err(e),
1143        }
1144    })
1145}
1146
1147#[no_mangle]
1148pub unsafe extern "C" fn seekdas_at_ping(at: *mut seekdas_at) -> c_int {
1149    guard(|| obj(at, "at")?.0.ping().map(|_| SEEKDAS_OK))
1150}
1151
1152#[no_mangle]
1153pub unsafe extern "C" fn seekdas_at_get_version(at: *mut seekdas_at, out: *mut seekdas_at_version) -> c_int {
1154    guard(|| {
1155        let out = obj(out, "out")?;
1156        let v = obj(at, "at")?.0.version()?;
1157        out.channels = v.channels;
1158        out.slots = v.slots;
1159        put_str(&v.pl_version, out.pl_version.as_mut_ptr(), 16);
1160        put_str(&v.pl_build, out.pl_build.as_mut_ptr(), 24);
1161        put_str(&v.app_version, out.app_version.as_mut_ptr(), 16);
1162        put_str(&v.app_build, out.app_build.as_mut_ptr(), 32);
1163        Ok(SEEKDAS_OK)
1164    })
1165}
1166
1167#[no_mangle]
1168pub unsafe extern "C" fn seekdas_at_get_status(at: *mut seekdas_at, out: *mut seekdas_at_status) -> c_int {
1169    guard(|| {
1170        let out = obj(out, "out")?;
1171        let s = obj(at, "at")?.0.status()?;
1172        *out = seekdas_at_status {
1173            uptime_s: s.uptime.as_secs_f64(), die_temperature_c: s.die_temperature_c, sample_clock_mhz: s.sample_clock_mhz, selftest: s.selftest,
1174            fifo_errors: s.fifo_errors, taps: s.taps, power: s.power.map(|v| v as u8), adc_aligned: s.adc_aligned.map(|v| v as u8),
1175            lasers: s.lasers.map(|v| v as u8), adc_power: s.adc_power as u8, receivers_active: s.receivers_active as u8, running: s.running as u8,
1176            host_ip: [0; 16],
1177        };
1178        put_str(&s.host_ip.to_string(), out.host_ip.as_mut_ptr(), 16);
1179        Ok(SEEKDAS_OK)
1180    })
1181}
1182
1183#[no_mangle]
1184pub unsafe extern "C" fn seekdas_at_selftest_result(at: *mut seekdas_at, done: *mut c_int, passed: *mut c_int, failed_items: *mut u32) -> c_int {
1185    guard(|| {
1186        let r = obj(at, "at")?.0.selftest_result()?;
1187        if let Some(p) = done.as_mut() {
1188            *p = r.done as c_int;
1189        }
1190        if let Some(p) = passed.as_mut() {
1191            *p = r.passed as c_int;
1192        }
1193        if let Some(p) = failed_items.as_mut() {
1194            *p = r.failed_items;
1195        }
1196        Ok(SEEKDAS_OK)
1197    })
1198}
1199
1200#[no_mangle]
1201pub unsafe extern "C" fn seekdas_at_run_selftest(at: *mut seekdas_at, passed: *mut c_int, failed_items: *mut u32, report: *mut c_char, size: usize) -> c_int {
1202    guard(|| {
1203        let r = obj(at, "at")?.0.run_selftest()?;
1204        if let Some(p) = passed.as_mut() {
1205            *p = r.passed as c_int;
1206        }
1207        if let Some(p) = failed_items.as_mut() {
1208            *p = r.failed_items;
1209        }
1210        put_str(&r.lines.join("\n"), report, size);
1211        Ok(SEEKDAS_OK)
1212    })
1213}
1214
1215#[no_mangle]
1216pub unsafe extern "C" fn seekdas_at_set_lasers(at: *mut seekdas_at, sfp0: c_int, sfp1: c_int) -> c_int {
1217    guard(|| obj(at, "at")?.0.set_lasers(sfp0 != 0, sfp1 != 0).map(|_| SEEKDAS_OK))
1218}
1219
1220#[no_mangle]
1221pub unsafe extern "C" fn seekdas_at_set_adc_power(at: *mut seekdas_at, on: c_int) -> c_int {
1222    guard(|| obj(at, "at")?.0.set_adc_power(on != 0).map(|_| SEEKDAS_OK))
1223}
1224
1225#[no_mangle]
1226pub unsafe extern "C" fn seekdas_at_set_range(at: *mut seekdas_at, target_code: c_int, range_volts: c_int) -> c_int {
1227    guard(|| {
1228        let r = Range::from_volts(u32::try_from(range_volts).map_err(|_| arg("range: 10, 5 or 2"))?)?;
1229        obj(at, "at")?.0.set_range(target(target_code)?, r).map(|_| SEEKDAS_OK)
1230    })
1231}
1232
1233#[no_mangle]
1234pub unsafe extern "C" fn seekdas_at_get_ranges(at: *mut seekdas_at, range_volts: *mut c_int) -> c_int {
1235    guard(|| {
1236        if range_volts.is_null() {
1237            return Err(arg("range_volts: null pointer"));
1238        }
1239        for (i, r) in obj(at, "at")?.0.ranges()?.iter().enumerate() {
1240            *range_volts.add(i) = r.volts() as c_int;
1241        }
1242        Ok(SEEKDAS_OK)
1243    })
1244}
1245
1246#[no_mangle]
1247pub unsafe extern "C" fn seekdas_at_read(at: *mut seekdas_at, channel_index: c_int, window_index: c_int, out: *mut seekdas_window_stats) -> c_int {
1248    guard(|| {
1249        let out = obj(out, "out")?;
1250        let r = obj(at, "at")?.0.read(Target::Channel(channel(channel_index)?), window(window_index)?)?;
1251        match r.first().and_then(|r| r.stats) {
1252            Some(w) => {
1253                *out = wstats(&w);
1254                Ok(1)
1255            }
1256            None => Ok(0),
1257        }
1258    })
1259}
1260
1261#[no_mangle]
1262pub unsafe extern "C" fn seekdas_at_read_all(at: *mut seekdas_at, window_index: c_int, out: *mut seekdas_window_stats, valid: *mut u8) -> c_int {
1263    guard(|| {
1264        if out.is_null() {
1265            return Err(arg("out: null pointer"));
1266        }
1267        for r in obj(at, "at")?.0.read(Target::All, window(window_index)?)? {
1268            let i = r.channel.index();
1269            *out.add(i) = r.stats.map_or_else(Default::default, |w| wstats(&w));
1270            if !valid.is_null() {
1271                *valid.add(i) = r.stats.is_some() as u8;
1272            }
1273        }
1274        Ok(SEEKDAS_OK)
1275    })
1276}
1277
1278#[no_mangle]
1279pub unsafe extern "C" fn seekdas_at_uptime_ms(at: *mut seekdas_at, milliseconds: *mut u64) -> c_int {
1280    guard(|| {
1281        *obj(milliseconds, "milliseconds")? = obj(at, "at")?.0.uptime()?.as_millis() as u64;
1282        Ok(SEEKDAS_OK)
1283    })
1284}
1285
1286#[no_mangle]
1287pub unsafe extern "C" fn seekdas_at_get_host_ip(at: *mut seekdas_at, ip: *mut c_char, size: usize) -> c_int {
1288    guard(|| {
1289        put_str(&obj(at, "at")?.0.host_ip()?.to_string(), ip, size);
1290        Ok(SEEKDAS_OK)
1291    })
1292}
1293
1294#[no_mangle]
1295pub unsafe extern "C" fn seekdas_at_set_host_ip(at: *mut seekdas_at, ip: *const c_char) -> c_int {
1296    guard(|| {
1297        let ip = text(ip, "ip")?.parse().map_err(|_| arg("ip: not an IPv4 address"))?;
1298        obj(at, "at")?.0.set_host_ip(ip).map(|_| SEEKDAS_OK)
1299    })
1300}
1301
1302#[no_mangle]
1303pub unsafe extern "C" fn seekdas_at_conv_sources(at: *mut seekdas_at, out: *mut seekdas_conv_source, capacity: usize, count: *mut usize) -> c_int {
1304    guard(|| {
1305        let list = obj(at, "at")?.0.conv_sources()?;
1306        *obj(count, "count")? = list.len();
1307        for (i, s) in list.iter().take(if out.is_null() { 0 } else { capacity }).enumerate() {
1308            *out.add(i) = seekdas_conv_source { channel: s.channel.index() as i32, group: s.group.map_or(-1, |g| g as i32), threshold: s.threshold,
1309                                                hysteresis: s.hysteresis, rising: s.rising as u8, falling: s.falling as u8 };
1310        }
1311        Ok(SEEKDAS_OK)
1312    })
1313}
1314
1315#[no_mangle]
1316pub unsafe extern "C" fn seekdas_at_set_conv_sources(at: *mut seekdas_at, channels: *const c_int, count: usize) -> c_int {
1317    guard(|| {
1318        let idx: &[c_int] = if count == 0 { &[] } else if channels.is_null() { return Err(arg("channels: null pointer")) } else { std::slice::from_raw_parts(channels, count) };
1319        let list: Result<Vec<Channel>> = idx.iter().map(|&c| channel(c)).collect();
1320        obj(at, "at")?.0.set_conv_sources(&list?).map(|_| SEEKDAS_OK)
1321    })
1322}
1323
1324#[no_mangle]
1325pub unsafe extern "C" fn seekdas_at_add_conv_source(at: *mut seekdas_at, source: *const seekdas_conv_source) -> c_int {
1326    guard(|| {
1327        let s = source.as_ref().ok_or_else(|| arg("source: null pointer"))?;
1328        let src = ConvSource { channel: channel(s.channel)?, group: u8::try_from(s.group).ok(), rising: s.rising != 0, falling: s.falling != 0,
1329                               threshold: s.threshold, hysteresis: s.hysteresis };
1330        obj(at, "at")?.0.add_conv_source(&src).map(|_| SEEKDAS_OK)
1331    })
1332}
1333
1334#[no_mangle]
1335pub unsafe extern "C" fn seekdas_at_remove_conv_source(at: *mut seekdas_at, channel_index: c_int) -> c_int {
1336    guard(|| obj(at, "at")?.0.remove_conv_source(channel(channel_index)?).map(|_| SEEKDAS_OK))
1337}
1338
1339#[no_mangle]
1340pub unsafe extern "C" fn seekdas_at_reg_read(at: *mut seekdas_at, addr: u16, value: *mut u32) -> c_int {
1341    guard(|| {
1342        *obj(value, "value")? = obj(at, "at")?.0.read_reg(addr)?;
1343        Ok(SEEKDAS_OK)
1344    })
1345}
1346
1347#[no_mangle]
1348pub unsafe extern "C" fn seekdas_at_reg_write(at: *mut seekdas_at, addr: u16, value: u32, readback: *mut u32) -> c_int {
1349    guard(|| {
1350        let v = obj(at, "at")?.0.write_reg(addr, value)?;
1351        if let Some(r) = readback.as_mut() {
1352            *r = v;
1353        }
1354        Ok(SEEKDAS_OK)
1355    })
1356}
1357
1358// ---------------------------------------------------------------- software model of the device (feature "emulator")
1359
1360#[cfg(feature = "emulator")]
1361#[path = "../../tests/emu/mod.rs"]
1362mod emu;
1363
1364/// 设备的软件模型(只在特性 `emulator` 下编译),供其他语言的测试使用。
1365#[cfg(feature = "emulator")]
1366pub struct seekdas_emu(#[allow(dead_code)] emu::Emu);
1367
1368#[cfg(feature = "emulator")]
1369#[no_mangle]
1370pub unsafe extern "C" fn seekdas_emu_start(drop_per_mille: u32, run_time_ms: u32, ctrl_port: *mut u16, data_port: *mut u16) -> *mut seekdas_emu {
1371    let e = emu::spawn(emu::Faults { drop: drop_per_mille, drop_retx: drop_per_mille, drop_tail: 0, run_time_ms }, 0);
1372    if let Some(p) = ctrl_port.as_mut() {
1373        *p = e.ctrl_port;
1374    }
1375    if let Some(p) = data_port.as_mut() {
1376        *p = e.data_port;
1377    }
1378    Box::into_raw(Box::new(seekdas_emu(e)))
1379}
1380
1381#[cfg(feature = "emulator")]
1382#[no_mangle]
1383pub unsafe extern "C" fn seekdas_emu_stop(e: *mut seekdas_emu) {
1384    if !e.is_null() {
1385        drop(Box::from_raw(e));
1386    }
1387}