mtui 0.7.1

An extensive Modbus client (TCP, RTU & mock) for your terminal.
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
use crate::app::WriteType;
use crate::compat::Instant;
use crate::custom::{CustomOp, CustomRepr, EnumEntry};
use crate::modbus::{DataBits, DeviceIdAccess, Parity, StopBits, WordOrder};
use crate::num_ops::{cycle, wrap_index};
use crate::register::{RegisterCell, RegisterType};
use serde::{Deserialize, Serialize};
use std::time::Duration;

macro_rules! field_enum {
    ( $(#[$meta:meta])* $vis:vis enum $name:ident { $( $(#[$vmeta:meta])* $variant:ident ),+ $(,)? } ) => {
        $(#[$meta])*
        $vis enum $name { $( $(#[$vmeta])* $variant ),+ }
        impl $name {
            pub const ALL: [$name; field_enum!(@count $($variant)+)] = [$($name::$variant),+];
        }
    };
    (@count) => (0usize);
    (@count $head:ident $($tail:ident)*) => (1usize + field_enum!(@count $($tail)*));
}

macro_rules! popups {
    ( $( $variant:ident $( ( $payload:ty ) )? ),+ $(,)? ) => {
        #[derive(Debug, PartialEq)]
        pub enum Popup {
            $( $variant $( ( $payload ) )? ),+
        }

        #[derive(Clone, Copy, PartialEq, Eq)]
        pub enum PopupKind {
            $( $variant ),+
        }

        impl Popup {
            pub fn kind(&self) -> PopupKind {
                match self {
                    $( Popup::$variant { .. } => PopupKind::$variant ),+
                }
            }
        }
    };
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterfaceKind {
    Mock,
    Wired,
    Network,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscoveryField {
    Interface,
    Port,
    Baud,
    DataBits,
    Parity,
    StopBits,
    Ip,
    NetPort,
    SlaveId,
    ConnectTimeout,
    CommandTimeout,
    BetweenCommands,
    WordOrder,
    ScanNetwork,
    Connect,
}

#[derive(Debug, PartialEq)]
pub struct DiscoveryParams {
    pub interface: InterfaceKind,
    pub selected: u16,
    pub ports: Vec<String>,
    pub port_index: u16,
    pub baud_rate: u32,
    pub data_bits: DataBits,
    pub parity: Parity,
    pub stop_bits: StopBits,
    pub ip: String,
    pub net_port: u16,
    pub slave_id: u8,
    pub connect_timeout_ms: u64,
    pub command_timeout_ms: u64,
    pub between_commands_ms: u64,
    pub word_order: WordOrder,
    pub found: Vec<String>,
    pub scan_open: bool,
    pub scan_selected: u16,
    pub status: Option<StatusMessage>,
    pub previous: Option<ReadParams>,
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn local_subnet_prefix() -> Option<String> {
    match local_ip_address::local_ip().ok()? {
        std::net::IpAddr::V4(ip) if !ip.is_loopback() => {
            let [a, b, c, _] = ip.octets();
            Some(format!("{a}.{b}.{c}."))
        }
        _ => None,
    }
}

#[cfg(target_arch = "wasm32")]
pub(crate) fn local_subnet_prefix() -> Option<String> {
    None
}

impl Default for DiscoveryParams {
    fn default() -> Self {
        Self {
            interface: InterfaceKind::Mock,
            selected: 0,
            ports: Vec::new(),
            port_index: 0,
            baud_rate: 9600,
            data_bits: DataBits::Eight,
            parity: Parity::None,
            stop_bits: StopBits::One,
            ip: local_subnet_prefix().unwrap_or_else(|| "127.0.0.1".to_string()),
            net_port: 502,
            slave_id: 1,
            connect_timeout_ms: 1000,
            command_timeout_ms: 2000,
            between_commands_ms: 3,
            word_order: WordOrder::default(),
            found: Vec::new(),
            scan_open: false,
            scan_selected: 0,
            status: None,
            previous: None,
        }
    }
}

impl DiscoveryParams {
    pub fn fields(&self) -> Vec<DiscoveryField> {
        use DiscoveryField::*;
        let mut fields = vec![Interface];
        match self.interface {
            InterfaceKind::Mock => {}
            InterfaceKind::Wired => fields.extend([Port, Baud, DataBits, Parity, StopBits]),
            InterfaceKind::Network => fields.extend([Ip, NetPort, ScanNetwork]),
        }
        fields.extend([
            SlaveId,
            ConnectTimeout,
            CommandTimeout,
            BetweenCommands,
            WordOrder,
            Connect,
        ]);
        fields
    }

    pub fn current_field(&self) -> DiscoveryField {
        let fields = self.fields();
        let i = (self.selected as usize).min(fields.len() - 1);
        fields[i]
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct WriteParams {
    pub position: u16,
    pub result: Option<StatusMessage>,
    pub value: Option<i64>,
    pub write_type: WriteType,
    pub bit_cursor: u16,
    pub force_multiple: bool,
}

#[derive(Debug, Default, PartialEq)]
pub struct LabelParams {
    pub position: u16,
    pub register_type: RegisterType,
    pub text: String,
}

#[derive(Debug, Default, PartialEq)]
pub struct DumpParams {
    pub result: Option<StatusMessage>,
}

#[derive(Debug, Default, PartialEq)]
pub struct ImportParams {
    pub pins: usize,
    pub labels: usize,
    pub rules: usize,
}

#[derive(Debug, Default, PartialEq)]
pub struct DeviceIdParams {
    pub access: DeviceIdAccess,
    pub objects: Vec<(u8, String)>,
    pub status: Option<StatusMessage>,
    pub loading: bool,
}

field_enum! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum RawField {
        Code,
        Data,
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct RawParams {
    pub code: String,
    pub data: String,
    pub selected: u16,
    pub response: Option<String>,
    pub status: Option<StatusMessage>,
}

fn clamp_pick<const N: usize, T: Copy>(selected: u16, all: &[T; N]) -> T {
    all[(selected as usize).min(N - 1)]
}

impl RawParams {
    pub fn current_field(&self) -> RawField {
        clamp_pick(self.selected, &RawField::ALL)
    }
}

field_enum! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum CustomField {
        Repr,
        Ops,
        Enum,
        Decimals,
        Prefix,
        Suffix,
        Save,
        Remove,
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CustomParams {
    pub address: u16,
    pub register_type: RegisterType,
    pub repr: CustomRepr,
    pub ops: Vec<CustomOp>,
    pub enum_map: Vec<EnumEntry>,
    pub decimals: String,
    pub prefix: String,
    pub suffix: String,
    pub op_buffer: String,
    pub enum_buffer: String,
    pub selected: u16,
    pub existed: bool,
    pub error: Option<String>,
}

impl CustomParams {
    pub fn current_field(&self) -> CustomField {
        clamp_pick(self.selected, &CustomField::ALL)
    }
}

field_enum! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum SweepField {
        From,
        To,
        Mode,
        Action,
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SweepConfigParams {
    pub from: u16,
    pub to: u16,
    pub continuous: bool,
    pub selected: u16,
}

impl SweepConfigParams {
    pub fn current_field(&self) -> SweepField {
        clamp_pick(self.selected, &SweepField::ALL)
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct SearchParams {
    pub query: String,
    pub matches: Vec<(RegisterCell, String)>,
    pub selected: u16,
    pub top: u16,
}

impl SearchParams {
    pub fn scroll(&mut self, rows: u16) {
        let len = self.matches.len() as u16;
        scroll_window(&mut self.selected, &mut self.top, rows, len);
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct HelpParams {
    pub query: String,
    pub selected: u16,
}

#[derive(Debug, Default, PartialEq)]
pub struct ColumnsParams {
    pub query: String,
    pub selected: u16,
}

fn scroll_window(cursor: &mut u16, top: &mut u16, rows: u16, len: u16) {
    let rows = rows.max(1);
    if len == 0 {
        *cursor = 0;
        *top = 0;
        return;
    }
    *cursor = (*cursor).min(len - 1);
    if *cursor < *top {
        *top = *cursor;
    } else if *cursor >= top.saturating_add(rows) {
        *top = cursor.saturating_sub(rows - 1);
    }
    if *top >= len {
        *top = len.saturating_sub(rows).min(*cursor);
    }
}

field_enum! {
    #[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
    pub enum ReadPanel {
        #[default]
        Main,
        Pinned,
        Labeled,
        Custom,
        Matrix,
    }
}

impl ReadPanel {
    pub fn name(self) -> &'static str {
        match self {
            ReadPanel::Main => "Main",
            ReadPanel::Pinned => "Pinned",
            ReadPanel::Labeled => "Labeled",
            ReadPanel::Custom => "Custom",
            ReadPanel::Matrix => "Matrix",
        }
    }
}

field_enum! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum SettingsField {
        Name,
        RegistersBatch,
        AutoUpdate,
        HistoryCap,
        MatrixCols,
        ReadOnly,
        LogWrites,
        ApiPort,
        ApiSlaveOverride,
        StartupPanel,
        CycleHoldings,
        CycleInputs,
        CycleCoils,
        CycleDiscretes,
        IgnoreDirty,
        ClearPins,
        ClearLabels,
        ClearCustom,
        ShowContinuation,
        EditKeybinds,
        Save,
        LoadConfig,
    }
}

impl SettingsField {
    pub fn is_text_input(self) -> bool {
        matches!(self, SettingsField::Name | SettingsField::LoadConfig)
    }

    pub fn is_toggle(self) -> bool {
        matches!(
            self,
            SettingsField::ReadOnly
                | SettingsField::ApiSlaveOverride
                | SettingsField::LogWrites
                | SettingsField::ShowContinuation
                | SettingsField::StartupPanel
                | SettingsField::IgnoreDirty
                | SettingsField::CycleHoldings
                | SettingsField::CycleInputs
                | SettingsField::CycleCoils
                | SettingsField::CycleDiscretes
        )
    }

    pub fn cycle_register_type(self) -> Option<RegisterType> {
        Some(match self {
            SettingsField::CycleHoldings => RegisterType::Holding,
            SettingsField::CycleInputs => RegisterType::Input,
            SettingsField::CycleCoils => RegisterType::Coil,
            SettingsField::CycleDiscretes => RegisterType::Discrete,
            _ => return None,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageKind {
    Ok,
    Warn,
    Err,
    Info,
}

#[derive(Debug, Clone, PartialEq)]
pub struct StatusMessage {
    pub text: String,
    pub kind: MessageKind,
}

impl StatusMessage {
    pub fn ok(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            kind: MessageKind::Ok,
        }
    }

    pub fn warn(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            kind: MessageKind::Warn,
        }
    }

    pub fn err(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            kind: MessageKind::Err,
        }
    }

    pub fn info(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            kind: MessageKind::Info,
        }
    }
}

pub type Outcome = Result<String, String>;

impl From<Outcome> for StatusMessage {
    fn from(result: Outcome) -> Self {
        match result {
            Ok(text) => Self::ok(text),
            Err(text) => Self::err(text),
        }
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct SettingsParams {
    pub selected: u16,
    pub status: Option<StatusMessage>,
    pub load_path: String,
    pub previous: ReadParams,
    pub editing_keybinds: bool,
    pub kb_selected: u16,
    pub kb_top: u16,
    pub kb_capturing: bool,
}

impl SettingsParams {
    pub const KB_VISIBLE: u16 = 14;

    pub fn open_keybinds(&mut self) {
        self.editing_keybinds = true;
        self.kb_selected = 0;
        self.kb_top = 0;
        self.kb_capturing = false;
    }

    pub fn kb_move(&mut self, up: bool, count: u16) {
        if count == 0 {
            return;
        }
        self.kb_selected = wrap_index(self.kb_selected, count, !up);
        self.kb_scroll_into_view(count);
    }

    pub fn kb_page(&mut self, up: bool, count: u16) {
        if count == 0 {
            return;
        }
        self.kb_selected = if up {
            self.kb_selected.saturating_sub(Self::KB_VISIBLE)
        } else {
            (self.kb_selected + Self::KB_VISIBLE).min(count - 1)
        };
        self.kb_scroll_into_view(count);
    }

    fn kb_scroll_into_view(&mut self, count: u16) {
        scroll_window(
            &mut self.kb_selected,
            &mut self.kb_top,
            Self::KB_VISIBLE,
            count,
        );
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct LogsParams {
    pub path: String,
    pub lines: Vec<String>,
    pub top: u16,
}

impl LogsParams {
    pub const VISIBLE: u16 = 16;

    pub fn scroll(&mut self, delta: i32) {
        let len = self.lines.len() as i32;
        let max_top = (len - Self::VISIBLE as i32).max(0);
        self.top = (self.top as i32 + delta).clamp(0, max_top) as u16;
    }

    pub fn scroll_to_bottom(&mut self) {
        self.scroll(i32::MAX);
    }
}

popups! {
    Help(HelpParams),
    Dump(DumpParams),
    Search(SearchParams),
    Label(LabelParams),
    Custom(CustomParams),
    Columns(ColumnsParams),
    Write(WriteParams),
    Slave(u16),
    Logs(LogsParams),
    SweepConfig(SweepConfigParams),
    Inspect,
    DeviceId(DeviceIdParams),
    Raw(RawParams),
    Import(ImportParams),
    Quit,
}

#[derive(Debug, PartialEq)]
pub struct ReadParams {
    pub position: u16,
    pub window_start: u16,
    pub col_offset: u16,
    pub panel: ReadPanel,
    pub pinned_index: u16,
    pub pinned_top: u16,
    pub popup: Option<Popup>,
    pub graph: bool,
    pub graph_dword: bool,
    pub refresh_timer: Instant,
    pub register_type: RegisterType,
    pub read_duration: Option<Duration>,
    pub loading: bool,
    pub read_error: Option<String>,
    pub status: Option<StatusMessage>,
    pub status_at: Instant,
}

const STATUS_TTL: Duration = Duration::from_secs(4);

impl Default for ReadParams {
    fn default() -> Self {
        Self {
            position: 0,
            window_start: 0,
            col_offset: 0,
            panel: ReadPanel::Main,
            pinned_index: 0,
            pinned_top: 0,
            popup: None,
            graph: false,
            graph_dword: false,
            refresh_timer: Instant::now(),
            register_type: Default::default(),
            read_duration: None,
            loading: false,
            read_error: None,
            status: None,
            status_at: Instant::now(),
        }
    }
}

impl ReadParams {
    pub fn active_status(&self) -> Option<&StatusMessage> {
        self.status
            .as_ref()
            .filter(|_| self.status_at.elapsed() < STATUS_TTL)
    }

    pub fn scroll_to_cursor(&mut self, rows: u16, matrix_cols: u16) {
        let rows = rows.max(1);
        if self.panel == ReadPanel::Matrix {
            let cols = matrix_cols.max(1);
            let last_row = u16::MAX / cols;
            let max_start_row = last_row.saturating_sub(rows - 1);
            let row = self.position / cols;
            let start_row = row.saturating_sub(rows / 2).min(max_start_row);
            self.window_start = start_row.saturating_mul(cols);
            return;
        }
        let max_start = u16::MAX - (rows - 1);
        self.window_start = self.position.saturating_sub(rows / 2).min(max_start);
    }

    pub fn toggle_panel(&mut self) {
        self.panel = cycle(&ReadPanel::ALL, self.panel, true);
    }

    pub fn scroll_pinned(&mut self, rows: u16, len: u16) {
        scroll_window(&mut self.pinned_index, &mut self.pinned_top, rows, len);
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub enum ConnectionStatus {
    #[default]
    Unknown,
    Reading,
    Connected,
    Reconnecting,
    Error(String),
}

impl ConnectionStatus {
    pub fn code(&self) -> u8 {
        match self {
            ConnectionStatus::Unknown => 0,
            ConnectionStatus::Reading => 1,
            ConnectionStatus::Connected => 2,
            ConnectionStatus::Reconnecting => 3,
            ConnectionStatus::Error(_) => 4,
        }
    }

    pub fn label_from_code(code: u8) -> &'static str {
        match code {
            1 => "reading",
            2 => "connected",
            3 => "reconnecting",
            4 => "error",
            _ => "unknown",
        }
    }

    pub fn code_serving(code: u8) -> bool {
        matches!(code, 0..=2)
    }
}

#[derive(Debug, PartialEq)]
pub struct LogViewParams {
    pub top: u16,
    pub follow: bool,
    pub previous: ReadParams,
}

#[derive(Debug, PartialEq)]
pub enum State {
    Read(ReadParams),
    Discovery(DiscoveryParams),
    Settings(SettingsParams),
    Logs(LogViewParams),
}