twinleaf-tools 2.2.0

Tools for the Twinleaf I/O protocol for reading data from Twinleaf quantum sensors.
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
use clap::{
    builder::{PossibleValuesParser, TypedValueParser, ValueHint},
    Subcommand, ValueEnum,
};
use clap_complete::Shell;
use twinleaf::device::RpcValueType;

const RPC_TYPE_NAMES: &[&str] = &[
    "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "f32", "f64", "string",
];

fn parse_rpc_type(s: &str) -> RpcValueType {
    match s {
        "u8" => RpcValueType::Int { signed: false, size: 1 },
        "u16" => RpcValueType::Int { signed: false, size: 2 },
        "u32" => RpcValueType::Int { signed: false, size: 4 },
        "u64" => RpcValueType::Int { signed: false, size: 8 },
        "i8" => RpcValueType::Int { signed: true, size: 1 },
        "i16" => RpcValueType::Int { signed: true, size: 2 },
        "i32" => RpcValueType::Int { signed: true, size: 4 },
        "i64" => RpcValueType::Int { signed: true, size: 8 },
        "f32" => RpcValueType::Float { size: 4 },
        "f64" => RpcValueType::Float { size: 8 },
        "string" => RpcValueType::String { max_len: None },
        // PossibleValuesParser validates against RPC_TYPE_NAMES first.
        _ => unreachable!("possible values already validated"),
    }
}

#[derive(Parser, Debug)]
#[command(
    name = "tio",
    version,
    about = "Twinleaf sensor management and data logging tool",
    disable_help_subcommand = true,
)]
pub struct TioCli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// List connected devices
    List {
        /// Include serial ports with unknown VID/PID
        #[arg(short = 'a', long = "all")]
        all: bool,
    },

    /// Live sensor data display
    Monitor {
        #[command(flatten)]
        tio: TioOpts,
        #[arg(long = "fps", default_value_t = 20)]
        fps: u32,
        #[arg(short = 'c', long = "colors")]
        colors: Option<String>,
        /// Routing depth limit (default: unlimited)
        #[arg(long = "depth")]
        depth: Option<usize>,
    },

    /// Live timing and rate diagnostics
    Health(HealthCli),

    /// Dump raw packets from a device
    Dump {
        #[command(flatten)]
        tio: TioOpts,

        /// Show parsed data samples
        #[arg(short = 'd', long = "data")]
        data: bool,

        /// Show metadata on boundaries
        #[arg(short = 'm', long = "meta")]
        meta: bool,

        /// Routing depth limit (default: unlimited)
        #[arg(long = "depth")]
        depth: Option<usize>,
    },

    /// Log samples to a file
    #[command(args_conflicts_with_subcommands = true)]
    Log {
        #[command(flatten)]
        tio: TioOpts,

        #[command(subcommand)]
        subcommands: Option<LogSubcommands>,

        /// Output log file path
        #[arg(short = 'f', default_value_t = default_log_path())]
        file: String,

        /// Unbuffered output (flush every packet)
        #[arg(short = 'u')]
        unbuffered: bool,

        /// Raw mode: skip metadata request and dump all packets
        #[arg(long)]
        raw: bool,

        /// Routing depth (only used in --raw mode)
        #[arg(long = "depth")]
        depth: Option<usize>,

        /// Stop after this wall-clock duration (e.g. 30s, 5m, 2h)
        #[arg(long, value_parser = humantime::parse_duration)]
        duration: Option<std::time::Duration>,
    },

    /// Execute a device RPC
    #[command(args_conflicts_with_subcommands = true, arg_required_else_help = true)]
    Rpc {
        #[command(flatten)]
        tio: TioOpts,

        #[command(subcommand)]
        subcommands: Option<RPCSubcommands>,

        /// RPC name to execute
        #[arg(value_hint = ValueHint::Other)]
        rpc_name: Option<String>,

        /// RPC argument value
        #[arg(
            allow_negative_numbers = true,
            value_name = "ARG",
            value_hint = ValueHint::Other,
            help_heading = "RPC Arguments"
        )]
        rpc_arg: Option<String>,

        /// RPC request type
        #[arg(
            short = 't',
            long = "req-type",
            value_parser = PossibleValuesParser::new(RPC_TYPE_NAMES).map(|s: String| parse_rpc_type(&s)),
            help_heading = "Type Options",
        )]
        req_type: Option<RpcValueType>,

        /// RPC reply type
        #[arg(
            short = 'T',
            long = "rep-type",
            value_parser = PossibleValuesParser::new(RPC_TYPE_NAMES).map(|s: String| parse_rpc_type(&s)),
            help_heading = "Type Options",
        )]
        rep_type: Option<RpcValueType>,

        /// Enable debug output
        #[arg(short = 'd', long)]
        debug: bool,
    },

    /// Upgrade device firmware
    #[command(alias = "firmware-upgrade")]
    Upgrade {
        #[command(flatten)]
        tio: TioOpts,

        /// Input firmware image path
        #[arg(value_hint = ValueHint::FilePath, value_parser = parse_existing_file)]
        firmware_path: PathBuf,

        /// Skip confirmation prompt
        #[arg(short = 'y', long = "yes")]
        yes: bool,
    },

    /// Multiplex a sensor over TCP
    Proxy(ProxyCli),

    /// Run a simulated sine wave Twinleaf device over UDP
    Test(TestCli),

    /// Generate shell completions for tio
    #[command(long_about = "\
