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::{ChannelOptionsBuilder, 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        // The channel definition is never actually used, since we do no matching from topics to channel!
98        // But we must set it up so that subscription happens.
99        let _channel_def = ChannelOptionsBuilder::create_receiver("all")
100            .topic(Some(self.options.topic.clone()).as_deref()) // TODO: should be possible to build TPT
101            .build(tether_agent)
102            .expect("failed to create Channel Receiver");
103
104        let file_path = match &self.options.file_override_path {
105            Some(override_path) => String::from(override_path),
106            None => {
107                if self.options.file_no_timestamp {
108                    format!(
109                        "{}{}.json",
110                        self.options.file_base_path, self.options.file_base_name
111                    )
112                } else {
113                    let timestamp = SystemTime::now()
114                        .duration_since(SystemTime::UNIX_EPOCH)
115                        .unwrap_or(Duration::from_secs(0))
116                        .as_secs();
117                    format!(
118                        "{}{}-{}.json",
119                        self.options.file_base_path, self.options.file_base_name, timestamp
120                    )
121                }
122            }
123        };
124
125        info!("Writing recorded data to \"{}\" ...", &file_path);
126
127        let file = File::create(&file_path).expect("failed to create file");
128        let mut file = LineWriter::new(file);
129
130        let buf = b"[";
131        file.write_all(buf).expect("failed to write first line");
132
133        let max_duration = match self.options.timing_duration {
134            Some(dur) => {
135                warn!(
136                    "Max duration was set to {}s; Ctr+C to stop before that point ...",
137                    dur
138                );
139                Some(Duration::from_secs_f32(dur))
140            }
141            None => {
142                warn!("No duration provided; recording runs until you press Ctrl+C ...");
143                None
144            }
145        };
146
147        let start_delay = match self.options.timing_delay {
148            Some(dur) => {
149                warn!("Recording will only start after {}s", dur);
150                Some(Duration::from_secs_f32(dur))
151            }
152            None => {
153                debug!("No start delay set");
154                None
155            }
156        };
157
158        let start_application_time = SystemTime::now();
159        let mut first_message_time = SystemTime::now();
160        let mut previous_message_time = SystemTime::now();
161
162        let mut count: i128 = 0;
163
164        let stop_from_key = self.stop_request_tx.clone();
165        let stop_from_timer = self.stop_request_tx.clone();
166        // let stop_tx_clone = stop_tx.clone();
167
168        // let should_stop = Arc::new(AtomicBool::new(false));
169        // let should_stop_clone = Arc::clone(&should_stop);
170
171        if !self.options.ignore_ctrl_c {
172            ctrlc::set_handler(move || {
173                // should_stop_clone.store(true, Ordering::Relaxed);
174                stop_from_key
175                    .send(true)
176                    .expect("failed to send stop from key");
177                warn!("received Ctrl+C!");
178            })
179            .expect("Error setting Ctrl-C handler");
180        } else {
181            warn!(
182                "No Ctrl+C handler set; you may need to kill this process manually, PID: {}",
183                std::process::id()
184            );
185        }
186
187        let mut finished = false;
188
189        while !finished {
190            if let Some(delay) = start_delay {
191                if let Ok(elapsed) = start_application_time.elapsed() {
192                    if elapsed < delay {
193                        continue;
194                    }
195                }
196            }
197
198            if let Some(dur) = max_duration {
199                if let Ok(elapsed) = first_message_time.elapsed() {
200                    if elapsed > dur {
201                        if count == 0 && !self.options.timing_nonzero_start {
202                            debug!("Ignore duration; nothing received yet")
203                        } else {
204                            warn!(
205                                "Exceeded the max duration specified ({}s); will stop now...",
206                                dur.as_secs_f32()
207                            );
208                            // should_stop.store(true, Ordering::Relaxed);
209                            stop_from_timer
210                                .send(true)
211                                .expect("failed to send stop from timer");
212                        }
213                    }
214                }
215            }
216            if let Ok(_should_stop) = self.stop_request_rx.try_recv() {
217                info!(
218                    "Stopping after {} entries written to disk; end file cleanly, wait then exit",
219                    count
220                );
221                file.write_all(b"\n]")
222                    .expect("failed to close JSON file properly");
223                file.flush().unwrap();
224                std::thread::sleep(Duration::from_secs(2));
225                debug!("Exit now");
226                // exit(0);
227                finished = true;
228            } else {
229                let mut did_work = false;
230                while let Some((topic, payload)) = tether_agent.check_messages() {
231                    did_work = true;
232
233                    let delta_time = if count == 0 && !self.options.timing_nonzero_start {
234                        first_message_time = SystemTime::now();
235                        Duration::ZERO
236                    } else {
237                        previous_message_time.elapsed().unwrap_or_default()
238                    };
239                    previous_message_time = SystemTime::now();
240
241                    let full_topic_string = topic.full_topic_string();
242
243                    debug!("Received message on topic \"{}\"", &full_topic_string);
244                    let row = SimulationRow {
245                        topic: full_topic_string,
246                        message: SimulationMessage {
247                            r#type: "Buffer".into(),
248                            data: payload.to_vec(),
249                        },
250                        delta_time: delta_time.as_millis() as u64,
251                    };
252
253                    if count == 0 {
254                        file.write_all(b"\n").unwrap(); // line break only
255                        info!("First message written to disk");
256                    } else {
257                        file.write_all(b",\n").unwrap(); // comma, line break
258                    }
259
260                    let json =
261                        serde_json::to_string(&row).expect("failed to convert to stringified JSON");
262                    file.write_all(json.as_bytes())
263                        .expect("failed to write new entry");
264
265                    file.flush().unwrap();
266
267                    count += 1;
268
269                    debug!("Wrote {} rows", count);
270                }
271                if !did_work {
272                    std::thread::sleep(std::time::Duration::from_micros(100)); //0.1 ms
273                }
274            }
275        }
276    }
277}