masaka 0.1.0

A highly modular, no-std async MQTT client
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
use core::time::Duration;

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use mqtt_proto::{QoS, TopicFilter, TopicName};

use crate::config::{
    ClientConfig, PublishConfig, V5ConnectConfig, V5PublishConfig, V5SubscribeConfig,
};
use crate::error::{ConfigError, MqttError, ProtocolError, TransportError};
use crate::protocol::{MqttProtocolEngine, MqttProtocolHandler, PacketAction, V5Handler};
use crate::session::{InMemorySession, InflightMessage, SessionState};
use crate::state::{ClientState, ClientStats, ConnectionState, ReceivedMessage};
use crate::time::{DefaultTimeProvider, TimeProvider};
use crate::transport::MqttTransport;

/// High-level MQTT client with comprehensive feature support.
pub struct MqttClient<T, H, S = InMemorySession, TP = DefaultTimeProvider>
where
    T: MqttTransport + Unpin,
    H: MqttProtocolHandler,
    S: SessionState,
    TP: TimeProvider,
{
    config: ClientConfig,
    protocol_engine: MqttProtocolEngine<T, H, TP>,
    state: ClientState,
    session_state: S,
    time_provider: TP,
    reconnect_attempt: u32,
    reconnect_interval_ms: u32,
}

impl<T, H> MqttClient<T, H, InMemorySession, DefaultTimeProvider>
where
    T: MqttTransport + Unpin,
    H: MqttProtocolHandler,
    H::Error: From<TransportError>,
{
    /// Creates a new MQTT client with default session and time provider.
    pub fn new(transport: T, protocol_handler: H, config: ClientConfig) -> Self {
        let time_provider = DefaultTimeProvider::default();
        let session_state = InMemorySession::new(config.max_subscriptions);

        Self::with_session_state(
            transport,
            protocol_handler,
            config,
            session_state,
            time_provider,
        )
    }
}

