tether_utils/
tether_record.rs

1use std::{
2    fs::File,
3    io::{LineWriter, Write},
4    sync::mpsc,
5    time::{Duration, SystemTime},
6};
7
8use clap::Args;
9use log::{debug, info, warn};
10use tether_agent::{PlugOptionsBuilder, TetherAgent};
11
12use crate::tether_playback::{SimulationMessage, SimulationRow};
13
14#[derive(Args, Clone)]
15pub struct RecordOptions {
16    /// Specify the full path for the recording file; overrides any other file args
17    pub file_override_path: Option<String>,
18
19    /// Base path for recording file
20    #[arg(long = "file.path", default_value_t=String::from("./"))]
21    pub file_base_path: String,
22
23    /// Base name for recording file, excluding timestamp and .json extension
24    #[arg(long = "file.name", default_value_t=String::from("recording"))]
25    pub file_base_name: String,
26
27    /// Flag to disable appending timestamp onto recording file name
28    #[arg(long = "file.noTimestamp")]
29    pub file_no_timestamp: bool,
30
31    /// Topic to subscribe; by default we recording everything
32    #[arg(long = "topic", default_value_t=String::from("#"))]
33    pub topic: String,
34
35    /// Flag to disable zero-ing of the first entry's deltaTime; using this
36    /// flag will count time from launch, not first message received
37    #[arg(long = "timing.nonzeroStart")]
38    pub timing_nonzero_start: bool,
39
40    /// Time (in seconds) to delay writing anything to disk, even if messages are
41    /// received
42    #[arg(long = "timing.delay")]
43    pub timing_delay: Option<f32>,
44
45    /// Duration (in seconds) to stop recording even if Ctrl+C has not been encountered
46    /// yet
47    #[arg(long = "timing.duration")]
48    pub timing_duration: Option<f32>,
49
50    /// Flag to disable registration of Ctrl+C handler - this is usually necessary
51    /// when using the utility programmatically (i.e. not via CLI)
52    #[arg(long = "ignoreCtrlC")]
53    pub ignore_ctrl_c: bool,
54}
55
56impl Default for RecordOptions {
57    fn default() -> Self {
58        RecordOptions {
59            file_override_path: None,
60            file_base_path: "./".into(),
61            file_base_name: "recording".into(),
62            file_no_timestamp: false,
63            topic: "#".into(),
64            timing_nonzero_start: false,
65            timing_delay: None,
66            timing_duration: None,
67            ignore_ctrl_c: false,
68        }
69    }
70}
71
72pub struct TetherRecordUtil {
73    stop_request_tx: mpsc::Sender<bool>,
74    stop_request_rx: mpsc::Receiver<bool>,
75    options: RecordOptions,
76}
77
78impl TetherRecordUtil {
79    pub fn new(options: RecordOptions) -> Self {
80        info!("Tether Record Utility: initialise");
81
82        let (tx, rx) = mpsc::channel();
83
84        TetherRecordUtil {
85            stop_request_tx: tx,
86            stop_request_rx: rx,
87            options,
88        }
89    }
90
91    pub fn get_stop_tx(&self) -> mpsc::Sender<bool> {
92        self.stop_request_tx.clone()
93    }
94    pub fn start_recording(&self, tether_agent: &mut TetherAgent) {
95        info!("Tether Record Utility: start recording");
96
97        let _input = PlugOptionsBuilder::create_input("all")
98            .topic(Some(self.options.topic.clone()).as_deref()) // TODO: should be possible to build TPT
99            .build(tether_agent)
100            .expect("failed to create input plug");
101
102        let file_path = match &self.options.file_override_path {
103            Some(override_path) => String::from(override_path),
104            None => {
105                if self.options.file_no_timestamp {
106                    format!(
107                        "{}{}.json",
108                        self.options.file_base_path, self.options.file_base_name
109                    )
110                } else {
111                    let timestamp = SystemTime::now()
112                        .duration_since(SystemTime::UNIX_EPOCH)
113                        .unwrap_or(Duration::from_secs(0))
114                        .as_secs();
115                    format!(
116                        "{}{}-{}.json",
117                        self.options.file_base_path, self.options.file_base_name, timestamp
118                    )
119                }
120            }
121        };
122
123        info!("Writing recorded data to \"{}\" ...", &file_path);
124
125        let file = File::create(&file_path).expect("failed to create file");
126        let mut file = LineWriter::new(file);
127
128        let buf = b"[";
129        file.write_all(buf).expect("failed to write first line");
130
131        let max_duration = match self.options.timing_duration {
132            Some(dur) => {
133                warn!(
134                    "Max duration was set to {}s; Ctr+C to stop before that point ...",
135                    dur
136                );
137                Some(Duration::from_secs_f32(dur))
138            }
139            None => {
140                warn!("No duration provided; recording runs until you press Ctrl+C ...");
141                None
142            }
143        };
144
145        let start_delay = match self.options.timing_delay {
146            Some(dur) => {
147                warn!("Recording will only start after {}s", dur);
148                Some(Duration::from_secs_f32(dur))
149            }
150            None => {
151                debug!("No start delay set");
152                None
153            }
154        };
155
156        let start_application_time = SystemTime::now();
157        let mut first_message_time = SystemTime::now();
158        let mut previous_message_time = SystemTime::now();
159
160        let mut count: i128 = 0;
161
162        let stop_from_key = self.stop_request_tx.clone();
163        let stop_from_timer = self.stop_request_tx.clone();
164        // let stop_tx_clone = stop_tx.clone();
165
166        // let should_stop = Arc::new(AtomicBool::new(false));
167        // let should_stop_clone = Arc::clone(&should_stop);
168
169        if !self.options.ignore_ctrl_c {
170            ctrlc::set_handler(move || {
171                // should_stop_clone.store(true, Ordering::Relaxed);
172                stop_from_key
173                    .send(true)
174                    .expect("failed to send stop from key");
175                warn!("received Ctrl+C!");
176            })
177            .expect("Error setting Ctrl-C handler");
178        } else {
179            warn!(
180                "No Ctrl+C handler set; you may need to kill this process manually, PID: {}",
181                std::process::id()
182            );
183        }
184
185        let mut finished = false;
186
187        while !finished {
188            if let Some(delay) = start_delay {
189                if let Ok(elapsed) = start_application_time.elapsed() {
190                    if elapsed < delay {
191                        continue;
192                    }
193                }
194            }
195
196            if let Some(dur) = max_duration {
197                if let Ok(elapsed) = first_message_time.elapsed() {
198                    if elapsed > dur {
199                        if count == 0 && !self.options.timing_nonzero_start {
200                            debug!("Ignore duration; nothing received yet")
201                        } else {
202                            warn!(
203                                "Exceeded the max duration specified ({}s); will stop now...",
204                                dur.as_secs_f32()
205                            );
206                            // should_stop.store(true, Ordering::Relaxed);
207                            stop_from_timer
208                                .send(true)
209                                .expect("failed to send stop from timer");
210                        }
211                    }
212                }
213            }
214            if let Ok(_should_stop) = self.stop_request_rx.try_recv() {
215                info!(
216                    "Stopping after {} entries written to disk; end file cleanly, wait then exit",
217                    count
218                );
219                file.write_all(b"\n]")
220                    .expect("failed to close JSON file properly");
221                file.flush().unwrap();
222                std::thread::sleep(Duration::from_secs(2));
223                debug!("Exit now");
224                // exit(0);
225                finished = true;
226            } else {
227                let mut did_work = false;
228                while let Some((topic, payload)) = tether_agent.check_messages() {
229                    did_work = true;
230
231                    let delta_time = if count == 0 && !self.options.timing_nonzero_start {
232                        first_message_time = SystemTime::now();
233                        Duration::ZERO
234                    } else {
235                        previous_message_time.elapsed().unwrap_or_default()
236                    };
237                    previous_message_time = SystemTime::now();
238
239                    let full_topic_string = topic.full_topic_string();
240
241                    debug!("Received message on topic \"{}\"", &full_topic_string);
242                    let row = SimulationRow {
243                        topic: full_topic_string,
244                        message: SimulationMessage {
245                            r#type: "Buffer".into(),
246                            data: payload.to_vec(),
247                        },
248                        delta_time: delta_time.as_millis() as u64,
249                    };
250
251                    if count == 0 {
252                        file.write_all(b"\n").unwrap(); // line break only
253                        info!("First message written to disk");
254                    } else {
255                        file.write_all(b",\n").unwrap(); // comma, line break
256                    }
257
258                    let json =
259                        serde_json::to_string(&row).expect("failed to convert to stringified JSON");
260                    file.write_all(json.as_bytes())
261                        .expect("failed to write new entry");
262
263                    file.flush().unwrap();
264
265                    count += 1;
266
267                    debug!("Wrote {} rows", count);
268                }
269                if !did_work {
270                    std::thread::sleep(std::time::Duration::from_micros(100)); //0.1 ms
271                }
272            }
273        }
274    }
275}