Created
February 9, 2025 21:21
-
-
Save ramonsmits/8d9ee9d94a934cc5d5a930b33b27b228 to your computer and use it in GitHub Desktop.
MQTTnet MessagePack helper that supports mqtt 5 topic alias
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MessagePack; | |
using MQTTnet; | |
using MQTTnet.Client; | |
public static class MqttExtensions | |
{ | |
static readonly HashSet<ushort> topicAliases = new(); | |
/// <summary> | |
/// Publish a message pack serialized message with optional topic alias. | |
/// </summary> | |
/// <remarks> | |
/// The implementation will stop using the topic once the alias is successfully published once and could result | |
/// in the topic to be use more than once but this is the safe approach compared to only using the topic for | |
/// the 1st message | |
/// </remarks> | |
public static async ValueTask PublishMsgPack<T>( | |
this IMqttClient client, | |
string topic, | |
T value, | |
ushort alias = 0, | |
CancellationToken cancellationToken = default | |
) where T : struct | |
{ | |
var useAliasOnly = alias != 0 && topicAliases.Contains(alias); // Safe without lock | |
var payload = MessagePackSerializer.Serialize(value); | |
var message = new MqttApplicationMessage | |
{ | |
TopicAlias = alias, PayloadSegment = payload | |
}; | |
if (!useAliasOnly) message.Topic = topic; | |
await client.PublishAsync(message, cancellationToken); | |
if (useAliasOnly) return; | |
lock (topicAliases) topicAliases.Add(alias); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment