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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Fundamentum Client
//!

use crate::message::Message;
use crate::models::{Command, DeviceCommandUpdate, HeartBeat, StatesEvent};
use crate::{error, Device, Security};
use rumqttc::{self, Event, LastWill, MqttOptions, QoS, TlsConfiguration, Transport};
use rumqttc::{ClientError, Packet};
use tokio::{
    sync::broadcast::{self, Receiver, Sender},
    time::Duration,
};

use rumqttc::{AsyncClient, EventLoop};
use tracing::error;

/// Max Packet Size Override
pub struct MQTTMaxPacketSize {
    incoming_max_packet_size: usize,
    outgoing_max_packet_size: usize,
}

/// Option Size Override
pub struct MQTTOptionsOverrides {
    /// Override clean_session
    pub clean_session: Option<bool>,
    /// Override keep_alive
    pub keep_alive: Option<Duration>,
    /// Override max_packet_size
    pub max_packet_size: Option<MQTTMaxPacketSize>,
    /// Override request_channel_capacity
    pub request_channel_capacity: Option<usize>,
    /// Override pending_throttle
    pub pending_throttle: Option<Duration>,
    /// Override inflight
    pub inflight: Option<u16>,
    /// Override last_will
    pub last_will: Option<LastWill>,
    /// Override transport
    pub transport: Option<Transport>,
}

/// Fundamentum `IoT` Settings
pub struct ClientSettings {
    /// Security strategy
    security: Security,
    /// Device's representation
    device: Device,
    /// Fundamentum endpoint
    endpoint: String,
    /// MQTT options overrides
    mqtt_options_overrides: Option<MQTTOptionsOverrides>,
}

impl ClientSettings {
    /// Create a new `FundamentumIoTSettings`
    ///
    /// # Params
    ///
    /// * `security`: Security generator
    /// * `device`: Device's definition
    /// * `iot_endpoint`: Uri endpoint MQTT
    /// * `mqtt_options_overrides`: MQTT options overrides
    ///
    #[must_use]
    pub const fn new(
        security: Security,
        device: Device,
        endpoint: String,
        mqtt_options_overrides: Option<MQTTOptionsOverrides>,
    ) -> Self {
        Self {
            security,
            device,
            endpoint,
            mqtt_options_overrides,
        }
    }
}

async fn get_mqtt_options(settings: ClientSettings) -> Result<MqttOptions, error::Error> {
    let mut mqtt_options = MqttOptions::new(settings.device.client_id(), settings.endpoint, 8883);
    let mut transport_overrided = false;

    if let Some(overrides) = settings.mqtt_options_overrides {
        if let Some(clean_session) = overrides.clean_session {
            mqtt_options.set_clean_session(clean_session);
        }
        if let Some(transport) = overrides.transport {
            transport_overrided = true;
            mqtt_options.set_transport(transport);
        }
        if let Some(keep_alive) = overrides.keep_alive {
            mqtt_options.set_keep_alive(keep_alive);
        }
        if let Some(packet_size) = overrides.max_packet_size {
            mqtt_options.set_max_packet_size(
                packet_size.incoming_max_packet_size,
                packet_size.outgoing_max_packet_size,
            );
        }
        if let Some(request_channel_capacity) = overrides.request_channel_capacity {
            mqtt_options.set_request_channel_capacity(request_channel_capacity);
        }
        if let Some(pending_throttle) = overrides.pending_throttle {
            mqtt_options.set_pending_throttle(pending_throttle);
        }
        if let Some(inflight) = overrides.inflight {
            mqtt_options.set_inflight(inflight);
        }
        if let Some(clean_session) = overrides.clean_session {
            mqtt_options.set_clean_session(clean_session);
        }
        if let Some(last_will) = overrides.last_will {
            mqtt_options.set_last_will(last_will);
        }
    }

    // Generate a new signed token
    let token = settings.security.generate_token().await?;
    mqtt_options.set_credentials("unused", token);

    if !transport_overrided {
        let transport = Transport::Tls(TlsConfiguration::default());
        mqtt_options.set_transport(transport);
    }

    mqtt_options.set_keep_alive(Duration::from_secs(10));

    Ok(mqtt_options)
}

/// Async Event Loop Listener
///
/// # Errors
///
/// TODO
pub async fn async_event_loop_listener(
    (mut eventloop, incoming_event_sender): (EventLoop, Sender<Message>),
) -> Result<(), error::Error> {
    loop {
        match eventloop.poll().await {
            Ok(event) => {
                if let Event::Incoming(packet) = event {
                    match packet {
                        Packet::Publish(p) => {
                            if p.topic.ends_with("/commands") {
                                match serde_json::from_slice::<Vec<Command>>(&p.payload) {
                                    // Fundamentum's commands
                                    Ok(commands) => {
                                        if let Err(e) =
                                            incoming_event_sender.send(Message::Commands(commands))
                                        {
                                            error!("Error sending incoming event: {e:?}");
                                        }
                                    }
                                    Err(e) => error!("Error sending incoming event: {e:?}"),
                                }
                            } else {
                                // Custom packet
                                if let Err(e) =
                                    incoming_event_sender.send(Message::Other(Packet::Publish(p)))
                                {
                                    error!("Error sending incoming event: {e:?}");
                                }
                            }
                        }
                        packet => {
                            if let Err(e) = incoming_event_sender.send(Message::Other(packet)) {
                                error!("Error sending incoming event: {e:?}");
                            }
                        }
                    }
                }
            }
            Err(e) => {
                error!("Connection error: {e:?}");
            }
        }
    }
}

/// Fundamentum `IoT` Async Client
pub struct Client {
    client: AsyncClient,
    device: Device,
    incoming_event_sender: Sender<Message>,
}

