summaryrefslogtreecommitdiffstats
path: root/crates/core/c8y_smartrest/src/topic.rs
blob: 491c7a4bd74f89b3514ff10c677381f446b16101 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use agent_interface::topic::ResponseTopic;
use agent_interface::TopicError;
use mqtt_channel::Topic;
use mqtt_channel::{Message, MqttError};

use crate::error::SMCumulocityMapperError;
use crate::smartrest_serializer::{
    CumulocitySupportedOperations, SmartRestSerializer, SmartRestSetOperationToExecuting,
    SmartRestSetOperationToSuccessful,
};

#[derive(Debug, Clone, PartialEq)]
pub enum C8yTopic {
    SmartRestRequest,
    SmartRestResponse,
    OperationTopic(String),
}

impl C8yTopic {
    pub fn as_str(&self) -> &str {
        match self {
            Self::SmartRestRequest => r#"c8y/s/ds"#,
            Self::SmartRestResponse => r#"c8y/s/us"#,
            Self::OperationTopic(name) => name.as_str(),
        }
    }

    pub fn to_topic(&self) -> Result<Topic, MqttError> {
        Ok(Topic::new(self.as_str())?)
    }
}

impl TryFrom<String> for C8yTopic {
    type Error = TopicError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.as_str() {
            r#"c8y/s/ds"# => Ok(C8yTopic::SmartRestRequest),
            r#"c8y/s/us"# => Ok(C8yTopic::SmartRestResponse),
            topic_name => {
                if topic_name[..3].contains("c8y") {
                    Ok(C8yTopic::OperationTopic(topic_name.to_string()))
                } else {
                    Err(TopicError::UnknownTopic {
                        topic: topic_name.to_string(),
                    })
                }
            }
        }
    }
}
impl TryFrom<&str> for C8yTopic {
    type Error = TopicError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(value.to_string())
    }
}

impl TryFrom<Topic> for C8yTopic {
    type Error = TopicError;

    fn try_from(value: Topic) -> Result<Self, Self::Error> {
        value.name.try_into()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum MapperSubscribeTopic {
    C8yTopic(C8yTopic),
    ResponseTopic(ResponseTopic),
}

impl TryFrom<String> for MapperSubscribeTopic {
    type Error = TopicError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        match ResponseTopic::try_from(value.clone()) {
            Ok(response_topic) => Ok(MapperSubscribeTopic::ResponseTopic(response_topic)),
            Err(_) => match C8yTopic::try_from(value) {
                Ok(smart_rest_request) => Ok(MapperSubscribeTopic::C8yTopic(smart_rest_request)),
                Err(err) => Err(err),
            },
        }
    }
}

impl TryFrom<&str> for MapperSubscribeTopic {
    type Error = TopicError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(value.to_string())
    }
}

impl TryFrom<Topic> for MapperSubscribeTopic {
    type Error = TopicError;

    fn try_from(value: Topic) -> Result<Self, Self::Error> {
        value.name.try_into()
    }
}

/// returns a c8y message specifying to set log status to executing.
///
/// example message: '501,c8y_LogfileRequest'
pub async fn get_log_file_request_executing() -> Result<Message, SMCumulocityMapperError> {
    let topic = C8yTopic::SmartRestResponse.to_topic()?;
    let smartrest_set_operation_status =
        SmartRestSetOperationToExecuting::new(CumulocitySupportedOperations::C8yLogFileRequest)
            .to_smartrest()?;
    Ok(Message::new(&topic, smartrest_set_operation_status))
}

/// returns a c8y message specifying to set log status to successful.
///
/// example message: '503,c8y_LogfileRequest,https://{c8y.url}/etc...'
pub async fn get_log_file_request_done_message(
    binary_upload_event_url: &str,
) -> Result<Message, SMCumulocityMapperError> {
    let topic = C8yTopic::SmartRestResponse.to_topic()?;
    let smartrest_set_operation_status =
        SmartRestSetOperationToSuccessful::new(CumulocitySupportedOperations::C8yLogFileRequest)
            .with_response_parameter(binary_upload_event_url)
            .to_smartrest()?;

    Ok(Message::new(&topic, smartrest_set_operation_status))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::convert::TryInto;

    #[test]
    fn convert_c8y_topic_to_str() {
        assert_eq!(C8yTopic::SmartRestRequest.as_str(), "c8y/s/ds");
        assert_eq!(C8yTopic::SmartRestResponse.as_str(), "c8y/s/us");
    }

    #[test]
    fn convert_str_into_c8y_topic() {
        let c8y_req: C8yTopic = "c8y/s/ds".try_into().unwrap();
        assert_eq!(c8y_req, C8yTopic::SmartRestRequest);
        let c8y_resp: C8yTopic = "c8y/s/us".try_into().unwrap();
        assert_eq!(c8y_resp, C8yTopic::SmartRestResponse);
        let error: Result<C8yTopic, TopicError> = "test".try_into();
        assert!(error.is_err());
    }

    #[test]
    fn convert_topic_into_c8y_topic() {
        let c8y_req: C8yTopic = Topic::new("c8y/s/ds").unwrap().try_into().unwrap();
        assert_eq!(c8y_req, C8yTopic::SmartRestRequest);

        let c8y_resp: C8yTopic = Topic::new("c8y/s/us").unwrap().try_into().unwrap();
        assert_eq!(c8y_resp, C8yTopic::SmartRestResponse);
        let error: Result<C8yTopic, TopicError> = Topic::new("test").unwrap().try_into();
        assert!(error.is_err());
    }
}