use crate::Result;
use mqttrs::{
QoS,
SubscribeReturnCodes,
SubscribeTopic,
};
use tokio::time::Duration;
#[derive(Clone, Debug)]
pub struct Publish {
topic: String,
payload: Vec<u8>,
qos: QoS,
retain: bool,
}
impl Publish {
pub fn new(topic: String, payload: Vec<u8>) -> Publish {
Publish {
topic,
payload,
qos: QoS::AtMostOnce,
retain: false,
}
}
pub fn topic(&self) -> &str {
&*self.topic
}
pub fn payload(&self) -> &[u8] {
&*self.payload
}
pub fn qos(&self) -> QoS {
self.qos
}
pub fn set_qos(&mut self, qos: QoS) -> &mut Self {
self.qos = qos;
self
}
pub fn set_retain(&mut self, retain: bool) -> &mut Self {
self.retain = retain;
self
}
pub fn retain(&self) -> bool {
self.retain
}
}
#[derive(Debug)]
pub struct Subscribe {
topics: Vec<SubscribeTopic>,
}
impl Subscribe {
pub fn new(v: Vec<SubscribeTopic>) -> Subscribe {
Subscribe {
topics: v,
}
}
pub fn topics(&self) -> &[SubscribeTopic] {
&*self.topics
}
}
#[derive(Debug)]
pub struct SubscribeResult {
pub(crate) return_codes: Vec<SubscribeReturnCodes>,
}
impl SubscribeResult {
pub fn return_codes(&self) -> &[SubscribeReturnCodes] {
&*self.return_codes
}
pub fn any_failures(&self) -> Result<()> {
let any_failed =
self.return_codes().iter()
.any(|rc| *rc == SubscribeReturnCodes::Failure);
if any_failed {
return Err(format!("Some subscribes failed: {:#?}", self.return_codes()).into());
}
Ok(())
}
}
pub struct Unsubscribe {
topics: Vec<UnsubscribeTopic>
}
impl Unsubscribe {
pub fn new(topics: Vec<UnsubscribeTopic>) -> Unsubscribe {
Unsubscribe { topics: topics }
}
pub fn topics(&self) -> &[UnsubscribeTopic] {
&*self.topics
}
}
pub struct UnsubscribeTopic {
topic_name: String,
}
impl UnsubscribeTopic {
pub fn new(topic_name: String) -> UnsubscribeTopic {
UnsubscribeTopic { topic_name: topic_name }
}
pub fn topic_name(&self) -> &str {
&*self.topic_name
}
}
#[derive(Debug)]
pub struct ReadResult {
pub(crate) topic: String,
pub(crate) payload: Vec<u8>,
}
impl ReadResult {
pub fn topic(&self) -> &str {
&*self.topic
}
pub fn payload(&self) -> &[u8] {
&*self.payload
}
}
#[derive(Clone, Copy, Debug)]
pub enum KeepAlive {
Disabled,
Enabled {
secs: u16
},
}
impl KeepAlive {
pub fn from_secs(secs: u16) -> KeepAlive {
if secs == 0 {
panic!("KeepAlive secs == 0 not permitted");
}
KeepAlive::Enabled { secs, }
}
pub fn disabled() -> KeepAlive {
KeepAlive::Disabled
}
pub fn is_enabled(&self) -> bool {
match self {
KeepAlive::Disabled => false,
KeepAlive::Enabled { .. } => true,
}
}
pub fn is_disabled(&self) -> bool {
match self {
KeepAlive::Disabled => true,
KeepAlive::Enabled { .. } => false,
}
}
pub fn as_duration(&self) -> Option<Duration> {
match self {
KeepAlive::Disabled => None,
KeepAlive::Enabled { secs } => {
Some(Duration::from_secs(*secs as u64))
},
}
}
}