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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use core::fmt::Display;
use core::fmt::Write;
use core::str::FromStr;

use heapless::String;
use mqttrust::{Mqtt, QoS, SubscribeTopic};

use super::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Direction {
    Incoming,
    Outgoing,
}

#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PayloadFormat {
    #[cfg(feature = "provision_cbor")]
    Cbor,
    Json,
}

impl Display for PayloadFormat {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(feature = "provision_cbor")]
            Self::Cbor => write!(f, "cbor"),
            Self::Json => write!(f, "json"),
        }
    }
}

impl FromStr for PayloadFormat {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            #[cfg(feature = "provision_cbor")]
            "cbor" => Ok(Self::Cbor),
            "json" => Ok(Self::Json),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Topic<'a> {
    // ---- Outgoing Topics
    /// `$aws/provisioning-templates/<templateName>/provision/<payloadFormat>`
    RegisterThing(&'a str, PayloadFormat),

    /// $aws/certificates/create/<payloadFormat>
    CreateKeysAndCertificate(PayloadFormat),

    /// $aws/certificates/create-from-csr/<payloadFormat>
    CreateCertificateFromCsr(PayloadFormat),

    // ---- Incoming Topics
    /// `$aws/provisioning-templates/<templateName>/provision/<payloadFormat>/accepted`
    RegisterThingAccepted(&'a str, PayloadFormat),

    /// `$aws/provisioning-templates/<templateName>/provision/<payloadFormat>/rejected`
    RegisterThingRejected(&'a str, PayloadFormat),

    /// `$aws/certificates/create/<payloadFormat>/accepted`
    CreateKeysAndCertificateAccepted(PayloadFormat),

    /// `$aws/certificates/create/<payloadFormat>/rejected`
    CreateKeysAndCertificateRejected(PayloadFormat),

    /// `$aws/certificates/create-from-csr/<payloadFormat>/accepted`
    CreateCertificateFromCsrAccepted(PayloadFormat),

    /// `$aws/certificates/create-from-csr/<payloadFormat>/rejected`
    CreateCertificateFromCsrRejected(PayloadFormat),
}

impl<'a> Topic<'a> {
    const CERT_PREFIX: &'static str = "$aws/certificates";
    const PROVISIONING_PREFIX: &'static str = "$aws/provisioning-templates";

    pub fn check(s: &'a str) -> bool {
        s.starts_with(Self::CERT_PREFIX) || s.starts_with(Self::PROVISIONING_PREFIX)
    }

    pub fn from_str(s: &'a str) -> Option<Self> {
        let tt = s.splitn(6, '/').collect::<heapless::Vec<&str, 6>>();
        match (tt.get(0), tt.get(1)) {
            (Some(&"$aws"), Some(&"provisioning-templates")) => {
                // This is a register thing topic, now figure out which one.

                match (tt.get(2), tt.get(3), tt.get(4), tt.get(5)) {
                    (
                        Some(template_name),
                        Some(&"provision"),
                        Some(payload_format),
                        Some(&"accepted"),
                    ) => Some(Topic::RegisterThingAccepted(
                        *template_name,
                        PayloadFormat::from_str(payload_format).ok()?,
                    )),
                    (
                        Some(template_name),
                        Some(&"provision"),
                        Some(payload_format),
                        Some(&"rejected"),
                    ) => Some(Topic::RegisterThingRejected(
                        *template_name,
                        PayloadFormat::from_str(payload_format).ok()?,
                    )),
                    _ => None,
                }
            }
            (Some(&"$aws"), Some(&"certificates")) => {
                // This is a register thing topic, now figure out which one.

                match (tt.get(2), tt.get(3), tt.get(4)) {
                    (Some(&"create"), Some(payload_format), Some(&"accepted")) => {
                        Some(Topic::CreateKeysAndCertificateAccepted(
                            PayloadFormat::from_str(payload_format).ok()?,
                        ))
                    }
                    (Some(&"create"), Some(payload_format), Some(&"rejected")) => {
                        Some(Topic::CreateKeysAndCertificateRejected(
                            PayloadFormat::from_str(payload_format).ok()?,
                        ))
                    }
                    (Some(&"create-from-csr"), Some(payload_format), Some(&"accepted")) => {
                        Some(Topic::CreateCertificateFromCsrAccepted(
                            PayloadFormat::from_str(payload_format).ok()?,
                        ))
                    }
                    (Some(&"create-from-csr"), Some(payload_format), Some(&"rejected")) => {
                        Some(Topic::CreateCertificateFromCsrRejected(
                            PayloadFormat::from_str(payload_format).ok()?,
                        ))
                    }
                    _ => None,
                }
            }
            _ => None,
        }
    }

    pub fn direction(&self) -> Direction {
        if matches!(
            self,
            Topic::RegisterThing(_, _)
                | Topic::CreateKeysAndCertificate(_)
                | Topic::CreateCertificateFromCsr(_)
        ) {
            Direction::Outgoing
        } else {
            Direction::Incoming
        }
    }

    pub fn format<const L: usize>(&self) -> Result<String<L>, Error> {
        let mut topic_path = String::new();
        match self {
            Self::RegisterThing(template_name, payload_format) => {
                topic_path.write_fmt(format_args!(
                    "{}/{}/provision/{}",
                    Self::PROVISIONING_PREFIX,
                    template_name,
                    payload_format,
                ))
            }
            Topic::RegisterThingAccepted(template_name, payload_format) => {
                topic_path.write_fmt(format_args!(
                    "{}/{}/provision/{}/accepted",
                    Self::PROVISIONING_PREFIX,
                    template_name,
                    payload_format,
                ))
            }
            Topic::RegisterThingRejected(template_name, payload_format) => {
                topic_path.write_fmt(format_args!(
                    "{}/{}/provision/{}/rejected",
                    Self::PROVISIONING_PREFIX,
                    template_name,
                    payload_format,
                ))
            }

            Topic::CreateKeysAndCertificate(payload_format) => topic_path.write_fmt(format_args!(
                "{}/create/{}",
                Self::CERT_PREFIX,
                payload_format,
            )),

            Topic::CreateKeysAndCertificateAccepted(payload_format) => topic_path.write_fmt(
                format_args!("{}/create/{}/accepted", Self::CERT_PREFIX, payload_format),
            ),
            Topic::CreateKeysAndCertificateRejected(payload_format) => topic_path.write_fmt(
                format_args!("{}/create/{}/rejected", Self::CERT_PREFIX, payload_format),
            ),

            Topic::CreateCertificateFromCsr(payload_format) => topic_path.write_fmt(format_args!(
                "{}/create-from-csr/{}",
                Self::CERT_PREFIX,
                payload_format,
            )),
            Topic::CreateCertificateFromCsrAccepted(payload_format) => topic_path.write_fmt(
                format_args!("{}/create-from-csr/{}", Self::CERT_PREFIX, payload_format),
            ),
            Topic::CreateCertificateFromCsrRejected(payload_format) => topic_path.write_fmt(
                format_args!("{}/create-from-csr/{}", Self::CERT_PREFIX, payload_format),
            ),
        }
        .map_err(|_| Error::Overflow)?;

        Ok(topic_path)
    }
}

#[derive(Default)]
pub struct Subscribe<'a, const N: usize> {
    topics: heapless::Vec<(Topic<'a>, QoS), N>,
}

impl<'a, const N: usize> Subscribe<'a, N> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn topic(self, topic: Topic<'a>, qos: QoS) -> Self {
        // Ignore attempts to subscribe to outgoing topics
        if topic.direction() != Direction::Incoming {
            return self;
        }

        if self.topics.iter().any(|(t, _)| t == &topic) {
            return self;
        }

        let mut topics = self.topics;
        topics.push((topic, qos)).ok();

        Self { topics }
    }

    pub fn topics(self) -> Result<heapless::Vec<(heapless::String<128>, QoS), N>, Error> {
        self.topics
            .iter()
            .map(|(topic, qos)| Ok((topic.clone().format()?, *qos)))
            .collect()
    }

    pub fn send<M: Mqtt>(self, mqtt: &M) -> Result<(), Error> {
        if self.topics.is_empty() {
            return Ok(());
        }

        let topic_paths = self.topics()?;

        debug!("Subscribing! {:?}", topic_paths);

        let topics: heapless::Vec<_, N> = topic_paths
            .iter()
            .map(|(s, qos)| SubscribeTopic {
                topic_path: s.as_str(),
                qos: *qos,
            })
            .collect();

        for t in topics.chunks(5) {
            mqtt.subscribe(t)?;
        }
        Ok(())
    }
}

#[derive(Default)]
pub struct Unsubscribe<'a, const N: usize> {
    topics: heapless::Vec<Topic<'a>, N>,
}

impl<'a, const N: usize> Unsubscribe<'a, N> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn topic(self, topic: Topic<'a>) -> Self {
        // Ignore attempts to subscribe to outgoing topics
        if topic.direction() != Direction::Incoming {
            return self;
        }

        if self.topics.iter().any(|t| t == &topic) {
            return self;
        }

        let mut topics = self.topics;
        topics.push(topic).ok();
        Self { topics }
    }

    pub fn topics(self) -> Result<heapless::Vec<heapless::String<256>, N>, Error> {
        self.topics
            .iter()
            .map(|topic| topic.clone().format())
            .collect()
    }

    pub fn send<M: Mqtt>(self, mqtt: &M) -> Result<(), Error> {
        if self.topics.is_empty() {
            return Ok(());
        }

        let topic_paths = self.topics()?;
        let topics: heapless::Vec<_, N> = topic_paths.iter().map(|s| s.as_str()).collect();

        for t in topics.chunks(5) {
            mqtt.unsubscribe(t)?;
        }

        Ok(())
    }
}