rsiot/components_config/mqtt_client/
mqtt_msg_gen.rs1use serde::{Serialize, de::DeserializeOwned};
2
3use crate::serde_utils::{self, SerdeAlg};
4
5use super::MqttMsgSend;
6
7#[derive(Clone)]
9pub struct MqttMsgGen {
10 pub serde_alg: SerdeAlg,
12
13 pub base_topic: String,
17}
18
19impl MqttMsgGen {
20 pub fn ser<TPayload>(
22 &self,
23 topic: impl Into<String>,
24 retain: bool,
25 payload: &TPayload,
26 ) -> Result<MqttMsgSend, serde_utils::Error>
27 where
28 TPayload: Serialize,
29 {
30 let topic = if self.base_topic.is_empty() {
31 topic.into()
32 } else {
33 format!("{}/{}", self.base_topic, topic.into())
34 };
35
36 let payload = self.serde_alg.serialize(payload)?;
37
38 let mqtt_msg = MqttMsgSend::Publish {
39 topic,
40 retain,
41 payload,
42 };
43 Ok(mqtt_msg)
44 }
45
46 pub fn de<TPayload>(&self, payload: &[u8]) -> Result<TPayload, serde_utils::Error>
48 where
49 TPayload: DeserializeOwned,
50 {
51 self.serde_alg.deserialize(payload)
52 }
53}