Generate shell completions for tio.

Add one of these lines to your shell's config file:

  Bash (~/.bashrc):
    eval \"$(tio completions bash)\"

  Zsh (~/.zshrc):
    eval \"$(tio completions zsh)\"

  Fish (~/.config/fish/config.fish):
    tio completions fish | source

  PowerShell ($PROFILE):
    tio completions powershell | Invoke-Expression")]
    Completions {
        #[arg(value_enum)]
        shell: Shell,
    },
}

#[derive(Subcommand, Debug)]
pub enum RPCSubcommands {
    /// List available RPCs on the device
    List {
        #[command(flatten)]
        tio: TioOpts,
    },
    /// Dump RPC data from the device
    Dump {
        #[command(flatten)]
        tio: TioOpts,

        /// RPC name to dump
        #[arg(value_hint = ValueHint::Other)]
        rpc_name: String,

        /// Trigger a capture before dumping
        #[arg(long)]
        capture: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum LogSubcommands {
    /// Log metadata to a file. See "tio log meta --help" for more options
    #[command(args_conflicts_with_subcommands = true)]
    Meta {
        #[command(flatten)]
        tio: TioOpts,

        #[command(subcommand)]
        subcommands: Option<MetaSubcommands>,

        /// Output metadata file path
        #[arg(short = 'f', default_value = "meta.tio")]
        file: String,
    },

    /// Dump data from binary log file(s)
    Dump {
        /// Input log file(s)
        #[arg(value_hint = ValueHint::FilePath, required = true, num_args = 1..)]
        files: Vec<String>,

        /// Show parsed data samples
        #[arg(short = 'd', long = "data")]
        data: bool,

        /// Show metadata on boundaries
        #[arg(short = 'm', long = "meta")]
        meta: bool,

        /// Sensor path in the sensor tree (e.g., /, /0, /0/1)
        #[arg(short = 's', long = "sensor", default_value = "/")]
        sensor: String,

        /// Routing depth limit (default: unlimited)
        #[arg(long = "depth")]
        depth: Option<usize>,
    },

    /// Summarize the contents of binary log file(s)
    Inspect {
        /// Input log file(s)
        #[arg(value_hint = ValueHint::FilePath, required = true, num_args = 1..)]
        files: Vec<String>,
    },

    /// Convert binary log data to CSV
    Csv {
        /// Stream ID/name and input .tio files (order-independent)
        #[arg(value_hint = ValueHint::FilePath)]
        args: Vec<String>,

        /// Sensor route in the device tree (default: /)
        #[arg(short = 's')]
        sensor: Option<String>,

        /// Output filename prefix
        #[arg(short = 'o')]
        output: Option<String>,
    },

    /// Convert binary log files to HDF5 format
    #[command(alias = "hdf5")]
    Hdf {
        /// Input log file(s)
        #[arg(value_hint = ValueHint::FilePath, required = true, num_args = 1..)]
        files: Vec<String>,

        /// Output file path (defaults to input filename with .h5 extension)
        #[arg(short = 'o')]
        output: Option<String>,

        /// Filter streams using a glob pattern (e.g. "/*/vector")
        #[arg(short = 'g', long = "glob")]
        filter: Option<String>,

        /// Enable deflate compression (saves space, slows down write significantly)
        #[arg(short = 'c', long = "compress")]
        compress: bool,

        /// Enable debug output for glob matching
        #[arg(short = 'd', long)]
        debug: bool,

        /// How to organize runs in the output (none=flat, stream=per-stream, device=per-device, global=all-shared)
        #[arg(short = 'l', long = "split", default_value = "none")]
        split_level: SplitLevel,

        /// When to detect discontinuities (continuous=any gap, monotonic=only time backward)
        #[arg(short = 'p', long = "policy", default_value = "continuous")]
        split_policy: SplitPolicy,
    },
}

#[derive(Subcommand, Debug)]
pub enum MetaSubcommands {
    /// Reroute metadata packets in a metadata file
    Reroute {
        /// Input metadata file path
        #[arg(value_hint = ValueHint::FilePath)]
        input: String,

        /// New device route (e.g., /0/1)
        #[arg(short = 's', long = "sensor")]
        route: String,

        /// Output metadata file path (defaults to <input>_rerouted.tio)
        #[arg(short = 'o', long = "output")]
        output: Option<String>,
    },
}

fn default_log_path() -> String {
    chrono::Local::now()
        .format("log.%Y%m%d-%H%M%S.tio")
        .to_string()
}

/// Controls when discontinuities trigger run splits
#[derive(ValueEnum, Clone, Debug, Default)]
pub enum SplitPolicy {
    /// Split on any discontinuity (gaps, rate changes, etc.)
    #[default]
    Continuous,
    /// Only split when time goes backward (allows gaps)
    Monotonic,
}

#[cfg(feature = "hdf5")]
impl From<SplitPolicy> for twinleaf::data::export::SplitPolicy {
    fn from(policy: SplitPolicy) -> Self {
        match policy {
            SplitPolicy::Continuous => Self::Continuous,
            SplitPolicy::Monotonic => Self::Monotonic,
        }
    }
}

/// Controls how runs are organized in the HDF5 output
#[derive(ValueEnum, Clone, Debug, Default)]
pub enum SplitLevel {
    /// No run splitting - flat structure: /{route}/{stream}/{datasets}
    #[default]
    None,
    /// Each stream has independent run counter
    Stream,
    /// All streams on a device share run counter
    Device,
    /// All streams globally share run counter
    Global,
}

#[cfg(feature = "hdf5")]
impl From<SplitLevel> for twinleaf::data::export::RunSplitLevel {
    fn from(level: SplitLevel) -> Self {
        match level {
            SplitLevel::None => Self::None,
            SplitLevel::Stream => Self::PerStream,
            SplitLevel::Device => Self::PerDevice,
            SplitLevel::Global => Self::Global,
        }
    }
}

#[derive(Parser, Debug, Clone)]
#[command(
    name = "tio-health",
    version,
    about = "Live timing & rate diagnostics for TIO (Twinleaf) devices"
)]
pub struct HealthCli {
    #[command(flatten)]
    tio: TioOpts,

