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
use std::marker::PhantomData;

use eframe::{egui, egui::Vec2};
use gmt_dos_clients_transceiver::{CompactRecvr, Monitor, Transceiver, TransceiverError};
use interface::UniqueIdentifier;
use tokio::task::JoinError;
use tracing::debug;

mod signal;
use signal::{Signal, SignalProcessing};

use crate::{GmtScope, ImageScope, PlotScope, ScopeKind};

#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    #[error("failed to build transceiver")]
    Transceiver(#[from] TransceiverError),
    #[error("some task didn't terminate successfully")]
    Join(#[from] JoinError),
}
pub type Result<T> = std::result::Result<T, ClientError>;

/// Data scope client
pub struct XScope<K = PlotScope>
where
    K: ScopeKind,
{
    server_ip: String,
    client_address: String,
    monitor: Option<Monitor>,
    signals: Vec<Box<dyn SignalProcessing>>,
    min_recvr: Option<CompactRecvr>,
    kind: PhantomData<K>,
}
impl<K: ScopeKind> XScope<K> {
    /// Creates a new scope
    ///
    /// A scope is build from both the server IP and the client internet socket addresses
    pub fn new<S: Into<String>>(server_ip: S, client_address: S) -> Self {
        Self {
            monitor: Some(Monitor::new()),
            server_ip: server_ip.into(),
            client_address: client_address.into(),
            signals: Vec::new(),
            min_recvr: None,
            kind: PhantomData,
        }
    }
    /// Adds a signal to the scope
    pub fn signal<U>(mut self, port: u32) -> Result<Self>
    where
        U: UniqueIdentifier + 'static,
    {
        let server_address = format!("{}:{}", self.server_ip, port);
        let rx = if let Some(min_recvr) = self.min_recvr.as_ref() {
            min_recvr.spawn(server_address)?
        } else {
            let recvr = Transceiver::<crate::payload::ScopeData<U>>::receiver(
                server_address,
                &self.client_address,
            )?;
            self.min_recvr = Some(CompactRecvr::from(&recvr));
            recvr
        }
        .run(self.monitor.as_mut().unwrap())
        .take_channel_receiver();
        self.signals.push(Box::new(Signal::new(rx)));
        Ok(self)
    }
    /// Initiates data acquisition
    pub fn run(mut self, ctx: egui::Context) -> Self {
        debug!("scope run");
        self.signals.iter_mut().for_each(|signal| {
            let _ = signal.run(ctx.clone());
        });
        // self.monitor.take().unwrap().await?;
        self
    }
    /// Takes ownership of [Monitor]
    pub fn take_monitor(&mut self) -> Monitor {
        self.monitor.take().unwrap()
    }
}

impl<K> XScope<K>
where
    XScope<K>: eframe::App,
    K: ScopeKind + 'static,
{
    /// Display the scope
    pub fn show(mut self) {
        let monitor = self.monitor.take().unwrap();
        tokio::spawn(async move {
            match monitor.join().await {
                Ok(_) => println!("*** data streaming complete ***"),
                Err(e) => println!("!!! data streaming error with {:?} !!!", e),
            }
        });
        let native_options = eframe::NativeOptions {
            initial_window_size: Some(Vec2::from(<K as ScopeKind>::window_size())),
            ..Default::default()
        };
        let _ = eframe::run_native(
            "GMT DOS Actors Scope",
            native_options,
            Box::new(|cc| Box::new(self.run(cc.egui_ctx.clone()))),
        );
    }
}

/// Signal plotting scope
pub type Scope = XScope<PlotScope>;

impl eframe::App for Scope {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            let plot = egui::plot::Plot::new("Scope").legend(Default::default());
            plot.show(ui, |plot_ui: &mut egui::plot::PlotUi| {
                for signal in &mut self.signals {
                    // plot_ui.line(signal.line());
                    signal.plot_ui(plot_ui)
                }
            });
        });
    }
}

/// Image display scope
pub type Shot = XScope<ImageScope>;

impl eframe::App for Shot {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            let plot = egui::plot::Plot::new("Scope")
                //.show_axes([false; 2])
                .show_x(false)
                .show_y(false)
                .allow_scroll(false)
                .data_aspect(1f32);
            plot.show(ui, |plot_ui: &mut egui::plot::PlotUi| {
                for signal in &mut self.signals {
                    // plot_ui.line(signal.line());
                    signal.plot_ui(plot_ui)
                }
            });
        });
    }
}

/// GMT scope
///
/// Image display scope which data is masked by the GMT exit pupil mask
pub type GmtShot = XScope<GmtScope>;

impl eframe::App for GmtShot {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        for signal in &mut self.signals {
            // plot_ui.line(signal.line());
            signal.plot_stats_ui(ctx)
        }
        egui::CentralPanel::default().show(ctx, |ui| {
            let plot = egui::plot::Plot::new("Scope")
                // .show_axes([false; 2])
                .show_x(false)
                .show_y(false)
                // .allow_drag(false)
                .allow_scroll(false)
                .data_aspect(1f32);
            // .view_aspect(1f32);
            plot.show(ui, |plot_ui: &mut egui::plot::PlotUi| {
                for signal in &mut self.signals {
                    // plot_ui.line(signal.line());
                    signal.plot_ui(plot_ui)
                }
            });
        });
    }
}