sparkplug_rs/
device_message_types.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3use std::str::FromStr;
4
5/// Enum for device-message types.
6///
7/// The string representation for use in MQTT's topic name can produced by [ToString::to_string]
8///
9/// # Examples
10/// ```
11/// # use sparkplug_rs::DeviceMessageType;
12/// assert_eq!(DeviceMessageType::DBIRTH.to_string(), "DBIRTH".to_string());
13/// ```
14///
15/// For conversion from the MQTT's topic representation use [FromStr::from_str]
16///
17/// # Examples
18/// ```
19/// # use std::str::FromStr;
20/// # use sparkplug_rs::DeviceMessageType;
21/// assert_eq!(DeviceMessageType::from_str("DBIRTH").unwrap(), DeviceMessageType::DBIRTH);
22/// assert!(DeviceMessageType::from_str("xyz").is_err());
23/// ```
24#[derive(Debug, Clone, PartialEq)]
25pub enum DeviceMessageType {
26    DBIRTH,
27    DDEATH,
28    DDATA,
29    DCMD,
30}
31
32impl ToString for DeviceMessageType {
33    fn to_string(&self) -> String {
34        match self {
35            DeviceMessageType::DBIRTH => "DBIRTH".to_string(),
36            DeviceMessageType::DDEATH => "DDEATH".to_string(),
37            DeviceMessageType::DDATA => "DDATA".to_string(),
38            DeviceMessageType::DCMD => "DCMD".to_string(),
39        }
40    }
41}
42
43pub struct DeviceMessageTypeParseError;
44
45impl Debug for DeviceMessageTypeParseError {
46    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47        Display::fmt(self, f)
48    }
49}
50
51impl Display for DeviceMessageTypeParseError {
52    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
53        f.write_str("Unknown DeviceMessageType")
54    }
55}
56
57impl Error for DeviceMessageTypeParseError {}
58
59impl FromStr for DeviceMessageType {
60    type Err = DeviceMessageTypeParseError;
61
62    fn from_str(s: &str) -> Result<Self, Self::Err> {
63        match s {
64            "DBIRTH" => Ok(DeviceMessageType::DBIRTH),
65            "DDEATH" => Ok(DeviceMessageType::DDEATH),
66            "DDATA" => Ok(DeviceMessageType::DDATA),
67            "DCMD" => Ok(DeviceMessageType::DCMD),
68            _ => Err(DeviceMessageTypeParseError),
69        }
70    }
71}