1use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
4use std::time::{Duration, Instant};
5
6use socket2::{Domain, Protocol, Socket, Type};
7
8use crate::acq::{AcqConfig, AcqStatus};
9use crate::capture::Capture;
10use crate::error::{Error, Result};
11use crate::proto;
12use crate::reg::{self, RegIo};
13use crate::stream::Stream;
14
15#[derive(Clone, Debug)]
17pub struct DeviceConfig {
18 pub addr: Ipv4Addr,
20 pub ctrl_port: u16,
22 pub data_port: u16,
24 pub host_port: u16,
28 pub set_host: bool,
35 pub reg_timeout: Duration,
37 pub reg_retries: u32,
39 pub recv_buffer: usize,
41}
42
43impl DeviceConfig {
44 pub fn new(addr: Ipv4Addr) -> DeviceConfig {
46 DeviceConfig {
47 addr,
48 ctrl_port: 5001,
49 data_port: 5000,
50 host_port: 5000,
51 set_host: true,
52 reg_timeout: Duration::from_millis(200),
53 reg_retries: 8,
54 recv_buffer: 64 << 20,
55 }
56 }
57}
58
59#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct DeviceInfo {
62 pub version: (u8, u8, u16),
64 pub build_date: String,
66 pub build_time: String,
68 pub channels: u8,
70 pub slots: u8,
72}
73
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
76pub struct NetStatus {
77 pub link_up: bool,
79 pub next_seq: u32,
81 pub acked_seq: u32,
83 pub packets_sent: u32,
85 pub retransmitted: u32,
87 pub nacks_received: u32,
89 pub acks_received: u32,
91 pub ddr_write_errors: u32,
93 pub arp_failures: u32,
95 pub ddr_read_errors: u32,
97}
98
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct BoardStatus {
102 pub power_good: bool,
104 pub adc_aligned: [bool; 3],
106 pub running: bool,
108 pub fifo_errors: [bool; 3],
110 pub selftest_done: bool,
112 pub selftest_passed: bool,
114 pub selftest_failed_items: u16,
116 pub lasers: [bool; 2],
118 pub raw: u32,
120}
121
122pub struct Device {
150 pub(crate) ctrl: UdpSocket,
151 pub(crate) data: UdpSocket,
152 pub(crate) dev_data: SocketAddr,
153 pub(crate) cfg: DeviceConfig,
154 tag: u32,
155}
156
157impl Device {
158 pub fn open(addr: Ipv4Addr) -> Result<Device> {
160 Device::open_with(DeviceConfig::new(addr))
161 }
162
163 pub fn open_with(cfg: DeviceConfig) -> Result<Device> {
165 let ctrl = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?;
166 ctrl.connect((cfg.addr, cfg.ctrl_port))?;
167 ctrl.set_read_timeout(Some(cfg.reg_timeout))?;
168
169 let sock = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
170 let _ = sock.set_recv_buffer_size(cfg.recv_buffer);
171 sock.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, cfg.host_port)).into())?;
172 let data: UdpSocket = sock.into();
173 data.set_read_timeout(Some(Duration::from_millis(1)))?;
174
175 let tag = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_millis() as u32);
176 let dev_data = SocketAddr::from((cfg.addr, cfg.data_port));
177 let mut dev = Device { ctrl, data, dev_data, cfg, tag };
178
179 let id = dev.read_reg(reg::ID)?;
180 if id != reg::ID_VALUE {
181 return Err(Error::Device(format!("ID register 0x{id:08X}, expected 0x{:08X}", reg::ID_VALUE)));
182 }
183 if dev.cfg.set_host && dev.read_reg(reg::GATE_CTRL)? & reg::GATE_BUSY == 0 {
186 let host_port = dev.data.local_addr()?.port();
187 let ports = dev.read_reg(reg::NET_PORTS)?;
188 let mut w = vec![(reg::NET_PORTS, (host_port as u32) << 16 | (ports & 0xFFFF))];
189 if let IpAddr::V4(ip) = dev.ctrl.local_addr()?.ip() {
190 w.push((reg::NET_HOST, u32::from(ip)));
191 }
192 dev.write_regs(&w)?;
193 }
194 Ok(dev)
195 }
196
197 pub fn config(&self) -> &DeviceConfig {
199 &self.cfg
200 }
201
202 pub fn host_port(&self) -> Result<u16> {
204 Ok(self.data.local_addr()?.port())
205 }
206
207 fn request(&mut self, write: bool, entries: &[(u16, u32)]) -> Result<Vec<u32>> {
208 let mut out = Vec::with_capacity(entries.len());
209 let mut rx = [0u8; 2048];
210 for part in entries.chunks(proto::MAX_REG_ENTRIES) {
211 self.tag = self.tag.wrapping_add(1);
212 let msg = proto::encode_reg_request(write, self.tag, part);
213 let mut done = false;
214 'retry: for _ in 0..self.cfg.reg_retries.max(1) {
215 self.ctrl.send(&msg)?;
216 let deadline = Instant::now() + self.cfg.reg_timeout;
217 while Instant::now() < deadline {
218 let n = match self.ctrl.recv(&mut rx) {
219 Ok(n) => n,
220 Err(e) if is_timeout(&e) => break,
221 Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset || e.kind() == std::io::ErrorKind::ConnectionRefused => continue,
223 Err(e) => return Err(e.into()),
224 };
225 if let Some((tag, e)) = proto::decode_reg_response(&rx[..n]) {
226 if tag == self.tag && e.len() == part.len() {
227 out.extend(e.iter().map(|x| x.1));
228 done = true;
229 break 'retry;
230 }
231 }
232 }
233 }
234 if !done {
235 return Err(Error::Timeout(format!("no answer from {}:{} (register access)", self.cfg.addr, self.cfg.ctrl_port)));
236 }
237 }
238 Ok(out)
239 }
240
241 pub fn info(&mut self) -> Result<DeviceInfo> {
243 let v = self.read_regs(reg::ID, 5)?;
244 Ok(DeviceInfo {
245 version: ((v[1] >> 24) as u8, (v[1] >> 16) as u8, v[1] as u16),
246 build_date: format!("{:04X}-{:02X}-{:02X}", v[2] >> 16, v[2] >> 8 & 0xFF, v[2] & 0xFF),
247 build_time: format!("{:02X}:{:02X}:{:02X}", v[3] >> 16 & 0xFF, v[3] >> 8 & 0xFF, v[3] & 0xFF),
248 channels: v[4] as u8,
249 slots: (v[4] >> 8 & 0xF) as u8,
250 })
251 }
252
253 pub fn uptime(&mut self) -> Result<Duration> {
255 Ok(Duration::from_millis(self.read_reg(reg::UPTIME_MS)? as u64))
256 }
257
258 pub fn sample_rate_hz(&mut self) -> Result<f64> {
262 Ok(self.read_reg(reg::SYS100)? as f64 * 100.0)
263 }
264
265 pub fn board_status(&mut self) -> Result<BoardStatus> {
267 let b = self.read_reg(reg::BOARD)?;
268 let c = self.read_reg(reg::CTRL)?;
269 let s = self.read_reg(reg::SELFTEST)?;
270 Ok(BoardStatus {
271 power_good: b & 0xF == 0xF,
272 adc_aligned: [b >> 16 & 1 != 0, b >> 17 & 1 != 0, b >> 18 & 1 != 0],
273 running: b >> 19 & 1 != 0,
274 fifo_errors: [b >> 22 & 1 != 0, b >> 23 & 1 != 0, b >> 24 & 1 != 0],
275 selftest_done: s >> 31 != 0,
276 selftest_passed: s >> 30 & 1 != 0,
277 selftest_failed_items: s as u16,
278 lasers: [c >> 4 & 1 != 0, c >> 5 & 1 != 0],
279 raw: b,
280 })
281 }
282
283 pub fn net_status(&mut self) -> Result<NetStatus> {
285 let phy = self.read_reg(reg::PHY)?;
286 let v = self.read_regs(reg::NEXT_SEQ, 10)?;
287 Ok(NetStatus {
288 link_up: phy & 1 != 0,
289 next_seq: v[0],
290 acked_seq: v[1],
291 packets_sent: v[2],
292 retransmitted: v[3],
293 nacks_received: v[4],
294 acks_received: v[5],
295 ddr_write_errors: v[6],
296 arp_failures: v[7],
297 ddr_read_errors: v[9],
298 })
299 }
300
301 pub fn configure(&mut self, cfg: &AcqConfig) -> Result<()> {
303 cfg.apply(self)
304 }
305
306 pub fn acq_status(&mut self) -> Result<AcqStatus> {
308 AcqStatus::read(self)
309 }
310
311 pub fn start(&mut self) -> Result<Stream<'_>> {
316 Stream::start(self)
317 }
318
319 pub fn stop(&mut self) -> Result<()> {
321 self.write_reg(reg::GATE_CTRL, 2).map(|_| ())
322 }
323
324 pub fn acquire(&mut self, cfg: &AcqConfig) -> Result<Capture> {
329 if cfg.total_points() == 0 {
330 return Err(Error::InvalidArgument("acquire() needs a point count; use acquire_for() or start() for an unlimited run".into()));
331 }
332 self.configure(cfg)?;
333 self.start()?.collect(Duration::from_secs(10))
334 }
335
336 pub fn acquire_for(&mut self, cfg: &AcqConfig, duration: Duration) -> Result<Capture> {
338 let mut cfg = cfg.clone();
339 cfg = cfg.points(0);
340 self.configure(&cfg)?;
341 let mut stream = self.start()?;
342 let mut cap = Capture::new();
343 let t0 = Instant::now();
344 let mut stopped = false;
345 while !stream.is_finished() {
346 if !stopped && t0.elapsed() >= duration {
347 stream.stop()?;
348 stopped = true;
349 }
350 if let Some(p) = stream.recv(Duration::from_millis(20))? {
351 cap.push(&p)?;
352 } else if stopped && t0.elapsed() > duration + Duration::from_secs(10) {
353 return Err(Error::Timeout("end packets not received after STOP".into()));
354 }
355 }
356 cap.finish(stream.finish()?)
357 }
358}
359
360impl RegIo for Device {
361 fn read_regs(&mut self, addr: u16, n: usize) -> Result<Vec<u32>> {
362 let e: Vec<(u16, u32)> = (0..n).map(|i| (addr.wrapping_add(4 * i as u16), 0)).collect();
363 self.request(false, &e)
364 }
365
366 fn write_regs(&mut self, pairs: &[(u16, u32)]) -> Result<Vec<u32>> {
367 self.request(true, pairs)
368 }
369}
370
371pub(crate) fn is_timeout(e: &std::io::Error) -> bool {
372 matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)
373}