    /// Time window in seconds for calculating jitter statistics
    #[arg(
        long = "jitter-window",
        default_value = "10",
        value_name = "SECONDS",
        value_parser = clap::value_parser!(u64).range(1..),
        help = "Seconds for jitter calculation window (>= 1)"
    )]
    jitter_window: u64,

    /// PPM threshold for yellow warning indicators
    #[arg(
        long = "ppm-warn",
        default_value = "100",
        value_name = "PPM",
        value_parser = nonneg_f64,
        help = "Warning threshold in parts per million (>= 0)"
    )]
    ppm_warn: f64,

    /// PPM threshold for red error indicators
    #[arg(
        long = "ppm-err",
        default_value = "200",
        value_name = "PPM",
        value_parser = nonneg_f64,
        help = "Error threshold in parts per million (>= 0)"
    )]
    ppm_err: f64,

    /// Filter to only show specific stream IDs (comma-separated)
    #[arg(
        long = "streams",
        value_delimiter = ',',
        value_name = "IDS",
        value_parser = clap::value_parser!(u8),
        help = "Comma-separated stream IDs to monitor (e.g., 0,1,5)"
    )]
    streams: Option<Vec<u8>>,

    /// Suppress the footer help text
    #[arg(short = 'q', long = "quiet")]
    quiet: bool,

    /// UI refresh rate for animations and stale detection (data updates are immediate)
    #[arg(
        long = "fps",
        default_value = "30",
        value_name = "FPS",
        value_parser = clap::value_parser!(u64).range(1..=60),
        help = "UI refresh rate for heartbeat animation and stale detection (1–60)"
    )]
    fps: u64,

    /// Time in milliseconds before marking a stream as stale
    #[arg(
        long = "stale-ms",
        default_value = "2000",
        value_name = "MS",
        value_parser = clap::value_parser!(u64).range(1..),
        help = "Mark streams as stale after this many milliseconds without data (>= 1)"
    )]
    stale_ms: u64,

    /// Maximum number of events to keep in the event log
    #[arg(
        short = 'n',
        long = "event-log-size",
        default_value = "100",
        value_name = "N",
        value_parser = clap::value_parser!(u64).range(1..),
        help = "Maximum number of events to keep in history (>= 1)"
    )]
    event_log_size: u64,

    /// Number of event lines to display on screen
    #[arg(
        long = "event-display-lines",
        default_value = "8",
        value_name = "LINES",
        value_parser = clap::value_parser!(u16).range(3..),
        help = "Number of event lines to show (>= 3)"
    )]
    event_display_lines: u16,

    /// Only show warning and error events in the log
    #[arg(short = 'w', long = "warnings-only")]
    warnings_only: bool,
}

