use clap::Args;
use log::{debug, error, info, warn};
use serde::Serialize;
use tether_agent::{ChannelOptionsBuilder, TetherAgent};
#[derive(Args)]
pub struct SendOptions {
#[arg(long = "channel.name")]
pub channel_name: Option<String>,
#[arg(long = "channel.role")]
pub channel_role: Option<String>,
#[arg(long = "channel.id")]
pub channel_id: Option<String>,
#[arg(long = "topic")]
pub channel_topic: Option<String>,
#[arg(long = "message")]
pub message_payload_json: Option<String>,
#[arg(long = "dummyData")]
pub use_dummy_data: bool,
}
#[derive(Serialize, Debug)]
struct DummyData {
id: usize,
a_float: f32,
an_int_array: Vec<usize>,
a_string: String,
}
pub fn send(options: &SendOptions, tether_agent: &mut TetherAgent) -> anyhow::Result<()> {
info!("Tether Send Utility");
let channel_name = options
.channel_name
.clone()
.unwrap_or("testMessages".into());
let channel = ChannelOptionsBuilder::create_sender(&channel_name)
.role(options.channel_role.as_deref())
.id(options.channel_id.as_deref())
.topic(options.channel_topic.as_deref())
.build(tether_agent)
.expect("failed to create Channel Sender");
info!("Sending on topic \"{}\" ...", channel.generated_topic());
if options.use_dummy_data {
let payload = DummyData {
id: 0,
a_float: 42.0,
an_int_array: vec![1, 2, 3, 4],
a_string: "hello world".into(),
};
info!("Sending dummy data {:?}", payload);
return match tether_agent.send(&channel, &payload) {
Ok(_) => {
info!("Sent dummy data message OK");
Ok(())
}
Err(e) => Err(e),
};
}
match &options.message_payload_json {
Some(custom_message) => {
debug!(
"Attempting to decode provided custom message \"{}\"",
&custom_message
);
match serde_json::from_str::<serde_json::Value>(custom_message) {
Ok(encoded) => {
tether_agent
.send(&channel, &encoded)
.expect("failed to publish");
info!("Sent message OK");
Ok(())
}
Err(e) => {
error!("Could not serialise String -> JSON; error: {}", e);
Err(e.into())
}
}
}
None => {
warn!("Sending empty message");
match tether_agent.send_empty(&channel) {
Ok(_) => {
info!("Sent empty message OK");
Ok(())
}
Err(e) => {
error!("Failed to send empty message: {}", e);
Err(e)
}
}
}
}
}