Skip to content

Commit

Permalink
Merge pull request #15 from jimmyeao/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
jimmyeao authored Dec 18, 2023
2 parents 0c3e92e + 15e5b59 commit b46d415
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 26 deletions.
41 changes: 31 additions & 10 deletions API/MqttClientWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,18 @@ public class MqttClientWrapper

private MqttClient _mqttClient;
private MqttClientOptions _mqttOptions;
private bool _isAttemptingConnection = false;
private const int MaxConnectionRetries = 5;
private const int RetryDelayMilliseconds = 2000; //wait a couple of seconds before retrying a connection attempt

#endregion Private Fields

#region Public Constructors

public bool IsAttemptingConnection
{
get { return _isAttemptingConnection; }
private set { _isAttemptingConnection = value; }
}
public MqttClientWrapper(string clientId, string mqttBroker, string username, string password)
{
var factory = new MqttFactory();
Expand Down Expand Up @@ -62,22 +69,36 @@ public MqttClientWrapper(/* parameters */)

public async Task ConnectAsync()
{
if (_mqttClient.IsConnected)
if (_mqttClient.IsConnected || _isAttemptingConnection)
{
Log.Information("MQTT client is already connected.");
Log.Information("MQTT client is already connected or connection attempt is in progress.");
return;
}

try
{
Log.Information("attempting to connect to mqtt");
await _mqttClient.ConnectAsync(_mqttOptions);
_isAttemptingConnection = true;
int retryCount = 0;

Log.Information("Connected to MQTT broker.");
while (retryCount < MaxConnectionRetries && !_mqttClient.IsConnected)
{
try
{
Log.Information($"Attempting to connect to MQTT (Attempt {retryCount + 1}/{MaxConnectionRetries})");
await _mqttClient.ConnectAsync(_mqttOptions);
Log.Information("Connected to MQTT broker.");
break;
}
catch (Exception ex)
{
Log.Debug($"Failed to connect to MQTT broker: {ex.Message}");
retryCount++;
await Task.Delay(RetryDelayMilliseconds);
}
}
catch (Exception ex)

_isAttemptingConnection = false;
if (!_mqttClient.IsConnected)
{
Log.Debug($"Failed to connect to MQTT broker: {ex.Message}");
Log.Error("Failed to connect to MQTT broker after several attempts.");
}
}

Expand Down
29 changes: 15 additions & 14 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,6 @@ private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
}
private async void ReestablishConnections()
{
// Logic to re-establish MQTT and WebSocket connections
try
{
if (!mqttClientWrapper.IsConnected)
Expand All @@ -429,6 +428,7 @@ private async void ReestablishConnections()
Log.Error($"Error re-establishing connections: {ex.Message}");
}
}

private void CreateNotifyIconContextMenu()
{
ContextMenu contextMenu = new ContextMenu();
Expand Down Expand Up @@ -536,23 +536,24 @@ private void ApplyTheme(string theme)

private async void CheckMqttConnection()
{
if (mqttClientWrapper != null && !mqttClientWrapper.IsConnected)
if (mqttClientWrapper != null && !mqttClientWrapper.IsConnected && !mqttClientWrapper.IsAttemptingConnection)
{
Log.Debug("CheckMqttConnection: MQTT Client Not Connected");
try
{
await mqttClientWrapper.ConnectAsync();
Dispatcher.Invoke(() => MQTTConnectionStatus.Text = "MQTT Status: Connected");
Log.Debug("CheckMqttConnection: MQTT Client Connected");
}
catch
{
Dispatcher.Invoke(() => MQTTConnectionStatus.Text = "MQTT Status: Disconnected");
Log.Debug("CheckMqttConnection: MQTT Client Failed to Connect");
}
Log.Debug("CheckMqttConnection: MQTT Client Not Connected. Attempting reconnection.");
await mqttClientWrapper.ConnectAsync();
UpdateConnectionStatus();
}
}

private void UpdateConnectionStatus()
{
Dispatcher.Invoke(() =>
{
MQTTConnectionStatus.Text = mqttClientWrapper.IsConnected ? "MQTT Status: Connected" : "MQTT Status: Disconnected";
UpdateStatusMenuItems();
});
}


private string DetermineDeviceClass(string sensor)
{
switch (sensor)
Expand Down
4 changes: 2 additions & 2 deletions TEAMS2HA.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<TargetFramework>net7.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<AssemblyVersion>1.1.0.228</AssemblyVersion>
<FileVersion>1.1.0.228</FileVersion>
<AssemblyVersion>1.1.0.231</AssemblyVersion>
<FileVersion>1.1.0.231</FileVersion>
<ApplicationIcon>Assets\Square150x150Logo.scale-200.ico</ApplicationIcon>
<Title>Teams2HA</Title>
<PackageIcon>Square150x150Logo.scale-200.png</PackageIcon>
Expand Down

0 comments on commit b46d415

Please sign in to comment.