tether_utils/
tether_send.rs1use clap::Args;
2use log::{debug, error, info, warn};
3use serde::Serialize;
4use tether_agent::{ChannelOptionsBuilder, TetherAgent};
5
6#[derive(Args)]
7pub struct SendOptions {
8 #[arg(long = "channel.name")]
10 pub channel_name: Option<String>,
11
12 #[arg(long = "channel.role")]
14 pub channel_role: Option<String>,
15
16 #[arg(long = "channel.id")]
18 pub channel_id: Option<String>,
19
20 #[arg(long = "topic")]
23 pub channel_topic: Option<String>,
24
25 #[arg(long = "message")]
28 pub message_payload_json: Option<String>,
29
30 #[arg(long = "dummyData")]
33 pub use_dummy_data: bool,
34}
35
36#[derive(Serialize, Debug)]
37struct DummyData {
38 id: usize,
39 a_float: f32,
40 an_int_array: Vec<usize>,
41 a_string: String,
42}
43
44pub fn send(options: &SendOptions, tether_agent: &mut TetherAgent) -> anyhow::Result<()> {
45 info!("Tether Send Utility");
46
47 let channel_name = options
48 .channel_name
49 .clone()
50 .unwrap_or("testMessages".into());
51
52 let channel = ChannelOptionsBuilder::create_sender(&channel_name)
53 .role(options.channel_role.as_deref())
54 .id(options.channel_id.as_deref())
55 .topic(options.channel_topic.as_deref())
56 .build(tether_agent)
57 .expect("failed to create Channel Sender");
58
59 info!("Sending on topic \"{}\" ...", channel.generated_topic());
60
61 if options.use_dummy_data {
62 let payload = DummyData {
63 id: 0,
64 a_float: 42.0,
65 an_int_array: vec![1, 2, 3, 4],
66 a_string: "hello world".into(),
67 };
68 info!("Sending dummy data {:?}", payload);
69 return match tether_agent.encode_and_send(&channel, &payload) {
70 Ok(_) => {
71 info!("Sent dummy data message OK");
72 Ok(())
73 }
74 Err(e) => Err(e),
75 };
76 }
77
78 match &options.message_payload_json {
79 Some(custom_message) => {
80 debug!(
81 "Attempting to decode provided custom message \"{}\"",
82 &custom_message
83 );
84 match serde_json::from_str::<serde_json::Value>(custom_message) {
85 Ok(encoded) => {
86 let payload =
87 rmp_serde::to_vec_named(&encoded).expect("failed to encode msgpack");
88 tether_agent
89 .send(&channel, Some(&payload))
90 .expect("failed to publish");
91 info!("Sent message OK");
92 Ok(())
93 }
94 Err(e) => {
95 error!("Could not serialise String -> JSON; error: {}", e);
96 Err(e.into())
97 }
98 }
99 }
100 None => {
101 warn!("Sending empty message");
102 match tether_agent.send(&channel, None) {
103 Ok(_) => {
104 info!("Sent empty message OK");
105 Ok(())
106 }
107 Err(e) => {
108 error!("Failed to send empty message: {}", e);
109 Err(e)
110 }
111 }
112 }
113 }
114}