### Quick Start HiveMQClient Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md Demonstrates basic client initialization, message handling, connection, subscription, and publishing. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Create a client var client = new HiveMQClient(); // Setup message handler BEFORE subscribing client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message received on {args.PublishMessage.Topic}: {args.PublishMessage.PayloadAsString}"); }; // Connect to the broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // Subscribe to a topic (tracked in client.Subscriptions) await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Publish a message await client.PublishAsync("my/topic", "Hello from HiveMQClient!").ConfigureAwait(false); // Disconnect when done await client.DisconnectAsync().ConfigureAwait(false); client.Dispose(); ``` -------------------------------- ### Start Docusaurus Development Server Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/README.md Launches a local development server with live reloading. ```bash $ yarn start ``` -------------------------------- ### Comprehensive SubscribeOptionsBuilder Example Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/subscribing.md Demonstrates all available configuration options including NoLocal, RetainAsPublished, and RetainHandling. ```csharp using HiveMQtt.MQTT5.Types; var options = new SubscribeOptionsBuilder() .WithSubscription( "topic1", // Topic QualityOfService.ExactlyOnceDelivery, // Quality of Service Level true, // NoLocal true, // RetainAsPublished RetainHandling.SendAtSubscribe) // RetainHandling .WithUserProperty("property1", "value1") .WithUserProperties( new Dictionary { { "property1", "value1" }, { "property2", "value2" } }) .Build(); ``` -------------------------------- ### Minimal MQTT Client Example Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/quickstart.md A simplified implementation for testing with a local broker using default settings. ```csharp using HiveMQtt.Client; // Connect to localhost:1883 with defaults var client = new HiveMQClient(); await client.ConnectAsync(); // Publish a message await client.PublishAsync("test/topic", "Hello World!"); // Clean up await client.DisconnectAsync(); client.Dispose(); ``` -------------------------------- ### Complete MQTT Workflow Example Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/quickstart.md Demonstrates the full lifecycle of configuring, connecting, subscribing, and publishing. Ensure message handlers are defined before subscribing to capture retained messages. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // 1. Configure client options var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(1883) .Build(); var client = new HiveMQClient(options); // 2. Set up message handler BEFORE subscribing client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message Received: {args.PublishMessage.PayloadAsString}"); }; // 3. Connect to the broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // 4. Subscribe to topics var subscribeOptions = new SubscribeOptionsBuilder() .WithSubscription("topic1", QualityOfService.AtLeastOnceDelivery) .WithSubscription("topic2", QualityOfService.ExactlyOnceDelivery) .Build(); var subscribeResult = await client.SubscribeAsync(subscribeOptions).ConfigureAwait(false); // 5. Publish a message var publishResult = await client.PublishAsync("topic1/example", "Hello, MQTT!").ConfigureAwait(false); // 6. Disconnect when done await client.DisconnectAsync().ConfigureAwait(false); client.Dispose(); ``` -------------------------------- ### Install DocFX Tool Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/README.md Installs the DocFX command-line tool globally via the .NET CLI. ```bash $ dotnet tool install docfx ``` -------------------------------- ### Example Usage of PublishMessageBuilder Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/publish_message_builder.md Demonstrates how to configure a topic and payload before building the message. ```csharp var message = new PublishMessageBuilder() .WithTopic("home/sensors/temperature") .WithPayload("22.5°C") .Build(); ``` -------------------------------- ### Secure Configuration File Example Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/security.md Use environment-specific configuration files that are excluded from source control. ```json // appsettings.Production.json - deployed securely, not in source control { "Mqtt": { "Broker": "production-broker.hivemq.cloud", "Username": "prod-user" } } ``` -------------------------------- ### Install HiveMQtt.Sparkplug NuGet package Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/sparkplug/intro.md Use the .NET CLI to add the Sparkplug client extension to your project. ```bash dotnet add package HiveMQtt.Sparkplug ``` -------------------------------- ### WithCleanStart(bool cleanStart) Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options_builder.md Configures whether the connection starts a new session or continues an existing one. ```APIDOC ## WithCleanStart(bool cleanStart) ### Description Specifies whether the Connection starts a new Session or is a continuation of an existing Session. This overrides any value set in HiveMQClientOptions. ### Parameters - **cleanStart** (bool) - Required - True to start a new session, false to continue an existing one. ``` -------------------------------- ### Install HiveMQtt NuGet Package Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/quickstart.md Use the .NET CLI to add the HiveMQtt package to your project. ```bash dotnet add package HiveMQtt ``` -------------------------------- ### Complete HiveMQClient Implementation Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md A full example demonstrating client configuration, event handling, connection management, subscription handling, and message publishing. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Configure the client var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(1883) .WithClientId("hivemqclient-example") .WithAutomaticReconnect(true) .Build(); var client = new HiveMQClient(options); // Setup global message handler client.OnMessageReceived += (sender, args) => { Console.WriteLine($"[{args.PublishMessage.Topic}]: {args.PublishMessage.PayloadAsString}"); }; // Track connection state changes client.AfterConnect += (sender, args) => Console.WriteLine("Connected to broker"); client.AfterDisconnect += (sender, args) => Console.WriteLine("Disconnected from broker"); try { // Connect var connectResult = await client.ConnectAsync().ConfigureAwait(false); if (connectResult.ReasonCode != ConnAckReasonCode.Success) { Console.WriteLine($"Connection failed: {connectResult.ReasonCode}"); return; } // Subscribe with per-subscription callbacks var subscribeOptions = new SubscribeOptionsBuilder() .WithSubscription( new TopicFilter("sensors/temperature", QualityOfService.AtLeastOnceDelivery), (sender, args) => Console.WriteLine($"Temperature: {args.PublishMessage.PayloadAsString}")) .WithSubscription( new TopicFilter("sensors/humidity", QualityOfService.AtLeastOnceDelivery), (sender, args) => Console.WriteLine($"Humidity: {args.PublishMessage.PayloadAsString}")) .Build(); await client.SubscribeAsync(subscribeOptions).ConfigureAwait(false); // View tracked subscriptions Console.WriteLine($"Active subscriptions: {client.Subscriptions.Count}"); // Publish messages for (var i = 0; i < 10; i++) { await client.PublishAsync("sensors/temperature", $"{20 + i}°C").ConfigureAwait(false); await Task.Delay(100); } // Wait for messages await Task.Delay(1000); // Unsubscribe by topic await client.UnsubscribeAsync("sensors/temperature").ConfigureAwait(false); // Disconnect await client.DisconnectAsync().ConfigureAwait(false); } finally { client.Dispose(); } ``` -------------------------------- ### Start Host and Send Rebirth Command Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/sparkplug/host-application.md Initializes the host application and triggers a rebirth command for a specific node. ```csharp await host.StartAsync(); await host.PublishRebirthCommandAsync("myGroup", "myNode"); ``` -------------------------------- ### Configure LWT properties Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/last_will_and_testament.md Examples of setting various properties on a LastWillAndTestament instance. ```csharp string Topic { get; set; } lwt.Topic = "status/update"; ``` ```csharp byte[]? Payload { get; set; } lwt.Payload = Encoding.UTF8.GetBytes("Disconnected"); ``` ```csharp string PayloadAsString { get; set; } lwt.PayloadAsString = "Disconnected"; ``` ```csharp QualityOfService QoS { get; set; } lwt.QoS = QualityOfService.ExactlyOnce; ``` ```csharp bool Retain { get; set; } lwt.Retain = true; ``` ```csharp long? WillDelayInterval { get; set; } lwt.WillDelayInterval = 60; // Delay of 60 seconds ``` ```csharp long? MessageExpiryInterval { get; set; } lwt.MessageExpiryInterval = 3600; // Expires in 1 hour ``` ```csharp string? ContentType { get; set; } lwt.ContentType = "text/plain"; ``` ```csharp string? ResponseTopic { get; set; } lwt.ResponseTopic = "response/topic"; ``` ```csharp byte[]? CorrelationData { get; set; } lwt.CorrelationData = Encoding.UTF8.GetBytes("correlation-id"); ``` ```csharp Dictionary UserProperties { get; set; } lwt.UserProperties["key"] = "value"; ``` -------------------------------- ### Trace Level Log Output Example Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/configure-logging.md Example of the verbose output generated when the logging level is set to Trace. ```log 2024-03-14 15:40:18.2252|TRACE|HiveMQtt.Client.HiveMQClient|Trace Level Logging Legend: 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(W)- == ConnectionWriter 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(PW)- == ConnectionPublishWriter 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(R)- == ConnectionReader 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(RPH)- == ReceivedPacketsHandler 2024-03-14 15:40:18.2320|INFO|HiveMQtt.Client.HiveMQClient|Connecting to broker at 127.0.0.1:1883 2024-03-14 15:40:18.2343|TRACE|HiveMQtt.Client.HiveMQClient|BeforeConnectEventLauncher 2024-03-14 15:40:18.2460|TRACE|HiveMQtt.Client.HiveMQClient|Socket connected to 127.0.0.1:1883 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|Queuing packet for send: HiveMQtt.MQTT5.Packets.ConnectPacket 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(RPH)- Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(R)- ConnectionReader Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|5: ConnectionMonitor Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(RPH)- 0 received packets currently waiting to be processed. 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- ConnectionWriter Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- ConnectionWriter: 1 packets waiting to be sent. 2024-03-14 15:40:18.2476|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- --> Sending ConnectPacket id=0 2024-03-14 15:40:18.2529|TRACE|HiveMQtt.Client.HiveMQClient|OnConnectSentEventLauncher 2024-03-14 15:40:18.2529|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- ConnectionWriter: 0 packets waiting to be sent. 2024-03-14 15:40:18.2732|TRACE|HiveMQtt.Client.HiveMQClient|ReadAsync: Read Buffer Length 11 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.MQTT5.PacketDecoder|PacketDecoder: Decoded Packet: consumed=11, packet=HiveMQtt.MQTT5.Packets.ConnAckPacket id=0 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.Client.HiveMQClient|-(R)- <-- Received ConnAckPacket. Adding to receivedQueue. 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.Client.HiveMQClient|-(RPH)- <-- Received ConnAck id=0 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.Client.HiveMQClient|OnConnAckReceivedEventLauncher 2024-03-14 15:40:18.2775|TRACE|HiveMQtt.Client.HiveMQClient|AfterConnectEventLauncher ``` -------------------------------- ### Install Docusaurus Dependencies Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/README.md Installs the necessary project dependencies for the Docusaurus site. ```bash $ yarn ``` -------------------------------- ### Example: FireFirstMatchingHandler Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md Demonstrates how FireFirstMatchingHandler limits execution to the first matching subscription handler when multiple patterns match a topic. ```csharp var options = new HiveMQClientOptionsBuilder() .WithOverlappingSubscriptionBehavior(OverlappingSubscriptionBehavior.FireFirstMatchingHandler) .Build(); var client = new HiveMQClient(options); // Subscribe to overlapping patterns var opts1 = new SubscribeOptions(); opts1.TopicFilters.Add(new TopicFilter("sensors/#", QualityOfService.AtLeastOnceDelivery)); opts1.Handlers["sensors/#"] = (s, e) => Console.WriteLine("Wildcard handler"); await client.SubscribeAsync(opts1); // First subscription var opts2 = new SubscribeOptions(); opts2.TopicFilters.Add(new TopicFilter("sensors/+/temperature", QualityOfService.AtLeastOnceDelivery)); opts2.Handlers["sensors/+/temperature"] = (s, e) => Console.WriteLine("Specific handler"); await client.SubscribeAsync(opts2); // Second subscription // Global handler always fires regardless of setting client.OnMessageReceived += (s, e) => Console.WriteLine("Global handler"); // Publish to sensors/livingroom/temperature // Output: // Global handler // Wildcard handler // (Specific handler does NOT fire - only first match fires) ``` -------------------------------- ### Start HiveMQ Community Edition with Docker Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/intro.md Use this command to quickly spin up a local MQTT broker instance on port 1883 for development and testing. ```bash docker run --name hivemq-ce -d -p 1883:1883 hivemq/hivemq-ce ``` -------------------------------- ### Implement Sparkplug Host Application Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/sparkplug/quickstart.md Configure and start a Sparkplug Host Application to listen for birth messages and publish rebirth commands. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-host") .Build(); var sparkplugOptions = new SparkplugHostApplicationOptions { SparkplugTopicFilter = "spBv1.0/#", UseStateMessages = false }; var host = new SparkplugHostApplication(clientOptions, sparkplugOptions); host.NodeBirthReceived += (_, e) => Console.WriteLine($"Node birth: {e.Topic.GroupId}/{e.Topic.EdgeNodeId}"); host.DeviceBirthReceived += (_, e) => Console.WriteLine($"Device birth: {e.Topic.DeviceId}"); await host.StartAsync(); await host.PublishRebirthCommandAsync("myGroup", "myNode"); ``` -------------------------------- ### Define Per-Subscription Callbacks Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/subscribing.md Shows the method signature for adding callbacks and provides examples using both lambda expressions and named methods. ```csharp public SubscribeOptionsBuilder WithSubscription(TopicFilter topicFilter, EventHandler? handler = null) ``` ```csharp var builder = new SubscribeOptionsBuilder(); var options = builder.WithSubscription( new TopicFilter("test/topic", QualityOfService.AtLeastOnceDelivery), (sender, e) => { Console.WriteLine($"Message received on topic {e.PublishMessage.Topic}: {e.PublishMessage.PayloadAsString}"); }) .Build(); ``` ```csharp private static void MessageHandler(object? sender, OnMessageReceivedEventArgs eventArgs) { Console.WriteLine($"Message Received: {eventArgs.PublishMessage.PayloadAsString}"); } var builder = new SubscribeOptionsBuilder(); var options = builder.WithSubscription( new TopicFilter("test/topic", QualityOfService.AtLeastOnceDelivery), MessageHandler) .Build(); ``` -------------------------------- ### Initialize Sparkplug Edge Node Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/sparkplug/edge-node.md Configure the client options and Sparkplug edge node options to start the edge node connection. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-edge-node") .Build(); var sparkplugOptions = new SparkplugEdgeNodeOptions { GroupId = "myGroup", EdgeNodeId = "myNode" }; var edgeNode = new SparkplugEdgeNode(clientOptions, sparkplugOptions); await edgeNode.StartAsync(); ``` -------------------------------- ### Implement Sparkplug Edge Node Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/sparkplug/quickstart.md Configure and start a Sparkplug Edge Node to handle commands and publish metrics. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-edge-node") .Build(); var sparkplugOptions = new SparkplugEdgeNodeOptions { GroupId = "myGroup", EdgeNodeId = "myNode" }; var edgeNode = new SparkplugEdgeNode(clientOptions, sparkplugOptions); edgeNode.NodeCommandReceived += (_, e) => Console.WriteLine($"NCMD: {e.Payload.Metrics.Count} metrics"); await edgeNode.StartAsync(); var metrics = new[] { SparkplugMetricBuilder.Create("temperature").WithFloatValue(22.5).Build() }; await edgeNode.PublishNodeDataAsync(metrics); ``` -------------------------------- ### Set Clean Start Flag Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options_builder.md Determines whether the connection initiates a new session or resumes an existing one. ```csharp .WithCleanStart(true) // Start with a clean session ``` -------------------------------- ### Configure and Initialize SparkplugHostApplication Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/sparkplug/host-application.md Sets up the MQTT client options and Sparkplug host application options to begin communication. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-host") .Build(); var sparkplugOptions = new SparkplugHostApplicationOptions { SparkplugTopicFilter = "spBv1.0/#", UseStateMessages = false }; var host = new SparkplugHostApplication(clientOptions, sparkplugOptions); ``` -------------------------------- ### Basic Publishing and Subscribing Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/namespaces.md Demonstrates initializing a client, connecting, subscribing to a topic, and publishing a message. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; var client = new HiveMQClient(); await client.ConnectAsync(); await client.SubscribeAsync("topic", QualityOfService.AtLeastOnceDelivery); await client.PublishAsync("topic", "Hello!"); ``` -------------------------------- ### Complete Connection Configuration Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options_builder.md Demonstrates building options and using them to connect to an MQTT broker. ```csharp var connectOptions = new ConnectOptionsBuilder() .WithSessionExpiryInterval(3600) // 1 hour session expiry .WithKeepAlive(60) // 60 second keep alive .WithCleanStart(true) // Start with a clean session .Build(); await client.ConnectAsync(connectOptions); ``` -------------------------------- ### Build and Run the Application Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Examples/HiveMQtt-CLI/README.md Commands to navigate to the project directory and execute the console application. ```bash cd Examples/HiveMQtt-CLI/HiveMQtt-CLI dotnet build dotnet run ``` -------------------------------- ### Initialize and use RawClient Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/rawclient/intro.md Demonstrates the full lifecycle of a RawClient instance including event handling, connection, subscription, and publishing. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Create a RawClient var client = new RawClient(); // Setup a global message handler BEFORE connecting client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message received on {args.PublishMessage.Topic}: {args.PublishMessage.PayloadAsString}"); }; // Connect to the broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // Subscribe to a topic (RawClient does NOT track this subscription) await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Publish a message await client.PublishAsync("my/topic", "Hello from RawClient!").ConfigureAwait(false); // Disconnect when done await client.DisconnectAsync().ConfigureAwait(false); client.Dispose(); ``` -------------------------------- ### Configure ConnectOptions for MQTT Connection Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options.md Demonstrates initializing ConnectOptions and overriding default client settings before establishing a connection. ```csharp ConnectOptions connectOptions = new ConnectOptions(); connectOptions.SessionExpiryInterval = 3600; // 1 hour session expiry connectOptions.KeepAlive = 60; // 60 second keep alive connectOptions.CleanStart = true; // Start with a clean session await client.ConnectAsync(connectOptions); ``` -------------------------------- ### Connect, Subscribe, and Publish with TCP Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/README.md Demonstrates the standard client lifecycle including broker connection, event handler registration, topic subscription, and message publishing. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Setup Client options and instantiate var options = new HiveMQClientOptionsBuilder(). WithBroker("candy.x39.eu.hivemq.cloud"). WithPort(8883). WithUseTls(true). Build(); var client = new HiveMQClient(options); // Setup application message handlers BEFORE subscribing to a topic client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message Received: {args.PublishMessage.PayloadAsString}"); }; // Connect to the MQTT broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // Configure the subscriptions we want and subscribe var builder = new SubscribeOptionsBuilder(); builder.WithSubscription("topic1", QualityOfService.AtLeastOnceDelivery) .WithSubscription("topic2", QualityOfService.ExactlyOnceDelivery); var subscribeOptions = builder.Build(); var subscribeResult = await client.SubscribeAsync(subscribeOptions); // Publish a message var publishResult = await client.PublishAsync("topic1/example", "Hello Payload"); ``` -------------------------------- ### Connect with Default Settings Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/connecting.md Establishes a connection to a local broker on localhost:1883 without additional configuration. ```csharp using HiveMQtt.Client; // Connect var client = new HiveMQClient(); var connectResult = await client.ConnectAsync().ConfigureAwait(false); ``` -------------------------------- ### Construct and Publish an MQTT5 Message Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/publishing.md Demonstrates how to instantiate an MQTT5PublishMessage, set properties like Topic, Payload, QoS, and Retain, and send it using the client. ```csharp var message = new MQTT5PublishMessage { Topic = "topic1/example", Payload = Encoding.UTF8.GetBytes("Hello, World!"), QoS = QualityOfService.AtLeastOnceDelivery, }; message.Retain = true; message.UserProperties.Add("Client-Geo", "-33.8688, 151.2093"); var result = await client.PublishAsync(message); ``` -------------------------------- ### Initialize HiveMQtt Client with Configuration Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/client-certificates.md Binds the configuration settings to the model and applies them to the HiveMQtt client options. ```csharp // Load certificate settings var certSettings = new CertificateSettings(); Configuration.GetSection("CertificateSettings").Bind(certSettings); // Use settings to initialize HiveMQtt client options var options = new HiveMQClientOptionsBuilder() .WithClientCertificate( certSettings.CertificatePath, certSettings.CertificatePassword) .Build(); var client = new HiveMQClient(options); ``` -------------------------------- ### Add Subscription with Options Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/subscribe_options_builder.md Configure a subscription with specific QoS, local delivery settings, and a message handler. ```csharp SubscribeOptionsBuilder WithSubscription( string topic, QualityOfService qos, bool? noLocal = null, bool? retainAsPublished = null, RetainHandling? retainHandling = RetainHandling.SendAtSubscribe, EventHandler? messageReceivedHandler = null ); ``` ```csharp builder.WithSubscription( "home/sensors/temperature", QualityOfService.AtLeastOnce, noLocal: true, retainAsPublished: false, retainHandling: RetainHandling.DoNotSendOnSubscribe, messageReceivedHandler: (sender, args) => { Console.WriteLine($"Received message: {args.Message.PayloadAsString}"); }); ``` -------------------------------- ### Connect with Default Options Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md Establishes a connection to localhost on port 1883 using default client settings. ```csharp using HiveMQtt.Client; var client = new HiveMQClient(); var connectResult = await client.ConnectAsync().ConfigureAwait(false); ``` -------------------------------- ### Build and Execute Subscription Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/subscribing.md Finalize the configuration and perform the subscription request using the client. ```csharp var options = builder.Build(); ``` ```csharp await client.SubscribeAsync(options); ``` -------------------------------- ### Load Configuration in Startup Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/client-certificates.md Initializes the configuration object within the application startup process. ```csharp using Microsoft.Extensions.Configuration; using System.IO; // Assuming you are in the Startup.cs or a similar setup file public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // Other configurations... } ``` -------------------------------- ### Configure Client Certificates with HiveMQClientOptionsBuilder Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/client-certificates.md Demonstrates adding client certificates using either an X509Certificate2 object or a file path. ```csharp using HiveMQtt.Client; using System.Security.Cryptography.X509Certificates; // Can pre-create a X509Certificate2 or alternatively pass a string path // to the certificate (see below) var clientCertificate = new X509Certificate2("path/to/certificate-file-1.pem"); var options = new HiveMQClientOptionsBuilder() .WithClientCertificate(clientCertificate) .WithClientCertificate("path/to/certificate-file-2.pem") .Build(); var client = new HiveMQClient(options); ``` -------------------------------- ### Build() Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options_builder.md Finalizes the configuration and returns a ConnectOptions instance. ```APIDOC ## Build() ### Description Creates and returns a new ConnectOptions object with all the configured settings. ``` -------------------------------- ### Run HiveMQtt Benchmarks Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/benchmarks.md Execute the benchmark suite from the project directory using the .NET CLI. ```bash cd Benchmarks/ClientBenchmarkApp dotnet run ClientBenchmarkApp.csproj -c Release ``` -------------------------------- ### Initialize MQTT5PublishMessage Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/publish_message.md Constructors for creating a new MQTT5PublishMessage instance. ```csharp var message = new MQTT5PublishMessage(); ``` ```csharp var message = new MQTT5PublishMessage("home/sensors/temperature", QualityOfService.AtLeastOnce); ``` -------------------------------- ### Build() Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/last_will_and_testament_builder.md Constructs the LastWillAndTestament instance and validates the configuration. ```APIDOC ## Build() ### Description Constructs the LastWillAndTestament instance and validates the configuration. ### Example ```csharp var lwt = builder .WithTopic("client/disconnect") .WithPayload("Disconnected unexpectedly") .WithQualityOfServiceLevel(QualityOfService.ExactlyOnce) .WithRetain(true) .Build(); ``` ``` -------------------------------- ### Connect with Specific Options Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md Configures client connection parameters such as broker address, port, TLS, and client ID using the builder pattern. ```csharp var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(8883) .WithUseTls(true) .WithClientId("my-client-id") .Build(); var client = new HiveMQClient(options); var connectResult = await client.ConnectAsync().ConfigureAwait(false); ``` -------------------------------- ### Connect with Username and Password in C# Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/connect-with-auth.md Establishes a secure connection to an MQTT broker using the HiveMQClientOptionsBuilder. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.ReasonCodes; var options = new HiveMQClientOptionsBuilder() .WithBroker("your-broker.hivemq.cloud") .WithPort(8883) .WithUseTls(true) .WithUserName("my-username") .WithPassword("my-password") .Build(); var client = new HiveMQClient(options); var connectResult = await client.ConnectAsync().ConfigureAwait(false); if (connectResult.ReasonCode == ConnAckReasonCode.Success) { Console.WriteLine("Connected successfully!"); } ``` -------------------------------- ### Configure Proxy with RawClient Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/configure-proxy.md Directly apply a WebProxy instance to the client options using the HiveMQClientOptionsBuilder. ```csharp using System.Net; using HiveMQtt.Client; var proxy = new WebProxy("http://proxy.example.com:8080"); var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.example.com") .WithProxy(proxy) .Build(); // Works with both HiveMQClient and RawClient var rawClient = new RawClient(options); await rawClient.ConnectAsync(); ``` -------------------------------- ### Configure Proxy via appsettings.json Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/configure-proxy.md Use the Microsoft.Extensions.Configuration library to load proxy settings from a JSON configuration file. ```json { "MqttSettings": { "Broker": "broker.example.com", "Port": 1883, "Proxy": { "Enabled": true, "Url": "http://proxy.example.com:8080", "Username": "", "Password": "" } } } ``` ```csharp using System.Net; using HiveMQtt.Client; using Microsoft.Extensions.Configuration; var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var mqttSettings = config.GetSection("MqttSettings"); var builder = new HiveMQClientOptionsBuilder() .WithBroker(mqttSettings["Broker"]) .WithPort(int.Parse(mqttSettings["Port"])); var proxySection = mqttSettings.GetSection("Proxy"); if (proxySection.GetValue("Enabled")) { var proxy = new WebProxy(proxySection["Url"]); var username = proxySection["Username"]; if (!string.IsNullOrEmpty(username)) { proxy.Credentials = new NetworkCredential( username, proxySection["Password"]); } builder.WithProxy(proxy); } var options = builder.Build(); ``` -------------------------------- ### Initialize SubscribeOptionsBuilder Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/subscribe_options_builder.md Instantiate the builder to begin configuring subscription options. ```csharp SubscribeOptionsBuilder(); ``` ```csharp var builder = new SubscribeOptionsBuilder(); ``` -------------------------------- ### Build DocFX Documentation Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/README.md Compiles the API documentation into static files using the docfx.json configuration. ```bash $ dotnet tool run docfx build ./docfx.json ``` -------------------------------- ### Setting up Message Handlers in HiveMQ MQTT Client Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/subscribing.md Demonstrates two approaches for assigning a message handler to the client before initiating the connection. ```csharp // Message Handler client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message Received: {args.PublishMessage.PayloadAsString}"); }; await client.ConnectAsync(); ``` ```csharp private static void MessageHandler(object? sender, OnMessageReceivedEventArgs eventArgs) { Console.WriteLine($"Message Received: {eventArgs.PublishMessage.PayloadAsString}"); } client.OnMessageReceived += MessageHandler; await client.ConnectAsync(); ``` -------------------------------- ### Full PublishMessageBuilder configuration Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/publishing.md Demonstrates all available configuration options for a publish message using the builder pattern. ```csharp var publishMessage = new PublishMessageBuilder() .WithTopic("topic1/example") .WithPayload("Hello, HiveMQtt!") .WithQualityOfServiceLevel(QualityOfService.AtLeastOnceDelivery) .WithRetainFlag(true) .WithPayloadFormatIndicator(MQTT5PayloadFormatIndicator.UTF8Encoded) .WithContentType("application/json") .WithResponseTopic("response/topic") .WithCorrelationData(Encoding.UTF8.GetBytes("correlation-data")) .WithUserProperty("property1", "value1") .WithUserProperties(new Dictionary { { "property1", "value1" }, { "property2", "value2" } }) .WithMessageExpiryInterval(3600) .WithSubscriptionIdentifier(123) .WithSubscriptionIdentifiers(1, 2, 3) .WithTopicAlias(456) .WithContentTypeAlias(789) .WithResponseTopicAlias(987) .Build(); ``` -------------------------------- ### Subscribe to Topics with HiveMQ Client Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md Demonstrates basic subscription methods using default or custom QoS levels and advanced subscription options. ```csharp // Subscribe with default options (QoS 0) await client.SubscribeAsync("my/topic").ConfigureAwait(false); // Subscribe with specific QoS await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Subscribe with additional options await client.SubscribeAsync( "my/topic", QualityOfService.ExactlyOnceDelivery, noLocal: true, retainAsPublished: true, retainHandling: RetainHandling.SendAtSubscribe ).ConfigureAwait(false); ``` -------------------------------- ### Build() Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/client_options_builder.md Builds the HiveMQClientOptions instance. ```APIDOC ## Build() ### Description Builds the HiveMQClientOptions instance based on the previously configured options. ``` -------------------------------- ### Configure Password-Protected Certificates with X509Certificate2 Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/client-certificates.md Manually instantiate an X509Certificate2 object with a password before adding it to the client options. ```csharp using HiveMQtt.Client; using System.Security.Cryptography.X509Certificates; var clientCertificate = new X509Certificate2( "path/to/certificate-with-password.pem", "certificate-password"); var options = new HiveMQClientOptionsBuilder() .WithClientCertificate(clientCertificate) .Build(); var client = new HiveMQClient(options); ``` -------------------------------- ### Configure Disconnect Options in C# Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/disconnect_options.md Demonstrates how to instantiate and populate DisconnectOptions to perform a controlled client disconnection. ```csharp DisconnectOptions disconnectOptions = new DisconnectOptions(); disconnectOptions.ReasonCode = DisconnectReasonCode.NormalDisconnection; disconnectOptions.SessionExpiry = 3600; disconnectOptions.ReasonString = "Device power save mode"; disconnectOptions.UserProperties = new Dictionary { { "device-id", "xrw02k-224a" }, { "TZ", "CEST" } }; await client.DisconnectAsync(disconnectOptions); ``` -------------------------------- ### Build Client Options Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/client_options_builder.md Finalizes the configuration and builds the HiveMQClientOptions instance. ```csharp HiveMQClientOptions options = new HiveMQClientOptionsBuilder().WithBroker("mqtt.example.com").WithPort(1883).Build(); ``` -------------------------------- ### Build LastWillAndTestament Instance Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/last_will_and_testament_builder.md Constructs the LastWillAndTestament instance and validates the configuration. ```csharp LastWillAndTestament Build(); ``` ```csharp var lwt = builder .WithTopic("client/disconnect") .WithPayload("Disconnected unexpectedly") .WithQualityOfServiceLevel(QualityOfService.ExactlyOnce) .WithRetain(true) .Build(); ``` -------------------------------- ### Build ConnectOptions Instance Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options_builder.md Constructs the final ConnectOptions object after applying configuration methods. ```csharp ConnectOptions options = new ConnectOptionsBuilder() .WithSessionExpiryInterval(3600) .WithKeepAlive(60) .WithCleanStart(true) .Build(); ``` -------------------------------- ### Configure NLog for TRACE Logging Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/debug.md Create an NLog.config file to route HiveMQtt logs at the Trace level to the console. ```xml ``` -------------------------------- ### MQTT5PublishMessage Constructors Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/publish_message.md Initializes a new instance of the MQTT5PublishMessage class. ```APIDOC ## Constructor: MQTT5PublishMessage() ### Description Initializes a new instance of the MQTT5PublishMessage class. ## Constructor: MQTT5PublishMessage(string topic, QualityOfService? qos) ### Description Initializes a new instance of the MQTT5PublishMessage class with the specified topic and Quality of Service level. ### Parameters - **topic** (string) - Required - The topic name. - **qos** (QualityOfService?) - Optional - The QoS level. ``` -------------------------------- ### Initialize LastWillAndTestamentBuilder Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/last_will_and_testament_builder.md Create a new instance of the builder to begin configuring a Last Will and Testament message. ```csharp LastWillAndTestamentBuilder(); ``` ```csharp var builder = new LastWillAndTestamentBuilder(); ``` -------------------------------- ### Initialize UnsubscribeOptions Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/unsubscribe_options.md Create a new instance of the UnsubscribeOptions class. ```csharp UnsubscribeOptions(); ``` ```csharp var options = new UnsubscribeOptions(); ``` -------------------------------- ### Initialize SubscribeOptions Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/subscribe_options.md Create a new instance of the SubscribeOptions class. ```csharp SubscribeOptions(); ``` ```csharp var options = new SubscribeOptions(); ``` -------------------------------- ### Configure Proxy via Environment Variables Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/configure-proxy.md Retrieve proxy URL and credentials from system environment variables to avoid hardcoding sensitive information. ```csharp using System.Net; using HiveMQtt.Client; var proxyUrl = Environment.GetEnvironmentVariable("HTTP_PROXY"); var builder = new HiveMQClientOptionsBuilder() .WithBroker("broker.example.com") .WithPort(1883); if (!string.IsNullOrEmpty(proxyUrl)) { var proxy = new WebProxy(proxyUrl); // Optional: Add credentials from environment var proxyUser = Environment.GetEnvironmentVariable("PROXY_USER"); var proxyPass = Environment.GetEnvironmentVariable("PROXY_PASS"); if (!string.IsNullOrEmpty(proxyUser)) { proxy.Credentials = new NetworkCredential(proxyUser, proxyPass); } builder.WithProxy(proxy); } var options = builder.Build(); var client = new HiveMQClient(options); ``` -------------------------------- ### Define Certificate Configuration Model Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/client-certificates.md Creates a C# class to map the certificate settings from the configuration file. ```csharp public class CertificateSettings { public string CertificatePath { get; set; } public string CertificatePassword { get; set; } } ``` -------------------------------- ### Configure X.509 Client Certificates Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/security.md Use WithClientCertificate to enable certificate-based authentication. Ensure TLS is enabled when using certificates. ```csharp using System.Security.Cryptography.X509Certificates; using HiveMQtt.Client; var options = new HiveMQClientOptionsBuilder() .WithBroker("your-broker.hivemq.cloud") .WithPort(8883) .WithUseTls(true) .WithClientCertificate("path/to/client-certificate.pem") .Build(); ``` ```csharp var options = new HiveMQClientOptionsBuilder() .WithBroker("your-broker.hivemq.cloud") .WithPort(8883) .WithUseTls(true) .WithClientCertificate("path/to/client-cert.pem") .WithClientCertificate("path/to/intermediate-ca.pem") .Build(); ``` -------------------------------- ### Build SubscribeOptions Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/subscribe_options_builder.md Finalize the configuration and generate the SubscribeOptions instance. ```csharp SubscribeOptions Build(); ``` ```csharp var options = builder .WithSubscription("home/sensors/temperature", QualityOfService.AtLeastOnce) .WithUserProperty("key", "value") .Build(); options.Validate(); ``` -------------------------------- ### Publishing messages with simple payloads Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/hivemqclient.md Demonstrates basic publish operations using string or byte array payloads with varying Quality of Service levels. ```csharp // Publish with string payload (default QoS 0) var result = await client.PublishAsync("topic/example", "Hello World!").ConfigureAwait(false); // Publish with specific QoS var result = await client.PublishAsync("topic/example", "Hello World!", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Publish with byte array payload var payload = Encoding.UTF8.GetBytes("Binary payload"); var result = await client.PublishAsync("topic/example", payload, QualityOfService.ExactlyOnceDelivery).ConfigureAwait(false); ``` -------------------------------- ### Build() Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/unsubscribe_options_builder.md Constructs the UnsubscribeOptions instance based on the provided settings. ```APIDOC ## Build() ### Description Validates the builder configuration and creates an instance of UnsubscribeOptions. ### Example ```csharp var options = builder .WithSubscription(new Subscription("home/sensors/temperature", QualityOfService.AtLeastOnce)) .WithUserProperty("reason", "No longer needed") .Build(); options.Validate(); ``` ``` -------------------------------- ### Migrate from Plain String to SecureString Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/security.md Demonstrates the obsolete warning generated by plain string overloads and the recommended SecureString replacement. ```csharp // ⚠️ This generates a compiler warning var options = new HiveMQClientOptionsBuilder() .WithPassword("plain-text-password") // CS0618: Obsolete warning .Build(); // ✅ Use SecureString instead var options = new HiveMQClientOptionsBuilder() .WithPassword(securePassword) .Build(); ``` -------------------------------- ### Build() Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/client_options_builder.md Constructs and returns a HiveMQClientOptions object based on the configured properties. ```APIDOC ## Build() ### Description Finalizes the configuration process and returns a configured HiveMQClientOptions instance. ### Method Build() ### Usage Call this method after setting desired properties on the HiveMQClientOptionsBuilder to retrieve the final options object. ``` -------------------------------- ### Build MQTT5PublishMessage Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/publish_message_builder.md Creates the final MQTT5PublishMessage instance. ```csharp MQTT5PublishMessage Build(); ``` -------------------------------- ### Configure Credentials via appsettings.json Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/connect-with-auth.md Reads MQTT configuration settings from an appsettings.json file using the .NET configuration system. ```csharp // In appsettings.json: // { // "Mqtt": { // "Broker": "your-broker.hivemq.cloud", // "Username": "your-username", // "Password": "your-password" // } // } var mqttConfig = configuration.GetSection("Mqtt"); var options = new HiveMQClientOptionsBuilder() .WithBroker(mqttConfig["Broker"]) .WithPort(8883) .WithUseTls(true) .WithUserName(mqttConfig["Username"]) .WithPassword(mqttConfig["Password"]) .Build(); ``` -------------------------------- ### Initialize LastWillAndTestament with binary payload Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/last_will_and_testament.md Constructor for creating a LWT instance using a byte array payload. ```csharp LastWillAndTestament(string topic, byte[] payload, QualityOfService qos = QualityOfService.AtMostOnceDelivery, bool retain = false); ``` ```csharp var lwt = new LastWillAndTestament("disconnect/topic", Encoding.UTF8.GetBytes("Client disconnected"), QualityOfService.ExactlyOnce, true); ``` -------------------------------- ### Deploy Docusaurus Site Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/README.md Commands for deploying the documentation site to GitHub Pages. ```bash yarn deploy ``` ```bash $ USE_SSH=true yarn deploy ``` ```bash $ GIT_USER= yarn deploy ``` -------------------------------- ### LastWillAndTestament(string topic, byte[] payload, QualityOfService qos, bool retain) Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/last_will_and_testament.md Initializes a new instance of the LastWillAndTestament class with a binary payload. ```APIDOC ## LastWillAndTestament(string topic, byte[] payload, QualityOfService qos = QualityOfService.AtMostOnceDelivery, bool retain = false) ### Description Initializes a new instance of the LastWillAndTestament class with a binary payload. ### Parameters - **topic** (string) - Required - The topic of the message. - **payload** (byte[]) - Required - The payload in binary format. - **qos** (QualityOfService) - Optional - The QoS level (default: AtMostOnceDelivery). - **retain** (bool) - Optional - Whether the message should be retained by the broker. ``` -------------------------------- ### Exception Handling Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/namespaces.md Demonstrates catching client-specific exceptions during connection attempts. ```csharp using HiveMQtt.Client; using HiveMQtt.Client.Exceptions; try { await client.ConnectAsync(); } catch (HiveMQttClientException ex) { Console.WriteLine($"Client error: {ex.Message}"); } ``` -------------------------------- ### Build() Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/publish_message_builder.md The Build method finalizes the configuration of the PublishMessageBuilder and returns a new MQTT5PublishMessage instance. ```APIDOC ## Build() ### Description Creates and returns the final `MQTT5PublishMessage` instance based on the parameters configured in the builder. ### Signature `MQTT5PublishMessage Build();` ### Example ```csharp var message = new PublishMessageBuilder() .WithTopic("home/sensors/temperature") .WithPayload("22.5°C") .Build(); ``` ``` -------------------------------- ### Configure Certificate Settings in appsettings.json Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/how-to/client-certificates.md Defines the structure for storing certificate paths and passwords in a JSON configuration file. ```json { // Other configuration settings "CertificateSettings": { "CertificatePath": "path/to/certificate-with-password.pem", "CertificatePassword": "YourSecurePassword" } } ``` -------------------------------- ### Importing Core Namespaces Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/namespaces.md Essential namespaces for most client applications, providing access to client builders and MQTT protocol types. ```csharp using HiveMQtt.Client; // Client classes and builders using HiveMQtt.MQTT5.Types; // QoS levels, topic filters, etc. ``` -------------------------------- ### ConnectOptions Class Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/connect_options.md Configuration options for the ConnectAsync method. ```APIDOC ## ConnectOptions ### Description The `ConnectOptions` class provides options for a connect call made with `ConnectAsync`. These options can override settings that were originally set in `HiveMQClientOptions`. ### Constructors - `ConnectOptions()`: Initializes a new instance of the `ConnectOptions` class with defaults. ### Properties - **SessionExpiryInterval** (long) - Gets or sets the session expiry interval in seconds. - **KeepAlive** (int) - Gets or sets the keep alive period in seconds. - **CleanStart** (bool) - Gets or sets whether to use a clean start. ### Usage Example ```csharp ConnectOptions connectOptions = new ConnectOptions(); connectOptions.SessionExpiryInterval = 3600; connectOptions.KeepAlive = 60; connectOptions.CleanStart = true; await client.ConnectAsync(connectOptions); ``` ``` -------------------------------- ### Initialize UnsubscribeOptionsBuilder Source: https://github.com/hivemq/hivemq-mqtt-client-dotnet/blob/main/Documentation/docs/hivemqtt/reference/unsubscribe_options_builder.md Instantiate a new builder object. ```csharp UnsubscribeOptionsBuilder(); ``` ```csharp var builder = new UnsubscribeOptionsBuilder(); ```