impl<T, H, S, TP> MqttClient<T, H, S, TP>
where
    T: MqttTransport + Unpin,
    H: MqttProtocolHandler,
    S: SessionState,
    H::Error: From<TransportError>,
    TP: TimeProvider + Clone,
{
    /// Creates a new MQTT client with custom session state and time provider.
    pub fn with_session_state(
        transport: T,
        protocol_handler: H,
        config: ClientConfig,
        session_state: S,
        time_provider: TP,
    ) -> Self {
        let state = ClientState::new(
            config.client_id.clone(),
            config.max_inflight_messages,
            config.clean_session,
        );
        let protocol_engine = MqttProtocolEngine::with_time_provider(
            transport,
            protocol_handler,
            time_provider.clone(),
        );

        Self {
            config,
            protocol_engine,
            state,
            session_state,
            time_provider,
            reconnect_attempt: 0,
            reconnect_interval_ms: 0,
        }
    }

    /// Connects to the MQTT broker.
    pub async fn connect(&mut self) -> Result<(), MqttError> {
        self.config.validate()?;
        self.state.set_connection_state(ConnectionState::Connecting);

        if self.config.clean_session {
            self.session_state.clear();
        }

        let (will_topic, will_message, will_qos, will_retain) =
            if let Some(will) = &self.config.will_message {
                (
                    Some(&will.topic),
                    Some(will.payload.as_slice()),
                    Some(will.qos),
                    will.retain,
                )
            } else {
                (None, None, None, false)
            };

        let result = self
            .protocol_engine
            .connect_with_will(
                &self.config.client_id,
                self.config.username.as_deref(),
                self.config.password.as_deref(),
                self.config.keep_alive,
                self.config.clean_session,
                will_topic,
                will_message,
                will_qos,
                will_retain,
            )
            .await;

        match result {
            Ok(PacketAction::ConnectAck {
                session_present,
                return_code: 0,
            }) => {
                self.state.set_connection_state(ConnectionState::Connected);
                self.reset_reconnect_state();

                if session_present && !self.config.clean_session {
                    log::info!("Session present, resuming and resending pending messages...");
                    self.resend_pending_messages().await?;
                }

                log::info!(
                    "Connected to MQTT broker (session_present: {}, will_message: {})",
                    session_present,
                    self.config.will_message.is_some()
                );
                Ok(())
            }
            Ok(PacketAction::ConnectAck { return_code, .. }) => {
                self.state.set_connection_state(ConnectionState::Error);
                log::error!("Connection failed with return code: {return_code}");
                Err(MqttError::AuthenticationFailed)
            }
            Err(err) => {
                self.state.set_connection_state(ConnectionState::Error);
                log::error!("Connection failed: {err}");
                Err(err)
            }
            _ => {
                self.state.set_connection_state(ConnectionState::Error);
                Err(MqttError::Protocol(ProtocolError::InvalidHeader))
            }
        }
    }

    /// Resends pending messages after reconnection.
    async fn resend_pending_messages(&mut self) -> Result<(), MqttError> {
        let mut to_resend = Vec::new();
        for (pid, msg) in self.session_state.pending_outgoing_publishes() {
            to_resend.push((pid, msg.clone()));
        }

        for (pid, msg) in to_resend {
            log::debug!(
                "Resending message to topic: {} (PID: {})",
                msg.topic,
                pid.value()
            );
            let packet = self
                .protocol_engine
                .handler
                .create_publish_packet(
                    &msg.topic,
                    msg.qos,
                    msg.retain,
                    &msg.payload,
                    Some(pid),
                    true, // Set DUP flag
                )
                .map_err(Into::into)?;
            self.protocol_engine
                .send_packet_from_client(&packet)
                .await?;
        }
        Ok(())
    }

    /// Attempts to reconnect to the broker using the configured strategy.
    pub async fn reconnect(&mut self) -> Result<(), MqttError> {
        if !self.config.reconnect.enabled {
            return Err(ConfigError::ReconnectDisabled.into());
        }

        if self.config.reconnect.max_attempts > 0
            && self.reconnect_attempt >= self.config.reconnect.max_attempts
        {
            log::error!(
                "Maximum reconnect attempts ({}) exceeded",
                self.config.reconnect.max_attempts
            );
            return Err(MqttError::Internal);
        }

        self.reconnect_attempt += 1;

        // Calculate reconnect interval (exponential backoff)
        if self.reconnect_interval_ms == 0 {
            self.reconnect_interval_ms = self.config.reconnect.initial_interval_ms;
        } else {
            let new_interval = (self.reconnect_interval_ms as f32
                * self.config.reconnect.backoff_multiplier) as u32;
            self.reconnect_interval_ms = new_interval.min(self.config.reconnect.max_interval_ms);
        }

        log::info!(
            "Attempting reconnect #{} after {}ms",
            self.reconnect_attempt,
            self.reconnect_interval_ms
        );

        // Wait for the reconnect interval
        self.time_provider
            .delay(Duration::from_millis(self.reconnect_interval_ms as u64))
            .await;

        // Attempt to reconnect
        self.connect().await
    }

    /// Publishes a message to a topic.
    pub async fn publish(
        &mut self,
        topic: &TopicName,
        payload: &[u8],
        config: PublishConfig,
    ) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        // Flow control check
        if self.session_state.pending_outgoing_publishes().count()
            >= self.config.max_inflight_messages
        {
            log::warn!("Max inflight messages reached, publish rejected");
            return Err(MqttError::PublishFailed);
        }

        let result = self
            .protocol_engine
            .publish(
                topic,
                config.qos,
                config.retain,
                payload,
                &mut self.session_state,
            )
            .await;

        match result {
            Ok(_pid) => {
                self.state.record_message_sent();
                log::debug!("Published message to topic: {topic}");
                Ok(())
            }
            Err(err) => {
                log::error!("Failed to publish message: {err}");
                Err(err)
            }
        }
    }

    /// Publishes a text message for convenience.
    pub async fn publish_text(
        &mut self,
        topic: &TopicName,
        text: &str,
        config: PublishConfig,
    ) -> Result<(), MqttError> {
        self.publish(topic, text.as_bytes(), config).await
    }

    /// Subscribes to a topic filter.
    pub async fn subscribe(
        &mut self,
        topic_filter: &TopicFilter,
        qos: QoS,
    ) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        let subscriptions = [(topic_filter.clone(), qos)];
        let pid = self
            .protocol_engine
            .subscribe(&subscriptions, &mut self.session_state)
            .await?;

        self.session_state
            .add_subscription(pid, topic_filter.clone(), qos)?;

        log::debug!("Subscribed to topic: {topic_filter} (QoS: {qos:?})");
        Ok(())
    }

    /// Subscribes to multiple topic filters in a single request.
    pub async fn subscribe_multiple(
        &mut self,
        subscriptions: &[(TopicFilter, QoS)],
    ) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        if subscriptions.is_empty() {
            return Ok(());
        }

        let pid = self
            .protocol_engine
            .subscribe(subscriptions, &mut self.session_state)
            .await?;

        // Add all subscriptions to session state
        for (topic_filter, qos) in subscriptions {
            self.session_state
                .add_subscription(pid, topic_filter.clone(), *qos)?;
        }

        log::debug!("Subscribed to {} topics", subscriptions.len());
        Ok(())
    }

    /// Unsubscribes from a topic filter.
    pub async fn unsubscribe(&mut self, topic_filter: &TopicFilter) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        let topics = [topic_filter.clone()];
        let _pid = self
            .protocol_engine
            .unsubscribe(&topics, &mut self.session_state)
            .await?;

        log::debug!("Unsubscribed from topic: {topic_filter}");
        Ok(())
    }

    /// Unsubscribes from multiple topic filters.
    pub async fn unsubscribe_multiple(
        &mut self,
        topic_filters: &[TopicFilter],
    ) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        if topic_filters.is_empty() {
            return Ok(());
        }

        let _pid = self
            .protocol_engine
            .unsubscribe(topic_filters, &mut self.session_state)
            .await?;

        log::debug!("Unsubscribed from {} topics", topic_filters.len());
        Ok(())
    }

    /// Sends a `PINGREQ` to the broker.
    pub async fn ping(&mut self) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        self.protocol_engine.ping().await
    }

    /// Disconnects from the broker.
    pub async fn disconnect(&mut self) -> Result<(), MqttError> {
        if self.state.connection_state() == ConnectionState::Disconnected {
            return Ok(());
        }

        self.state
            .set_connection_state(ConnectionState::Disconnecting);

        let result = self.protocol_engine.disconnect().await;
        self.state
            .set_connection_state(ConnectionState::Disconnected);

        result
    }

    /// Polls the client for new events and messages.
    pub async fn poll(&mut self) -> Result<Option<ClientEvent>, MqttError> {
        if !self.protocol_engine.is_connected() {
            if self.state.connection_state() == ConnectionState::Connected
                && self.config.reconnect.enabled
            {
                log::warn!("Connection lost, attempting to reconnect...");
                if self.reconnect().await.is_err() {
                    log::error!("Reconnect failed, client will remain disconnected.");
                    self.state
                        .set_connection_state(ConnectionState::Disconnected);
                    return Ok(Some(ClientEvent::Disconnected));
                }
            } else if self.state.connection_state() != ConnectionState::Disconnected {
                self.state
                    .set_connection_state(ConnectionState::Disconnected);
                return Ok(Some(ClientEvent::Disconnected));
            } else {
                return Ok(None);
            }
        }

        let current_time = self.time_provider.current_timestamp_ms();

        // Check for connection timeout
        if self.protocol_engine.is_connection_timeout(current_time) {
            log::warn!("Connection timeout detected");
            self.state.set_connection_state(ConnectionState::Error);
            return Err(MqttError::Transport(TransportError::Timeout));
        }

        // Check if we need to send keep-alive
        if self.protocol_engine.should_send_keep_alive(current_time) {
            log::debug!("Sending keep-alive ping");
            if let Err(err) = self.ping().await {
                log::error!("Failed to send keep-alive: {err}");
                return Err(err);
            }
        }

        // Handle retries
        if let Err(err) = self
            .protocol_engine
            .handle_retries(current_time, &mut self.session_state)
            .await
        {
            log::error!("Error handling retries: {err}");
            return Err(err);
        }

        // Process incoming packets
        match self
            .protocol_engine
            .receive_packet(&mut self.session_state)
            .await
        {
            Ok(action) => {
                let event = self.handle_packet_action(action).await?;
                Ok(event)
            }
            Err(err) => {
                log::error!("Error receiving packet: {err}");
                self.state.set_connection_state(ConnectionState::Error);
                Err(err)
            }
        }
    }

    /// Returns the next message from the receive queue, if any.
    pub fn next_message(&mut self) -> Option<ReceivedMessage> {
        self.state.pop_received_message()
    }

    /// Returns the current connection state.
    pub fn connection_state(&self) -> ConnectionState {
        self.state.connection_state()
    }

    /// Returns `true` if the client is connected.
    pub fn is_connected(&self) -> bool {
        self.state.connection_state() == ConnectionState::Connected
            && self.protocol_engine.is_connected()
    }

    /// Returns a reference to the client's statistics.
    pub fn stats(&self) -> &ClientStats {
        self.state.stats()
    }

    /// Returns the client configuration.
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    /// Returns a mutable reference to the session state.
    pub fn session_mut(&mut self) -> &mut S {
        &mut self.session_state
    }

    /// Returns a reference to the session state.
    pub fn session(&self) -> &S {
        &self.session_state
    }

    /// Handles a `PacketAction` from the protocol engine.
    async fn handle_packet_action(
        &mut self,
        action: PacketAction,
    ) -> Result<Option<ClientEvent>, MqttError> {
        match action {
            PacketAction::PublishReceived {
                topic,
                qos,
                retain,
                payload,
                pid,
            } => {
                let message = ReceivedMessage {
                    topic,
                    qos,
                    retain,
                    payload,
                    packet_id: pid,
                    timestamp: self.time_provider.current_timestamp_ms(),
                };
                self.state.add_received_message(message.clone());
                Ok(Some(ClientEvent::MessageReceived(message)))
            }
            PacketAction::SubscribeAck { pid, return_codes } => {
                self.session_state
                    .confirm_subscription(pid, &return_codes)?;
                Ok(Some(ClientEvent::SubscriptionConfirmed(pid)))
            }
            PacketAction::UnsubscribeAck { pid } => {
                self.session_state.remove_subscription(pid);
                Ok(Some(ClientEvent::UnsubscriptionConfirmed(pid)))
            }
            PacketAction::PingResponse => Ok(Some(ClientEvent::PingResponse)),
            PacketAction::PublishAck { pid } => Ok(Some(ClientEvent::MessageAcknowledged(pid))),
            PacketAction::PublishComplete { pid } => {
                Ok(Some(ClientEvent::MessageAcknowledged(pid)))
            }
            _ => Ok(None),
        }
    }

    /// Resets the reconnect attempt counter.
    fn reset_reconnect_state(&mut self) {
        self.reconnect_attempt = 0;
        self.reconnect_interval_ms = 0;
    }
}

