Skip to content

Commit

Permalink
Merge pull request #26 from jimmyeao/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
jimmyeao authored Feb 15, 2024
2 parents 7c5cea6 + e7eada4 commit a8110c1
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 77 deletions.
50 changes: 35 additions & 15 deletions API/MqttClientWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Runtime.ConstrainedExecution;
using System.Windows.Controls;
using System.Security.Authentication;
using System.Threading;

namespace TEAMS2HA.API
{
Expand All @@ -21,58 +26,65 @@ public class MqttClientWrapper
private const int RetryDelayMilliseconds = 2000; //wait a couple of seconds before retrying a connection attempt

#endregion Private Fields
public event Action<string> ConnectionStatusChanged;

#region Public Constructors
public bool IsAttemptingConnection
{
get { return _isAttemptingConnection; }
private set { _isAttemptingConnection = value; }
}
public MqttClientWrapper(string clientId, string mqttBroker, string mqttPort, string username, string password, bool useTls = false)
public MqttClientWrapper(string clientId, string mqttBroker, string mqttPort, string username, string password, bool UseTLS, bool IgnoreCertificateErrors)

{
var factory = new MqttFactory();
_mqttClient = factory.CreateMqttClient() as MqttClient;

int mqttportInt = System.Convert.ToInt32(mqttPort);
int mqttportInt;
int.TryParse(mqttPort, out mqttportInt);
if (mqttportInt == 0) mqttportInt = 1883;

var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
.WithClientId(clientId)
.WithCredentials(username, password)
.WithCleanSession();

// If useTls is true or the port is 8883, configure the client to use TLS.
if (useTls || mqttportInt == 8883)
if (UseTLS || mqttportInt == 8883)
{
var untrusted = IgnoreCertificateErrors;
// Configure TLS options
mqttClientOptionsBuilder.WithTcpServer(mqttBroker, mqttportInt)

.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
AllowUntrustedCertificates = true,
IgnoreCertificateChainErrors = true,
IgnoreCertificateRevocationErrors = true
AllowUntrustedCertificates = untrusted,
IgnoreCertificateChainErrors = untrusted,
IgnoreCertificateRevocationErrors = untrusted
});


Log.Information($"MQTT Client Created with TLS on port {mqttPort}.");
ConnectionStatusChanged?.Invoke($"MQTT Client Created with TLS");

}
else
{
mqttClientOptionsBuilder.WithTcpServer(mqttBroker, mqttportInt);
Log.Information("MQTT Client Created with TCP.");
ConnectionStatusChanged?.Invoke($"MQTT Client Created with TCP");
}

_mqttOptions = mqttClientOptionsBuilder.Build();
_mqttClient.ApplicationMessageReceivedAsync += OnMessageReceivedAsync;
if (_mqttClient != null)
{
_mqttClient.ApplicationMessageReceivedAsync += OnMessageReceivedAsync;
}

}


public MqttClientWrapper(/* parameters */)
{
// Existing initialization code...

_mqttClient.ApplicationMessageReceivedAsync += HandleReceivedApplicationMessage;
Log.Information("MQTT Client Created");
}

#endregion Public Constructors

#region Public Events
Expand All @@ -94,6 +106,7 @@ public async Task ConnectAsync()
if (_mqttClient.IsConnected || _isAttemptingConnection)
{
Log.Information("MQTT client is already connected or connection attempt is in progress.");

return;
}

Expand All @@ -107,11 +120,15 @@ public async Task ConnectAsync()
Log.Information($"Attempting to connect to MQTT (Attempt {retryCount + 1}/{MaxConnectionRetries})");
await _mqttClient.ConnectAsync(_mqttOptions);
Log.Information("Connected to MQTT broker.");
if (_mqttClient.IsConnected)
ConnectionStatusChanged?.Invoke("MQTT Status: Connected");

break;
}
catch (Exception ex)
{
Log.Debug($"Failed to connect to MQTT broker: {ex.Message}");
ConnectionStatusChanged?.Invoke($"MQTT Status: Disconnected (Retry {retryCount + 1}) {ex.Message}");
retryCount++;
await Task.Delay(RetryDelayMilliseconds);
}
Expand All @@ -120,6 +137,7 @@ public async Task ConnectAsync()
_isAttemptingConnection = false;
if (!_mqttClient.IsConnected)
{
ConnectionStatusChanged?.Invoke("MQTT Status: Disconnected (Failed to connect)");
Log.Error("Failed to connect to MQTT broker after several attempts.");
}
}
Expand All @@ -129,13 +147,15 @@ public async Task DisconnectAsync()
if (!_mqttClient.IsConnected)
{
Log.Debug("MQTTClient is not connected");
ConnectionStatusChanged?.Invoke("MQTTClient is not connected");
return;
}

try
{
await _mqttClient.DisconnectAsync();
Log.Information("MQTT Disconnected");
ConnectionStatusChanged?.Invoke("MQTTClient is not connected");
}
catch (Exception ex)
{
Expand Down
2 changes: 2 additions & 0 deletions MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@
<StackPanel Grid.Row="3" Margin="0,10,0,0" Orientation="Horizontal">
<TextBlock Text="MQTT Username:" Width="200" VerticalAlignment="Center"/>
<TextBox x:Name="MqttUserNameBox" Width="300" Margin="10,0,0,0" Style="{DynamicResource MaterialDesignTextBox}"/>
<CheckBox x:Name="UseTLS" Content="TLS?" RenderTransformOrigin="0.832,0.636" Margin="10,0,0,0"/>
<CheckBox x:Name="IgnoreCert" Content="Ignore Cert Errors?" Margin="10,0,0,0"/>

</StackPanel>
<StackPanel Grid.Row="4" Margin="0,10,0,0" Orientation="Horizontal">
Expand Down
Loading

0 comments on commit a8110c1

Please sign in to comment.