From 1a21db1b078112c520d50acdefeda7a3aa075460 Mon Sep 17 00:00:00 2001 From: Jimmy White Date: Tue, 16 Jul 2024 17:54:40 +0100 Subject: [PATCH] Enhanced MQTT logging and client ID generation - Enhanced logging for MQTT disconnections in MqttService.cs to include disconnection reasons and exception messages, with explicit error logging for exceptions. - Implemented dynamic MQTT client ID generation using the machine name (TEAMS2HA_{Environment.MachineName}) and increased the keep-alive period from 30 to 60 seconds for improved connection stability. - Updated the project file version in TEAMS2HA.csproj from 1.1.0.773 to 1.1.0.776, indicating a new release. --- API/MqttService.cs | 12 ++++++++---- TEAMS2HA.csproj | 4 ++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/API/MqttService.cs b/API/MqttService.cs index 38da3b0..7c99211 100644 --- a/API/MqttService.cs +++ b/API/MqttService.cs @@ -101,7 +101,11 @@ private MqttService() _mqttClient.DisconnectedAsync += async e => { - Log.Information("Disconnected from MQTT broker."); + Log.Information($"Disconnected from MQTT broker. Reason: {e.Reason} | Exception: {e.Exception?.Message}"); + if (e.Exception != null) + { + Log.Error($"Exception during disconnect: {e.Exception}"); + } _mqttClient.ApplicationMessageReceivedAsync -= OnMessageReceivedAsync; await Task.CompletedTask; @@ -246,10 +250,10 @@ public async Task ConnectAsync(AppSettings settings) await _mqttClient.StopAsync(); Log.Information("Existing MQTT client stopped successfully."); } - + string uniqueClientId = $"TEAMS2HA_{Environment.MachineName}"; var mqttClientOptionsBuilder = new MqttClientOptionsBuilder() - .WithClientId("TEAMS2HA") - .WithKeepAlivePeriod(TimeSpan.FromSeconds(30)) + .WithClientId(uniqueClientId) + .WithKeepAlivePeriod(TimeSpan.FromSeconds(60)) .WithCleanSession(true) .WithCredentials(settings.MqttUsername, settings.MqttPassword); if (settings.UseWebsockets && !settings.UseTLS) diff --git a/TEAMS2HA.csproj b/TEAMS2HA.csproj index 16e79fd..0d79a4b 100644 --- a/TEAMS2HA.csproj +++ b/TEAMS2HA.csproj @@ -5,8 +5,8 @@ net8.0-windows7.0 enable true - 1.1.0.773 - 1.1.0.773 + 1.1.0.776 + 1.1.0.776 Assets\Square150x150Logo.scale-200.ico Teams2HA Square150x150Logo.scale-200.png