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
use std::{
    fs::File,
    io::BufReader,
    sync::mpsc::{self, Receiver},
};

use clap::Args;
use log::{debug, info, warn};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use tether_agent::TetherAgent;

#[derive(Args, Clone)]
pub struct PlaybackOptions {
    /// Specify the full path to the JSON file containing recorded messages
    #[arg(long = "file.path", default_value_t=String::from("./demo.json"))]
    pub file_path: String,

    /// Overide any original topics saved in the file, to use with every published message
    #[arg(long = "topic")]
    pub override_topic: Option<String>,

    /// How many times to loop playback
    #[arg(long = "loops.count", default_value_t = 1)]
    pub loop_count: usize,

    /// Flag to enable infinite looping for playback (ignore loops.count if enabled)
    #[arg(long = "loops.infinite")]
    pub loop_infinite: bool,

    /// Flag to disable registration of Ctrl+C handler - this is usually necessary
    /// when using the utility programmatically (i.e. not via CLI)
    #[arg(long = "ignoreCtrlC")]
    pub ignore_ctrl_c: bool,
}

impl Default for PlaybackOptions {
    fn default() -> Self {
        PlaybackOptions {
            file_path: "./demo.json".into(),
            override_topic: None,
            loop_count: 1,
            loop_infinite: false,
            ignore_ctrl_c: false,
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SimulationMessage {
    pub r#type: String,
    pub data: Vec<u8>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SimulationRow {
    pub topic: String,
    pub message: SimulationMessage,
    pub delta_time: u64,
}

pub struct TetherPlaybackUtil {
    stop_request_tx: mpsc::Sender<bool>,
    stop_request_rx: mpsc::Receiver<bool>,
    options: PlaybackOptions,
}

impl TetherPlaybackUtil {
    pub fn new(options: PlaybackOptions) -> Self {
        info!("Tether Playback Utility: initialise");

        let (tx, rx) = mpsc::channel();
        TetherPlaybackUtil {
            stop_request_tx: tx,
            stop_request_rx: rx,
            options,
        }
    }

    pub fn get_stop_tx(&self) -> mpsc::Sender<bool> {
        self.stop_request_tx.clone()
    }

    pub fn start(&self, tether_agent: &TetherAgent) {
        info!("Tether Playback Utility: start playback");

        if let Some(t) = &self.options.override_topic {
            warn!("Override topic provided; ALL topics in JSON entries will be ignored and replaced with \"{}\"",t);
        }

        let stop_from_key = self.stop_request_tx.clone();

        if !self.options.ignore_ctrl_c {
            warn!("Infinite loops requested; Press Ctr+C to stop");
            ctrlc::set_handler(move || {
                // should_stop_clone.store(true, Ordering::Relaxed);
                stop_from_key
                    .send(true)
                    .expect("failed to send stop from key");
                warn!("received Ctrl+C! 2");
            })
            .expect("Error setting Ctrl-C handler");
        } else {
            warn!(
                "No Ctrl+C handler set; you may need to kill this process manually, PID: {}",
                std::process::id()
            );
        }

        let mut finished = false;

        let mut count = 0;

        while !finished {
            count += 1;
            if !finished {
                if !self.options.loop_infinite {
                    info!(
                        "Finite loops requested: starting loop {}/{}",
                        count, self.options.loop_count
                    );
                } else {
                    info!("Infinite loops requested; starting loop {}", count);
                }
                if parse_json_rows(
                    &self.options.file_path,
                    tether_agent,
                    &self.options.override_topic,
                    &self.stop_request_rx,
                ) {
                    warn!("Early exit; finish now");
                    finished = true;
                }
            }
            if !self.options.loop_infinite && count >= self.options.loop_count {
                info!("All {} loops completed", &self.options.loop_count);
                finished = true;
            }
        }
    }
}

fn parse_json_rows(
    filename: &str,
    tether_agent: &TetherAgent,
    override_topic: &Option<String>,
    should_stop_rx: &Receiver<bool>,
) -> bool {
    let file = File::open(filename).unwrap_or_else(|_| panic!("failed to open file {}", filename));
    let reader = BufReader::new(file);
    let deserializer = serde_json::Deserializer::from_reader(reader);
    let mut iterator = deserializer.into_iter::<Vec<Value>>();
    let top_level_array: Vec<Value> = iterator.next().unwrap().unwrap();

    let mut finished = false;
    let mut early_exit = false;
    // let rows = top_level_array.into_iter();

    let mut index = 0;

    while !finished {
        while let Ok(_should_stop) = should_stop_rx.try_recv() {
            early_exit = true;
            finished = true;
        }
        if let Some(row_value) = top_level_array.get(index) {
            let row: SimulationRow =
                serde_json::from_value(row_value.clone()).expect("failed to decode JSON row");

            let SimulationRow {
                topic,
                message,
                delta_time,
            } = &row;

            let payload = &message.data;

            if !finished {
                debug!("Sleeping {}ms ...", delta_time);
                std::thread::sleep(std::time::Duration::from_millis(*delta_time));
                let topic = match &override_topic {
                    Some(t) => String::from(t),
                    None => String::from(topic),
                };

                tether_agent
                    .publish_raw(&topic, payload, None, None)
                    .expect("failed to publish");
            }

            debug!("Got row {:?}", row);
        } else {
            finished = true;
        }
        index += 1;
    }
    early_exit
}