/// Events emitted by the MQTT client.
#[derive(Debug)]
pub enum ClientEvent {
    /// The client has successfully connected.
    Connected,
    /// The client has been disconnected.
    Disconnected,
    /// A new message has been received.
    MessageReceived(ReceivedMessage),
    /// A QoS > 0 message has been acknowledged by the broker.
    MessageAcknowledged(mqtt_proto::Pid),
    /// A subscription has been confirmed by the broker.
    SubscriptionConfirmed(mqtt_proto::Pid),
    /// An unsubscription has been confirmed by the broker.
    UnsubscriptionConfirmed(mqtt_proto::Pid),
    /// A `PINGRESP` has been received from the broker.
    PingResponse,
    /// A connection error occurred.
    Error(String),
}

// MQTT v5.0 specific client extensions
impl<T> MqttClient<T, V5Handler, InMemorySession, DefaultTimeProvider>
where
    T: MqttTransport + Unpin,
{
    /// Creates a new MQTT v5.0 client with enhanced configuration.
    pub fn new_v5(transport: T, config: ClientConfig, v5_config: V5ConnectConfig) -> Self {
        let handler = V5Handler::with_config(v5_config);
        let max_subs = config.max_subscriptions;
        Self::with_session_state(
            transport,
            handler,
            config,
            InMemorySession::new(max_subs),
            DefaultTimeProvider::default(),
        )
    }
}

