Skip to main content

live_capture/
live_capture.rs

1//! Stream attendance punches in real time until Ctrl-C.
2//!
3//! Run with: `cargo run --example live_capture -- 192.168.1.201 [port]`
4
5use std::sync::atomic::Ordering;
6use std::time::Duration;
7use zkteco::Zk;
8
9fn main() -> zkteco::ZkResult<()> {
10    let mut args = std::env::args().skip(1);
11    let ip = args.next().expect("usage: live_capture <ip> [port]");
12    let port: u16 = args.next().and_then(|p| p.parse().ok()).unwrap_or(4370);
13
14    let mut zk = Zk::builder(ip)
15        .port(port)
16        .timeout(Duration::from_secs(30))
17        .omit_ping(true)
18        .build();
19
20    zk.connect()?;
21    println!("listening for punches (Ctrl-C to stop)...");
22
23    let mut capture = zk.live_capture(Duration::from_secs(10))?;
24
25    // Stop the loop on Ctrl-C by flipping the shared stop flag.
26    let stop = capture.stop_handle();
27    ctrlc_set(move || stop.store(true, Ordering::SeqCst));
28
29    for event in &mut capture {
30        match event? {
31            Some(att) => println!("punch: {att}"),
32            None => println!("(tick — no punch in the last interval)"),
33        }
34    }
35    println!("stopped.");
36    Ok(())
37}
38
39/// Minimal Ctrl-C handler without pulling in an external crate.
40///
41/// Falls back to doing nothing if the signal can't be registered; the example
42/// still exits on process termination.
43fn ctrlc_set<F: FnOnce() + Send + 'static>(_f: F) {
44    // The `ctrlc` crate is the usual choice in real apps; we keep this example
45    // dependency-free, so this is a no-op placeholder. Replace with your own
46    // signal handling as needed.
47}