Build valid and verified MQTT topics
MqttTopicBuilder helps you construct valid MQTT topics using a fluent builder API. It enforces MQTT topic rules at build time, preventing common mistakes like using wildcards in publisher topics or placing wildcards in invalid positions.
Install via .NET CLI:
dotnet add package MqttTopicBuilderOr via Package Manager Console:
Install-Package MqttTopicBuilderUse the TopicBuilder to construct topics with validation based on whether you're publishing or subscribing:
// Subscriber topic with wildcards
var subscribeTopic = new TopicBuilder(TopicConsumer.Subscriber)
.AddTopic("sensors")
.AddTopic("temperature")
.AddMultiLevelWildcard()
.Build();
Console.WriteLine(subscribeTopic);
// Output: "sensors/temperature/#"
// Publisher topic (wildcards not allowed)
var publishTopic = new TopicBuilder(TopicConsumer.Publisher)
.AddTopic("sensors")
.AddTopic("temperature")
.AddTopic("room1")
.Build();
Console.WriteLine(publishTopic);
// Output: "sensors/temperature/room1"Access topic metadata through the Topic object:
var topic = new TopicBuilder(TopicConsumer.Subscriber)
.AddTopic("home")
.AddTopic("livingroom")
.AddTopic("temperature")
.Build();
Console.WriteLine(topic.Value); // "home/livingroom/temperature"
Console.WriteLine(topic.Levels); // 3Convert existing topic strings into Topic objects:
var topic = Topic.FromString("home/kitchen/humidity");
// or using implicit conversion:
// var topic = (Topic)"home/kitchen/humidity";
Console.WriteLine(topic.Value); // "home/kitchen/humidity"
Console.WriteLine(topic.Levels); // 3Validate topic strings before using them:
Topic integrity can also be checked sing the TopicValidator methods:
TopicValidator.ValidateTopic("a/wrong/#/Topic");
// Will throw an exception since no topic is allowed after '#'
"wrong+Topic".ValidateTopicForAppending();
// Will throw an exception since '+' is not allowed in a topicMQTT Topics rules are checked, such as if the topic is not blank, is utf-8, does not contains any forbidden character, and so on.
If any rule isn't respected, this will throw a specific exception, inheriting from the
MqttBaseException.
- Fluent API - Intuitive builder pattern for constructing topics
- Validation - Enforces MQTT specification rules
- Wildcard support - Proper handling of single-level (
+) and multi-level (#) wildcards - Publisher and Subscriber modes - Build topics with validation rules specific to each use case
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.