Skip to content

Commit

Permalink
Merge pull request #50 from jimmyeao/dev-refactor
Browse files Browse the repository at this point in the history
Dev refactor
  • Loading branch information
jimmyeao authored Mar 27, 2024
2 parents eb781b3 + cfa45d8 commit 91c4412
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 21 deletions.
9 changes: 6 additions & 3 deletions API/MqttService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class MqttService

private const int MaxConnectionRetries = 2;
private const int RetryDelayMilliseconds = 1000;
private readonly string _deviceId;
private string _deviceId;
private bool _isAttemptingConnection = false;
private MqttClient _mqttClient;
private bool _mqttClientsubscribed = false;
Expand Down Expand Up @@ -286,6 +286,8 @@ public async Task PublishConfigurations(MeetingUpdate meetingUpdate, AppSettings
if (forcePublish || !_previousSensorStates.TryGetValue(sensorKey, out var previousState) || previousState != stateValue)

{
Log.Information($"Force Publishing configuration for {sensorName} with state {stateValue}.");

_previousSensorStates[sensorKey] = stateValue; // Update the stored state
if(forcePublish)
{
Expand All @@ -311,7 +313,7 @@ public async Task PublishConfigurations(MeetingUpdate meetingUpdate, AppSettings
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.WithRetainFlag(true)
.Build();

Log.Information($"Publishing configuration for {sensorName} with state {stateValue}.");
await PublishAsync(switchConfigMessage);

var stateMessage = new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -342,7 +344,7 @@ public async Task PublishConfigurations(MeetingUpdate meetingUpdate, AppSettings
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.WithRetainFlag(true)
.Build();

Log.Information($"Publishing configuration for {sensorName} with state {stateValue}.");
await PublishAsync(binarySensorConfigMessage);

var binarySensorStateMessage = new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -426,6 +428,7 @@ public void UpdateConnectionStatus(string status) //could be obsolete
public async Task UpdateSettingsAsync(AppSettings newSettings)
{
_settings = newSettings;
_deviceId = _settings.SensorPrefix;
InitializeClientOptions(); // Reinitialize MQTT client options

if (IsConnected)
Expand Down
44 changes: 28 additions & 16 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ private void AboutMenuItem_Click(object sender, RoutedEventArgs e)
aboutWindow.ShowDialog();
}


private void ApplyTheme(string theme)
{
isDarkTheme = theme == "Dark";
Expand Down Expand Up @@ -467,17 +468,6 @@ private bool CheckIfSensorPrefixChanged(AppSettings newSettings)
return newSettings.SensorPrefix != currentSettings.SensorPrefix;
}

//private async void CheckMqttConnection() //could be obsolete
//{
// if (_mqttService != null && !_mqttService.IsConnected && !_mqttService.IsAttemptingConnection)
// {
// Log.Debug("CheckMqttConnection: MQTT Client Not Connected. Attempting reconnection.");
// await _mqttService.ConnectAsync();
// await _mqttService.SubscribeAsync("homeassistant/switch/+/set", MqttQualityOfServiceLevel.AtLeastOnce);
// _mqttService.UpdateConnectionStatus("Connected");
// UpdateStatusMenuItems();
// }
//}

private void CreateNotifyIconContextMenu()
{
Expand Down Expand Up @@ -531,7 +521,16 @@ private async Task HandleCommandToTeams(string jsonMessage)
await _teamsClient.SendMessageAsync(jsonMessage);
}
}

private async void CheckTeamsConnectionStatus()
{
if (!_teamsClient.IsConnected)
{
string teamsToken = _settings.PlainTeamsToken;
var uri = new Uri($"ws://localhost:8124?token={teamsToken}&protocol-version=2.0.0&manufacturer=JimmyWhite&device=PC&app=THFHA&app-version=2.0.26");
Log.Debug("Teams appears to be disconnected. Attempting to reconnect...");
await _teamsClient.StartConnectionAsync(uri);
}
}
private async Task initializeteamsconnection()
{
string teamsToken = _settings.PlainTeamsToken;
Expand Down Expand Up @@ -723,18 +722,29 @@ private void MyNotifyIcon_Click(object sender, EventArgs e)
}
}

private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
private async void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume)
{
Log.Information("System is waking up from sleep. Re-establishing connections...");
// Add a delay to allow the network to come up
await Task.Delay(TimeSpan.FromSeconds(10)); // Adjust based on your needs

// Implement logic to re-establish connections
ReestablishConnections();
await ReestablishConnections();
// publish current meeting state
await _mqttService.PublishConfigurations(_latestMeetingUpdate, _settings);
CheckTeamsConnectionStatus();
_teamsClient.ConnectionStatusChanged -= TeamsConnectionStatusChanged;
_teamsClient.ConnectionStatusChanged += TeamsConnectionStatusChanged;
}
}


private async void ReestablishConnections()
private async

Task
ReestablishConnections()
{
try
{
Expand All @@ -750,6 +760,8 @@ private async void ReestablishConnections()
await initializeteamsconnection();
Dispatcher.Invoke(() => UpdateStatusMenuItems());
}
// Force publish all sensor states after reconnection
await _mqttService.PublishConfigurations(_latestMeetingUpdate, _settings, forcePublish: true);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -813,7 +825,7 @@ private async Task SaveSettingsAsync()
// Save the updated settings to file
settings.SaveSettingsToFile();

if (mqttSettingsChanged)
if (mqttSettingsChanged || sensorPrefixChanged)
{
// Perform actions if MQTT settings have changed
Log.Debug("SaveSettingsAsync: MQTT settings have changed. Reconnecting MQTT client...");
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.501</AssemblyVersion>
<FileVersion>1.1.0.501</FileVersion>
<AssemblyVersion>1.1.0.507</AssemblyVersion>
<FileVersion>1.1.0.507</FileVersion>
<ApplicationIcon>Assets\Square150x150Logo.scale-200.ico</ApplicationIcon>
<Title>Teams2HA</Title>
<PackageIcon>Square150x150Logo.scale-200.png</PackageIcon>
Expand Down

0 comments on commit 91c4412

Please sign in to comment.