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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use clap::Args;
use log::{debug, error, info, warn};
use tether_agent::{mqtt::Message, PlugOptionsBuilder, TetherAgent, TetherOrCustomTopic};

#[derive(Args)]
pub struct ReceiveOptions {
    /// Specify a ROLE (instead of wildcard +)
    #[arg(long = "plug.role")]
    pub subscribe_role: Option<String>,

    /// Specify an ID (instead of wildcard +)
    #[arg(long = "plug.id")]
    pub subscribe_id: Option<String>,

    /// Specify a PLUG NAME part for the topic (instead of wildcard +)
    #[arg(long = "plug.name")]
    pub subscribe_plug_name: Option<String>,

    /// Override topic to subscribe; setting this will
    /// ignore any `plug.` options you may have set, since the
    /// topic is built manually.
    #[arg(long = "topic")]
    pub subscribe_topic: Option<String>,
}

impl Default for ReceiveOptions {
    fn default() -> Self {
        ReceiveOptions {
            subscribe_topic: None,
            subscribe_role: None,
            subscribe_id: None,
            subscribe_plug_name: None,
        }
    }
}

pub fn receive(
    options: &ReceiveOptions,
    tether_agent: &TetherAgent,
    on_message: fn(plug_name: String, message: Message, decoded: Option<String>),
) {
    info!("Tether Receive Utility");

    let input_def = build_receiver_plug(options);

    let input = input_def
        .build(tether_agent)
        .expect("failed to create input plug");

    info!("Subscribed to topic \"{}\" ...", input.topic());

    loop {
        let mut did_work = false;
        while let Some((topic, message)) = tether_agent.check_messages() {
            did_work = true;
            debug!("Received message on topic \"{}\"", message.topic());
            let plug_name = match topic {
                TetherOrCustomTopic::Custom(_) => String::from("unknown"),
                TetherOrCustomTopic::Tether(tpt) => String::from(tpt.plug_name()),
            };

            let bytes = message.payload();
            if bytes.is_empty() {
                debug!("Empty message payload");
                on_message(plug_name, message, None);
            } else if let Ok(value) = rmp_serde::from_slice::<rmpv::Value>(bytes) {
                let json = serde_json::to_string(&value).expect("failed to stringify JSON");
                debug!("Decoded MessagePack payload: {}", json);
                on_message(plug_name, message, Some(json));
            } else {
                debug!("Failed to decode MessagePack payload");
                if let Ok(s) = String::from_utf8(bytes.to_vec()) {
                    warn!("String representation of payload: \"{}\"", s);
                } else {
                    error!("Could not decode payload bytes as string, either");
                }
                on_message(plug_name, message, None);
            }
        }
        if !did_work {
            std::thread::sleep(std::time::Duration::from_micros(100)); //0.1 ms
        }
    }
}

fn build_receiver_plug(options: &ReceiveOptions) -> PlugOptionsBuilder {
    if options.subscribe_id.is_some()
        || options.subscribe_role.is_some()
        || options.subscribe_plug_name.is_some()
    {
        debug!(
            "TPT Overrides apply: {:?}, {:?}, {:?}",
            &options.subscribe_id, &options.subscribe_role, &options.subscribe_plug_name
        );
        PlugOptionsBuilder::create_input(match &options.subscribe_plug_name {
            Some(provided_name) => {
                if provided_name.as_str() == "+" {
                    "any"
                } else {
                    &provided_name
                }
            }
            None => "any",
        })
        .role(options.subscribe_role.as_deref())
        .id(options.subscribe_id.as_deref())
        .name(match &options.subscribe_plug_name {
            Some(provided_name_part) => {
                if provided_name_part.as_str() == "+" {
                    Some("+")
                } else {
                    None
                }
            }
            None => {
                if options.subscribe_id.is_some() || options.subscribe_role.is_some() {
                    // No plug name part was supplied, but other parts were; therefore
                    // in this case Tether Receive should subscribr to all messages
                    // matching or both of the specified Agent and/or Role
                    Some("+")
                } else {
                    // No plug name part was supplied, but neither was anything else
                    // Logically, we shouldn't reach this point because of the outer condition
                    // but it must be provided here for completeness
                    None
                }
            }
        })
    } else {
        debug!(
            "Using custom override topic \"{:?}\"",
            &options.subscribe_topic
        );
        PlugOptionsBuilder::create_input("custom")
            .topic(Some(options.subscribe_topic.as_deref().unwrap_or("#")))
    }
}

#[cfg(test)]
mod tests {
    use tether_agent::TetherAgentOptionsBuilder;

    use crate::tether_receive::build_receiver_plug;

    use super::ReceiveOptions;

    #[test]
    fn default_options() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions::default();

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "custom");
        assert_eq!(receive_plug.topic(), "#");
    }

    #[test]
    fn only_topic_custom() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: None,
            subscribe_id: None,
            subscribe_plug_name: None,
            subscribe_topic: Some("some/special/plug".into()),
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "custom");
        assert_eq!(receive_plug.topic(), "some/special/plug");
    }

    #[test]
    fn only_plug_name() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: None,
            subscribe_id: None,
            subscribe_plug_name: Some("something".into()),
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "something");
        assert_eq!(receive_plug.topic(), "+/+/something");
    }

    #[test]
    fn only_role() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: Some("something".into()),
            subscribe_id: None,
            subscribe_plug_name: None,
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "any");
        assert_eq!(receive_plug.topic(), "something/+/+");
    }

    #[test]
    fn only_id() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: None,
            subscribe_id: Some("something".into()),
            subscribe_plug_name: None,
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "any");
        assert_eq!(receive_plug.topic(), "+/something/+");
    }

    #[test]
    fn role_and_id() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: Some("x".into()),
            subscribe_id: Some("y".into()),
            subscribe_plug_name: None,
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "any");
        assert_eq!(receive_plug.topic(), "x/y/+");
    }

    #[test]
    fn role_and_plug_name() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: Some("x".into()),
            subscribe_id: None,
            subscribe_plug_name: Some("z".into()),
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "z");
        assert_eq!(receive_plug.topic(), "x/+/z");
    }

    #[test]
    fn spec_all_three() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: Some("x".into()),
            subscribe_id: Some("y".into()),
            subscribe_plug_name: Some("z".into()),
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "z");
        assert_eq!(receive_plug.topic(), "x/y/z");
    }

    #[test]
    fn redundant_but_valid() {
        let tether_agent = TetherAgentOptionsBuilder::new("tester")
            .build()
            .expect("sorry, these tests require working localhost Broker");

        let options = ReceiveOptions {
            subscribe_role: None,
            subscribe_id: None,
            subscribe_plug_name: Some("+".into()),
            subscribe_topic: None,
        };

        let receive_plug = build_receiver_plug(&options)
            .build(&tether_agent)
            .expect("build failed");

        assert_eq!(receive_plug.name(), "any");
        assert_eq!(receive_plug.topic(), "+/+/+");
    }
}