summaryrefslogtreecommitdiffstats
path: root/src/testbench.rs
blob: 5dd18fd3cb9e3bbc2546486a344095bcd2c29ca5 (plain)
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
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::option::Option;
use std::path::PathBuf;

use imgui;
use rlua::Lua;
// use serialport;

use crate::rusbtmc;

#[derive(Default, PartialEq)]
pub struct Test {
    pub path: PathBuf,
    text: Option<String>,
}

impl Test {
    pub fn new(path: PathBuf) -> Test {
        Test {
            path: path,
            text: None,
        }
    }

    pub fn read(&mut self) -> &str {
        if self.text.is_none() {
            self.text = Some(fs::read_to_string(&self.path).expect("Failed to read file"));
        }

        return self.text.as_ref().unwrap();
    }

    // pub fn text(&self) -> &str {
    //     return match &self.text {
    //         Some(text) => text,
    //         None => "",
    //     }
    // }
}

#[derive(Default)]
pub struct Bench {
    // tests window
    lua: Lua,
    tests: Vec<Test>,
    tests_path: PathBuf,
    selected_test: Option<usize>,
    selected_usb_dev: Option<usize>,
    usb_devices: HashMap<imgui::ImString, rusbtmc::Instrument<rusb::GlobalContext>>,
    selected_serial_dev: Option<usize>,
    // serial_devices: Vec<?>
    lua_console: Vec<imgui::ImString>,
    instr_console: Vec<imgui::ImString>,
    instr_input: imgui::ImString,
}

impl Bench {
    pub fn new() -> Bench {
        /* Prepare lua environment */
        let lua = Lua::new();
        let lua_setup = lua.context(|context| -> rlua::Result<()> {
            use rlua::{String, Variadic};

            let globals = context.globals();

            let ui_table = context.create_table()?;
            let ui_print = context.create_function(|_, _strings: Variadic<String>| {
                // TODO
                // lua_console.push()
                Ok(())
            })?;

            ui_table.set("print", ui_print)?;
            globals.set("ui", ui_table)?;

            Ok(())
        });

        if let Err(_) = lua_setup {
            // TODO: handle errors
        }

        let mut b = Bench {
            lua: lua,
            tests: Vec::new(),
            tests_path: PathBuf::from("lua"),
            selected_test: None,
            selected_usb_dev: None,
            usb_devices: HashMap::new(),
            selected_serial_dev: None,
            lua_console: Vec::new(),
            instr_console: Vec::new(),
            instr_input: imgui::ImString::with_capacity(256),
            // scope: None,
        };

        // TODO: set graphically and use RV
        let _ = b.load_tests();

        return b;
    }

    pub fn load_tests(&mut self) -> io::Result<()> {
        let entries: Result<Vec<PathBuf>, io::Error> = fs::read_dir(&self.tests_path)?
            .into_iter()
            .map(|r| r.map(|f| f.path()))
            .collect();

        match entries {
            Ok(files) => {
                self.tests = files
                    .into_iter()
                    .filter(|f| f.is_file())
                    .filter(|f| f.extension().unwrap_or(OsStr::new("")) == "lua")
                    .map(|f| Test::new(f))
                    .collect();

                return Ok(());
            }
            Err(e) => return Err(e),
        }
    }