impl<T, S, TP> MqttClient<T, V5Handler, S, TP>
where
    T: MqttTransport + Unpin,
    S: SessionState,
    TP: TimeProvider + Clone,
{
    /// Publishes a message with full MQTT v5.0 properties support.
    pub async fn publish_v5(
        &mut self,
        topic: &TopicName,
        payload: &[u8],
        config: PublishConfig,
        v5_config: V5PublishConfig,
    ) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        // Flow control check
        if self.session_state.pending_outgoing_publishes().count()
            >= self.config.max_inflight_messages
        {
            log::warn!("Max inflight messages reached, publish rejected");
            return Err(MqttError::PublishFailed);
        }

        let pid = match config.qos {
            QoS::Level0 => None,
            QoS::Level1 | QoS::Level2 => Some(self.session_state.next_pid()),
        };

        // Create packet using enhanced v5 handler
        let packet = self
            .protocol_engine
            .handler
            .create_publish_with_config(
                topic,
                config.qos,
                config.retain,
                payload,
                pid,
                false, // DUP flag
                v5_config,
            )
            .map_err(|e| MqttError::Protocol(ProtocolError::V5Specific(e.to_string())))?;

        // Store for QoS > 0
        if let Some(pid) = pid {
            let message = InflightMessage {
                topic: topic.clone(),
                qos: config.qos,
                retain: config.retain,
                payload: payload.to_vec(),
                retry_count: 0,
                timestamp: self.time_provider.current_timestamp_ms(),
            };
            self.session_state.store_outgoing_publish(pid, message)?;
        }

        // Send packet
        self.protocol_engine
            .send_packet_from_client(&packet)
            .await?;
        self.state.record_message_sent();

        log::debug!("Published v5.0 message to topic: {topic}");
        Ok(())
    }

    /// Subscribes with full MQTT v5.0 properties support.
    pub async fn subscribe_v5(
        &mut self,
        subscriptions: &[(TopicFilter, QoS)],
        v5_config: V5SubscribeConfig,
    ) -> Result<(), MqttError> {
        if self.state.connection_state() != ConnectionState::Connected {
            return Err(MqttError::InvalidState);
        }

        if subscriptions.is_empty() {
            return Ok(());
        }

        let pid = self.session_state.next_pid();

        // Create packet using enhanced v5 handler
        let packet = self
            .protocol_engine
            .handler
            .create_subscribe_with_config(subscriptions, pid, v5_config)
            .map_err(|e| MqttError::Protocol(ProtocolError::V5Specific(e.to_string())))?;

        // Send packet
        self.protocol_engine
            .send_packet_from_client(&packet)
            .await?;

        // Add all subscriptions to session state
        for (topic_filter, qos) in subscriptions {
            self.session_state
                .add_subscription(pid, topic_filter.clone(), *qos)?;
        }

        log::debug!(
            "Subscribed to {} topics with v5.0 properties",
            subscriptions.len()
        );
        Ok(())
    }

    /// Publishes a request message and returns a future for the response.
    pub async fn publish_request(
        &mut self,
        request_topic: &TopicName,
        response_topic: &TopicName,
        payload: &[u8],
        config: PublishConfig,
        correlation_data: Vec<u8>,
    ) -> Result<(), MqttError> {
        let v5_config = V5PublishConfig {
            response_topic: Some(response_topic.clone()),
            correlation_data: Some(bytes::Bytes::from(correlation_data)),
            ..Default::default()
        };

        self.publish_v5(request_topic, payload, config, v5_config)
            .await
    }

    /// Publishes a response message with correlation data.
    pub async fn publish_response(
        &mut self,
        response_topic: &TopicName,
        payload: &[u8],
        config: PublishConfig,
        correlation_data: Vec<u8>,
    ) -> Result<(), MqttError> {
        let v5_config = V5PublishConfig {
            correlation_data: Some(bytes::Bytes::from(correlation_data)),
            ..Default::default()
        };

        self.publish_v5(response_topic, payload, config, v5_config)
            .await
    }

    /// Sets up a subscription with a specific subscription identifier.
    pub async fn subscribe_with_id(
        &mut self,
        topic_filter: &TopicFilter,
        qos: QoS,
        subscription_id: u32,
    ) -> Result<(), MqttError> {
        let subscriptions = [(topic_filter.clone(), qos)];
        let v5_config = V5SubscribeConfig {
            subscription_identifier: Some(
                mqtt_proto::v5::VarByteInt::try_from(subscription_id)
                    .map_err(|_| MqttError::Protocol(ProtocolError::InvalidPacketId))?,
            ),
            ..Default::default()
        };

        self.subscribe_v5(&subscriptions, v5_config).await
    }

    /// Updates the v5.0 connection configuration.
    pub fn set_v5_config(&mut self, config: V5ConnectConfig) {
        self.protocol_engine.handler.set_connect_config(config);
    }

    /// Gets a reference to the current v5.0 configuration.
    pub fn v5_config(&self) -> &V5ConnectConfig {
        &self.protocol_engine.handler.connect_config
    }
}