1 year ago
#156046
John
Close Connection Message MQTTNet C#
I am using the MQTTNet library for the MQTT connection in my application. I am using Mosquitto Broker as a MQTT broker. My app is in .Net core 3.1.
I am having requirement to send the MQTT message to device when the app is connected, normal disconnected and unexpected disconnected.
For the connected scenario, I am using the UseConnectedHandler
extension method of the IMQTTClient
.
mqttClient.UseConnectedHandler((MqttClientConnectedEventArgs e) =>
{
// Console.WriteLine("MqttClient - Connected");
// Publish the Connect Message
});
For the unexpected disconnect scenario I am using the WithWillMessage
feature.
var mqttOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithWillMessage(_options.LastWillMessage)
.WithCleanSession()
.WithClientId(_options.DevcommMqttClientId)
.WithProtocolVersion(MqttProtocolVersion.V500)
.WithCommunicationTimeout(TimeSpan.FromSeconds(30))
.WithCredentials(_options.DevcommMqttUsername ?? string.Empty, _options.DevcommMqttPassword ?? string.Empty)
.WithTcpServer(_options.DevcommMqttHost, _options.DevcommMqttPort)
.WithTls(o =>
{
o.UseTls = _options.DevcommUseTls;
o.AllowUntrustedCertificates = _options.DevcommTlsAllowUntrustedCertificates;
o.IgnoreCertificateChainErrors = _options.DevcommTlsIgnoreCertificateChainErrors;
o.IgnoreCertificateRevocationErrors = _options.DevcommTlsIgnoreCertificateRevocationErrors;
o.SslProtocol = ParseSslProtocols(_options.DevcommTlsProtocols);
o.Certificates = _options.DevcommTlsClientCertificates.AsEnumerable();
o.CertificateValidationHandler = CertificateValidationHandler;
})
.Build())
.Build();
I am now stuck at graceful disconnect scenario. The UseDisconnectedHandler
extension method is being called after the disconnect and not before disconnect.
Mosquitto broker is providing the feature of close message, which is similar of before disconnect event.
Is there anyway that using MQTTNet I can send the before disconnect message?
c#
mqtt
mqttnet
0 Answers
Your Answer