tether_utils/
tether_record.rs1use 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 pub file_override_path: Option<String>,
18
19 #[arg(long = "file.path", default_value_t=String::from("./"))]
21 pub file_base_path: String,
22
23 #[arg(long = "file.name", default_value_t=String::from("recording"))]
25 pub file_base_name: String,
26
27 #[arg(long = "file.noTimestamp")]
29 pub file_no_timestamp: bool,
30
31 #[arg(long = "topic", default_value_t=String::from("#"))]
33 pub topic: String,
34
35 #[arg(long = "timing.nonzeroStart")]
38 pub timing_nonzero_start: bool,
39
40 #[arg(long = "timing.delay")]
43 pub timing_delay: Option<f32>,
44
45 #[arg(long = "timing.duration")]
48 pub timing_duration: Option<f32>,
49
50 #[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()) .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 if !self.options.ignore_ctrl_c {
170 ctrlc::set_handler(move || {
171 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 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 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(); info!("First message written to disk");
254 } else {
255 file.write_all(b",\n").unwrap(); }
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)); }
272 }
273 }
274 }
275}