Skip to content

Commit

Permalink
Merge pull request #62 from jimmyeao/dev-refactor
Browse files Browse the repository at this point in the history
Dev refactor
  • Loading branch information
jimmyeao authored Jun 4, 2024
2 parents 3f2cc2d + 572c04f commit 4ee9ae3
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 7 deletions.
26 changes: 21 additions & 5 deletions API/WebSocketManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
Expand All @@ -24,6 +25,7 @@ public class WebSocketManager
private readonly Action<string> _updateTokenAction;
public event EventHandler<TeamsUpdateEventArgs> TeamsUpdateReceived;
public event EventHandler<string> MessageReceived;
public event Action<bool> ConnectionStatusChanged;
private TaskCompletionSource<string> _pairingResponseTaskSource;
private Dictionary<string, object> meetingState = new Dictionary<string, object>()
{
Expand All @@ -35,6 +37,7 @@ public class WebSocketManager
{ "isBackgroundBlurred", false },
};
public static WebSocketManager Instance => _instance.Value;



private WebSocketManager()
Expand Down Expand Up @@ -71,19 +74,29 @@ public async Task ConnectAsync(Uri uri)

_currentUri = uri;
await _clientWebSocket.ConnectAsync(uri, CancellationToken.None);
_isConnected = true;
SetIsConnected(true);
StartReceiving();
}
catch (Exception ex)
{
Log.Error("Failed to connect: " + ex.Message);
_isConnected = false;
SetIsConnected(false);
}
finally
{
_isConnecting = false;
}
}
private void SetIsConnected(bool value)
{
if (_isConnected != value)
{
_isConnected = value;
State.Instance.teamsRunning = value; //update the MQTT state

ConnectionStatusChanged?.Invoke(IsConnected); //update the UI
}
}

public async Task PairWithTeamsAsync(Action<string> updateTokenCallback)
{
Expand Down Expand Up @@ -131,7 +144,8 @@ private async void StartReceiving()
if (result.MessageType == WebSocketMessageType.Close)
{
await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
_isConnected = false;
SetIsConnected(false);

Log.Information("WebSocket closed.");
}
else
Expand All @@ -148,7 +162,9 @@ private async void StartReceiving()
catch (Exception ex)
{
Log.Error("Error in receiving loop: " + ex.Message);
_isConnected = false;
SetIsConnected(false);


}
}
public async Task SendMessageAsync(string message, CancellationToken cancellationToken = default)
Expand Down Expand Up @@ -403,7 +419,7 @@ public async Task DisconnectAsync()
if (_clientWebSocket.State == WebSocketState.Open)
{
await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client disconnect", CancellationToken.None);
_isConnected = false;
SetIsConnected(false);
Log.Information("Disconnected from server.");
}
}
Expand Down
42 changes: 42 additions & 0 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,31 @@ public async Task InitializeConnections()
Dispatcher.Invoke(() => UpdateStatusMenuItems());

}
public bool IsTeamsConnected
{
get { return isTeamsConnected; }
set
{
if (isTeamsConnected != value)
{
isTeamsConnected = value;


if (isTeamsConnected)
{
TeamsConnectionStatusChanged(isTeamsConnected);
_ = _mqttService.PublishConfigurations(null!, _settings);
Console.WriteLine("Teams is now connected");
}
else
{
TeamsConnectionStatusChanged(isTeamsConnected);
_= _mqttService.PublishConfigurations(null!, _settings);
Console.WriteLine("Teams is now disconnected");
}
}
}
}
private async void InitializeWebSocket()
{
var uri = new Uri($"ws://localhost:8124?token={_settings.PlainTeamsToken}&protocol-version=2.0.0&manufacturer=JimmyWhite&device=PC&app=THFHA&app-version=2.0.26");
Expand All @@ -357,6 +382,17 @@ await WebSocketManager.Instance.PairWithTeamsAsync(newToken =>
});
await WebSocketManager.Instance.ConnectAsync(uri);
WebSocketManager.Instance.TeamsUpdateReceived += TeamsClient_TeamsUpdateReceived;


WebSocketManager.Instance.ConnectionStatusChanged += (isConnected) =>
{
// Because this event handler might be called from a non-UI thread,
// use Dispatcher.Invoke to ensure that the UI update runs on the UI thread:
Dispatcher.Invoke(() => TeamsConnectionStatusChanged(isConnected));
};



Dispatcher.Invoke(() => UpdateStatusMenuItems());
}
private void MainWindow_StateChanged(object sender, EventArgs e)
Expand Down Expand Up @@ -815,8 +851,14 @@ private void TeamsConnectionStatusChanged(bool isConnected)
{
TeamsConnectionStatus.Text = isConnected ? "Teams: Connected" : "Teams: Disconnected";
_teamsStatusMenuItem.Header = "Teams Status: " + (isConnected ? "Connected" : "Disconnected");
if (_latestMeetingUpdate != null && _latestMeetingUpdate.MeetingState != null)
{
_latestMeetingUpdate.MeetingState.teamsRunning = isConnected;
}
_ = _mqttService.PublishConfigurations(_latestMeetingUpdate, _settings);
});
}


private async void TestTeamsConnection_Click(object sender, RoutedEventArgs e)
{
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.738</AssemblyVersion>
<FileVersion>1.1.0.738</FileVersion>
<AssemblyVersion>1.1.0.751</AssemblyVersion>
<FileVersion>1.1.0.751</FileVersion>
<ApplicationIcon>Assets\Square150x150Logo.scale-200.ico</ApplicationIcon>
<Title>Teams2HA</Title>
<PackageIcon>Square150x150Logo.scale-200.png</PackageIcon>
Expand Down

0 comments on commit 4ee9ae3

Please sign in to comment.