Skip to content

Commit f7f8fad

Browse files
committed
Fix auto_map_topic_alias_send logic
Previously, it would always remove the topic name when adding the alias, even the first time, so the mapping would not be set on the server, and the server would reject the packet.
1 parent fe389da commit f7f8fad

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/mqtt/connection/core.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1630,7 +1630,7 @@ where
16301630
} else {
16311631
let lru_ta = topic_alias_send.get_lru_alias();
16321632
topic_alias_send.insert_or_update(packet.topic_name(), lru_ta);
1633-
packet = packet.remove_topic_add_topic_alias(lru_ta);
1633+
packet = packet.add_topic_alias(lru_ta);
16341634
}
16351635
}
16361636
} else if self.auto_replace_topic_alias_send {

src/mqtt/packet/v5_0/publish.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,45 @@ where
688688
// Set topic name to empty string
689689
self.topic_name_buf = MqttString::new("").unwrap();
690690

691+
self.add_topic_alias(topic_alias)
692+
}
693+
694+
/// Add TopicAlias property
695+
///
696+
/// This method adds a TopicAlias property to the packet properties. This
697+
/// is required to associate a topic alias with a topic name on the server.
698+
/// Future messages can use only the topic alias and omit the topic name.
699+
/// This is useful for reducing packet size when sending multiple messages
700+
/// to the same topic.
701+
///
702+
/// The method removes any existing TopicAlias property before adding the new one
703+
/// to ensure only one TopicAlias property exists. It automatically recalculates
704+
/// the property_length and remaining_length to reflect these changes.
705+
///
706+
/// # Parameters
707+
///
708+
/// - `topic_alias`: The numeric topic alias to associate with the topic name
709+
///
710+
/// # Returns
711+
///
712+
/// The modified `GenericPublish` instance with the TopicAlias property
713+
///
714+
/// # Examples
715+
///
716+
/// ```ignore
717+
/// use mqtt_protocol_core::mqtt;
718+
///
719+
/// let publish_with_topic = mqtt::packet::v5_0::Publish::builder()
720+
/// .topic_name("sensors/temperature/room1")
721+
/// .unwrap()
722+
/// .payload(b"23.5")
723+
/// .build()
724+
/// .unwrap();
725+
///
726+
/// let publish_with_alias = publish_with_topic.add_topic_alias(42);
727+
/// // props() now contains TopicAlias property with value 42
728+
/// ```
729+
pub fn add_topic_alias(mut self, topic_alias: TopicAliasType) -> Self {
691730
// Add TopicAlias property to the end of properties
692731
let topic_alias_property =
693732
Property::TopicAlias(crate::mqtt::packet::TopicAlias::new(topic_alias).unwrap());

0 commit comments

Comments
 (0)