impl HealthCli {
    fn stale_dur(&self) -> Duration {
        Duration::from_millis(self.stale_ms)
    }
}

fn nonneg_f64(s: &str) -> Result<f64, String> {
    let v: f64 = s
        .parse()
        .map_err(|e: std::num::ParseFloatError| e.to_string())?;
    if v < 0.0 {
        Err("must be ≥ 0".into())
    } else {
        Ok(v)
    }
}

#[derive(Parser, Debug)]
#[command(
    name = "tio-test",
    version,
    about = "Run a simulated sine wave Twinleaf device over UDP"
)]
pub struct TestCli {
    /// Sample rate in Hz
    #[arg(
        long = "samplerate",
        alias = "sample-rate",
        default_value = "1000",
        value_parser = clap::value_parser!(u32).range(1..)
    )]
    samplerate: u32,

    /// Initial sine wave frequency in Hz
    #[arg(long = "frequency", default_value = "10", value_parser = nonneg_f64)]
    frequency: f64,

    /// Initial sine wave amplitude in V
    #[arg(long = "amplitude", default_value = "1", value_parser = nonneg_f64)]
    amplitude: f64,

    /// Initial white noise level in V/sqrt(Hz)
    #[arg(long = "noise", default_value = ".01", value_parser = nonneg_f64)]
    noise: f64,

    /// Segment duration in seconds
    #[arg(
        long = "segment-seconds",
        default_value = "10",
        value_parser = clap::value_parser!(u32).range(1..)
    )]
    segment_seconds: u32,

    /// UDP port to listen on
    #[arg(long = "port", default_value = "7855")]
    port: u16,
}

#[derive(Parser, Debug)]
#[command(
    name = "tio-proxy",
    version,
    about = "Multiplexes access to a sensor, exposing the functionality of tio::proxy via TCP",
    args_conflicts_with_subcommands = true,
)]
pub struct ProxyCli {
    #[command(subcommand)]
    pub subcommands: Option<ProxySubcommands>,

    /// Sensor URL (e.g., tcp://localhost, serial:///dev/ttyUSB0); defaults to auto-detecting a single connected device
    #[arg(value_hint = ValueHint::Url)]
    sensor_url: Option<String>,

    /// TCP port to listen on for clients
    #[arg(short = 'p', long = "port", default_value = "7855")]
    port: u16,

    /// Kick off slow clients instead of dropping traffic
    #[arg(short = 'k', long)]
    kick_slow: bool,

    /// Sensor subtree to look at
    #[arg(
        short = 's',
        long = "subtree",
        default_value = "/",
        value_parser = parse_device_route,
    )]
    subtree: DeviceRoute,

    /// Verbose output
    #[arg(short = 'v', long)]
    verbose: bool,

    /// Debugging output
    #[arg(short = 'd', long)]
    debug: bool,

    /// Timestamp format
    #[arg(short = 't', long = "timestamp", default_value = "%T%.3f ")]
    timestamp_format: String,

    /// Time limit for sensor reconnection attempts (seconds)
    #[arg(short = 'T', long = "timeout", default_value = "30")]
    reconnect_timeout: u64,

    /// Dump packet traffic except sample data/metadata or heartbeats
    #[arg(long)]
    dump: bool,

    /// Dump sample data traffic
    #[arg(long)]
    dump_data: bool,

    /// Dump sample metadata traffic
    #[arg(long)]
    dump_meta: bool,

    /// Dump heartbeat traffic
    #[arg(long)]
    dump_hb: bool,

    /// Deprecated; running without -s <url> now auto-detects by default.
    #[arg(short = 'a', long = "auto", hide = true)]
    auto: bool,

    /// Deprecated; use `tio list` instead.
    #[arg(short = 'e', long = "enumerate", name = "enum", hide = true)]
    enumerate: bool,
}

#[derive(Subcommand, Debug)]
pub enum ProxySubcommands {
    /// Bridge Twinleaf sensor data to NMEA TCP stream
    Nmea {
        #[command(flatten)]
        tio: TioOpts,

        /// TCP port to listen on
        #[arg(short = 'p', long = "port", default_value = "7800")]
        tcp_port: u16,
    },
}