impl Client {
    /// Create new `FundamentumIoTAsyncClient`. Input argument should be the `FundamentumIoTSettings`. Returns a tuple where the first element is the
    /// `FundamentumIoTAsyncClient`, and the second element is a new tuple with the eventloop and incoming
    /// event sender. This tuple should be sent as an argument to the `async_event_loop_listener`.
    ///
    /// # Errors
    ///
    /// If the creation failed then the result returns an error `FundamentumIoTError`
    pub async fn new(
        settings: ClientSettings,
    ) -> Result<(Self, (EventLoop, Sender<Message>)), error::Error> {
        let device = settings.device.clone();
        let mqtt_options = get_mqtt_options(settings).await?;

        let (client, eventloop) = AsyncClient::new(mqtt_options, 10);
        let (request_tx, _) = broadcast::channel(50);
        Ok((
            Self {
                client,
                device,
                incoming_event_sender: request_tx.clone(),
            },
            (eventloop, request_tx),
        ))
    }

    /// Subscribe to a topic
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    pub async fn subscribe<S: Into<String> + Send>(
        &self,
        topic: S,
        qos: QoS,
    ) -> Result<(), ClientError> {
        self.client.subscribe(topic, qos).await
    }

    /// Subscribe to device's config channel
    ///
    /// # Reference
    /// * `registries/{REGISTRY_ID}/devices/{DEVICE_SN}/config`
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    pub async fn subscribe_config(&self, qos: QoS) -> Result<(), ClientError> {
        self.subscribe(
            format!(
                "registries/{}/devices/{}/config",
                self.device.registry_id(),
                self.device.serial()
            ),
            qos,
        )
        .await
    }

    /// Subscribe to device's commands channel
    ///
    /// # Reference
    /// * `registries/{REGISTRY_ID}/devices/{DEVICE_SN}/commands`
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    pub async fn subscribe_commands(&self, qos: QoS) -> Result<(), ClientError> {
        self.subscribe(
            format!(
                "registries/{}/devices/{}/commands",
                self.device.registry_id(),
                self.device.serial()
            ),
            qos,
        )
        .await
    }

    /// Publish to topic.
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    pub async fn publish<S, V>(&self, topic: S, qos: QoS, payload: V) -> Result<(), ClientError>
    where
        S: Into<String> + Send,
        V: Into<Vec<u8>> + Send,
    {
        self.client.publish(topic, qos, false, payload).await
    }

    /// Publish event
    ///
    /// # Reference
    /// *  `registries/{REGISTRY_ID}/devices/{DEVICE_SN}/events`
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    pub async fn publish_events<V>(&self, qos: QoS, payload: V) -> Result<(), ClientError>
    where
        V: Into<Vec<u8>> + Send,
    {
        self.publish(
            format!(
                "registries/{}/devices/{}/events",
                self.device.registry_id(),
                self.device.serial()
            ),
            qos,
            payload,
        )
        .await
    }

    /// Publish heartbeat
    ///
    /// # Params
    ///
    /// * `qos`: mqtt's qos
    /// * `uptime`: number of second since boot
    ///
    /// # Reference
    ///
    /// *  `registries/{REGISTRY_ID}/devices/{DEVICE_SN}/heartbeat`
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    ///
    /// # Panics
    ///
    /// This function should never panic because the string is controled by rust types
    ///
    pub async fn publish_heartbeat(&self, qos: QoS, params: &HeartBeat) -> Result<(), ClientError> {
        self.publish(
            format!(
                "registries/{}/devices/{}/heartbeat",
                self.device.registry_id(),
                self.device.serial()
            ),
            qos,
            serde_json::to_string(params).expect("must be a valid json serialization"),
        )
        .await
    }

    /// Publish states
    ///
    /// # Reference
    /// *  `registries/{REGISTRY_ID}/devices/{DEVICE_SN}/states`
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    ///
    /// # Panics
    ///
    /// This function should never panic because the string is controled by rust types
    ///
    pub async fn publish_states(&self, qos: QoS, params: &StatesEvent) -> Result<(), ClientError> {
        self.publish(
            format!(
                "registries/{}/devices/{}/states",
                self.device.registry_id(),
                self.device.serial()
            ),
            qos,
            serde_json::to_string(params).expect("must be a valid json serialization"),
        )
        .await
    }

    /// Publish Device Command Update
    ///
    /// The command update the current status of a receive command.
    /// The `device_command_id` comes from the command receive by the client.
    ///
    /// # Reference
    /// *  `registries/{REGISTRY_ID}/devices/{DEVICE_SN}/commands/{DEVICE_COMMAND_ID}`
    ///
    /// # Errors
    ///
    /// Returns `ClientError` if the request failed
    ///
    /// # Panics
    ///
    /// This function should never panic because the string is controled by rust types
    ///
    pub async fn publish_update_command(
        &self,
        cmdid: u64,
        qos: QoS,
        params: &DeviceCommandUpdate,
    ) -> Result<(), ClientError> {
        self.publish(
            format!(
                "registries/{}/devices/{}/commands/{}",
                self.device.registry_id(),
                self.device.serial(),
                cmdid
            ),
            qos,
            serde_json::to_string(&params).expect("must be a valid json serialization"),
        )
        .await
    }

    /// Get a receiver of the incoming messages. Send this to any function that wants to read the
    /// incoming messages from `IoT` Core.
    #[must_use]
    pub fn get_receiver(&self) -> Receiver<Message> {
        self.incoming_event_sender.subscribe()
    }

    /// If you want to use the Rumqttc `AsyncClient` and `EventLoop` manually, this method can be used
    /// to get the `AsyncClient`.
    #[must_use]
    #[allow(clippy::nursery)]
    pub fn get_client(self) -> AsyncClient {
        self.client
    }
}