Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Last Will Not Working #2151

Open
Rob-Hamilton opened this issue Feb 7, 2025 · 0 comments
Open

Last Will Not Working #2151

Rob-Hamilton opened this issue Feb 7, 2025 · 0 comments
Labels
question It is a question regarding the project

Comments

@Rob-Hamilton
Copy link

Describe your question

I am unable to get the Last Will and Testament working. Any help or guidance would be greatly appreciated.

Which project is your question related to?

  • Client

For my test I am using:

  • Mosquito Broker Port 1883.
  • MQTT Explorer to watch the topic messages.
  • Visual Studio C# with Frameworks v4.8
  • MQTTnet.4.3.7.1207

I modified this example

  • I placed the example code in a Windows Form in a button click event.
  • I commented out the unsubscribe & disconnect code.
  • Ran the test project and used Task Manager to Kill it.
  • MQTT Explorer does not seem to get the LWT.

Image

CODE:

using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Formatter;
using MQTTnet.Protocol;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void Button1_Click(object sender, EventArgs e)
        {
            var broker = "LocalHost";
            var port = 1883;
            var clientId = Guid.NewGuid().ToString();
            var topic = "csharp/mqtt";

            // Create a MQTT client factory
            var factory = new MqttFactory();

            // Create a MQTT client instance
            IMqttClient mqttClient = factory.CreateMqttClient();

            // Create MQTT client options
            MqttClientOptions options = new MqttClientOptionsBuilder()
                .WithTcpServer(broker, port) // MQTT broker address and port
                .WithClientId(clientId)
                .WithCleanSession()

                .WithKeepAlivePeriod(new TimeSpan(0, 0, 30))
                .WithProtocolVersion(MqttProtocolVersion.V500)
                .WithCleanSession(true)

                .WithWillPayload("My Last Will")
                .WithWillQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
                .WithWillResponseTopic("csharp/LW")
                .WithWillRetain(true)

                .Build();

            // Connect to MQTT broker
            MqttClientConnectResult connectResult = await mqttClient.ConnectAsync(options);

            if (connectResult.ResultCode == MqttClientConnectResultCode.Success)
            {
                Console.WriteLine("Connected to MQTT broker successfully.");

                // Subscribe to a topic
                await mqttClient.SubscribeAsync(topic);

                // Callback function when a message is received
                mqttClient.ApplicationMessageReceivedAsync += ee =>
                {
                    //Console.WriteLine($"Received message: {Encoding.UTF8.GetString(ee.ApplicationMessage.PayloadSegment)}");
                    return Task.CompletedTask;
                };

                // Publish a message 10 times
                for (var i = 0; i < 100; i++)
                {
                    MqttApplicationMessage message = new MqttApplicationMessageBuilder()
                        .WithTopic(topic)
                        .WithPayload($"Hello, MQTT! Message number {i}")
                        .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                        .WithRetainFlag()
                        .Build();

                    await mqttClient.PublishAsync(message);
                    await Task.Delay(1000); // Wait for 1 second
                }

                //// Unsubscribe and disconnect
                //await mqttClient.UnsubscribeAsync(topic);
                //await mqttClient.DisconnectAsync();
            }
            else
            {
                Console.WriteLine($"Failed to connect to MQTT broker: {connectResult.ResultCode}");
            }

        }

    }
}
@Rob-Hamilton Rob-Hamilton added the question It is a question regarding the project label Feb 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question It is a question regarding the project
Projects
None yet
Development

No branches or pull requests

1 participant