    pub fn draw(&mut self, _: &mut bool, ui: &mut imgui::Ui) {
        use imgui::*;

        /* Testbench window */
        let tb_win = Window::new(im_str!("Testbench"))
            .size([400., 500.], Condition::Appearing)
            .position([20., 20.], Condition::Appearing);

        tb_win.build(&ui, || {
            for (index, test) in self.tests.iter().enumerate() {
                if let Some(test_name) = test.path.to_str() {
                    let test_name: ImString = test_name.to_string().into();
                    let selected = matches!(self.selected_test, Some(i) if i == index);

                    if Selectable::new(&test_name).selected(selected).build(ui) {
                        self.selected_test = Some(index)
                    }
                }
            }

            if let Some(index) = self.selected_test {
                ui.separator();
                if let Some(test_name) = self.tests[index].path.to_str() {
                    let imstr: ImString =
                        format!("Selected Test: {}", test_name).to_string().into();
                    ui.text_wrapped(&imstr);
                    ui.same_line(0.);
                    if ui.button(im_str!("Run"), [0., 0.]) {
                        self.run_test(index);
                    }

                    ui.same_line(0.);
                    if ui.button(im_str!("Show"), [0., 0.]) {
                        self.show_test(index);
                    }
                }
            }

            ui.separator();
            ChildWindow::new("lua console")
                .size([0., 0.])
                .scrollable(true)
                .build(&ui, || {
                    for line in &self.lua_console {
                        ui.text(line);
                    }
                });
        });

        /* devices window */
        let dev_win = Window::new(im_str!("Devices"))
            .size([400., 500.], Condition::Appearing)
            .position([520., 20.], Condition::Appearing);

        dev_win.build(&ui, || {
            // usb devices
            ui.text_wrapped(im_str!("USB Devices"));
            ui.same_line(0.);
            if ui.button(im_str!("Refresh"), [0., 0.]) {
                // TODO: do not remove open devices
                self.usb_devices.clear();
                self.selected_usb_dev = None;

                if let Ok(instruments) = rusbtmc::instruments() {
                    for instr in instruments {
                        let desc = match instr.device.device_descriptor() {
                            Ok(desc) => desc,
                            Err(_) => {
                                dbg!("failed to get descriptor");
                                continue;
                            }
                        };

                        let handle = match instr.device.open() {
                            Ok(handle) => handle,
                            Err(_) => {
                                // dbg!("failed to get handle");
                                continue;
                            }
                        };

                        let prodstr = match handle.read_product_string_ascii(&desc) {
                            Ok(s) => s,
                            Err(_) => {
                                dbg!("failed to read product string");
                                continue;
                            }
                        };

                        let dev_name: ImString = prodstr.into();
                        self.usb_devices.insert(dev_name, instr);
                    }
                }
            }

            if self.selected_usb_dev.is_some() {
                // search dev
                let mut instr = None;
                for (index, (_name, dev)) in self.usb_devices.iter_mut().enumerate() {
                    if matches!(self.selected_usb_dev, Some(i) if i == index) {
                        instr = Some(dev);
                        break;
                    }
                }

                if let Some(instr) = instr {
                    ui.same_line(0.);
                    if ui.button(im_str!("Open"), [0., 0.]) {
                        let _ = dbg!(instr.open());
                    }

                    ui.same_line(0.);
                    if ui.button(im_str!("Close"), [0., 0.]) {
                        let _ = dbg!(instr.close());
                    }

                    ui.same_line(0.);
                    if ui.button(im_str!("Pulse"), [0., 0.]) {
                        let _ = dbg!(instr.pulse());
                    }
                }
            }

            for (index, (name, _dev)) in self.usb_devices.iter().enumerate() {
                let selected = matches!(self.selected_usb_dev, Some(i) if i == index);

                if Selectable::new(&name).selected(selected).build(ui) {
                    self.selected_usb_dev = Some(index);
                }

                ui.same_line(0.);
            }

            ui.separator();
            ui.input_text(im_str!("Device"), &mut self.instr_input).build();
            ChildWindow::new("instrument console")
                .size([0., 0.])
                .scrollable(true)
                .build(&ui, || {
                    for line in &self.instr_console {
                        ui.text(line);
                    }
                });
        });
    }

    fn run_test(&mut self, index: usize) {
        if let Some(test) = self.tests.get_mut(index) {
            let text = test.read();
            let mut output = imgui::ImString::new("");

            self.lua.context(
                |context| match context.load(text).eval::<rlua::MultiValue>() {
                    Ok(values) => {
                        output.push_str(
                            &values
                                .iter()
                                .map(|value| format!("{:?}", value))
                                .collect::<Vec<_>>()
                                .join("\t"),
                        );
                    }
                    Err(e) => {
                        output.push_str(&e.to_string());
                    }
                },
            );

            self.lua_console.push(output);
        }
    }

    fn show_test(&self, _index: usize) {
        // TODO
    }
}