Skip to content

Commit

Permalink
update form correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmyeao committed Dec 10, 2023
1 parent 424df1f commit 0a42cdf
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 19 deletions.
30 changes: 23 additions & 7 deletions API/Teams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Windows.Threading;
using System.Windows;


namespace TEAMS2HA.API
{
Expand All @@ -18,18 +22,19 @@ public class WebSocketClient
private readonly State _state;
private readonly string _settingsFilePath;
private bool _isConnected;


private readonly Action<string> _updateTokenAction;
#endregion Private Fields

#region Public Constructors

public WebSocketClient(Uri uri, State state, string settingsFilePath)
public WebSocketClient(Uri uri, State state, string settingsFilePath, Action<string> updateTokenAction)
{
_clientWebSocket = new ClientWebSocket();
_state = state;
_settingsFilePath = settingsFilePath;
_appSettings = LoadAppSettings(settingsFilePath);

Task.Run(() => ConnectAsync(uri));

// Subscribe to the MessageReceived event
Expand Down Expand Up @@ -137,12 +142,20 @@ private void SaveAppSettings(AppSettings settings)
}
private void OnMessageReceived(object sender, string message)
{

if (message.Contains("tokenRefresh")) // Adjust based on the actual message format

Debug.WriteLine($"Message received: {message}"); // Add this line

if (message.Contains("tokenRefresh"))
{
var tokenUpdate = JsonConvert.DeserializeObject<TokenUpdate>(message);
_appSettings.TeamsToken = tokenUpdate.NewToken;
SaveAppSettings(_appSettings);

// Update the UI on the main thread
Application.Current.Dispatcher.Invoke(() =>
{
_updateTokenAction?.Invoke(_appSettings.TeamsToken);
});
}
// Update the Message property of the State class
var settings = new JsonSerializerSettings
Expand Down Expand Up @@ -237,12 +250,15 @@ private async Task PairWithTeamsAsync()
{
if (_isConnected)
{
string pairingCommand = "{\"action\":\"pair\",\"parameters\":{},\"requestId\":1}"; // Construct the pairing command as per API documentation
string pairingCommand = "{\"action\":\"pair\",\"parameters\":{},\"requestId\":1}";
await SendMessageAsync(pairingCommand);
// You might also want to handle the response to this pairing command

// Handle the response here
// For example: Check if the response contains a success message or token
}
}


private async Task ReceiveLoopAsync(CancellationToken cancellationToken = default)
{
const int bufferSize = 4096; // Starting buffer size
Expand Down
60 changes: 48 additions & 12 deletions MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
Expand Down Expand Up @@ -34,7 +35,7 @@ public partial class MainWindow : Window
private bool isDarkTheme = false;
private string _settingsFilePath;
private AppSettings _settings;

private FileSystemWatcher _settingsWatcher;
#endregion Private Fields

#region Public Constructors
Expand All @@ -53,6 +54,7 @@ public MainWindow()
string iconPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Square150x150Logo.scale-200.ico");
MyNotifyIcon.Icon = new System.Drawing.Icon(iconPath);
InitializeConnections();
InitializeSettingsWatcher();
}

#endregion Public Constructors
Expand Down Expand Up @@ -83,15 +85,43 @@ private async Task initializeteamsconnection()
//var uri = new Uri("ws://localhost:8124?protocol-version=2.0.0&manufacturer=JimmyWhite&device=PC&app=THFHA&app-version=2.0.26");
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");
var state = new API.State(); // You would initialize this as necessary
_teamsClient = new API.WebSocketClient(uri, state, _settingsFilePath);
_teamsClient = new API.WebSocketClient(uri, state, _settingsFilePath, token => this.Dispatcher.Invoke(() => TeamsApiKeyBox.Text = token));


_teamsClient.ConnectionStatusChanged += TeamsConnectionStatusChanged;
}

#endregion Public Methods

#region Private Methods
private void InitializeSettingsWatcher()
{
_settingsWatcher = new FileSystemWatcher
{
Path = Path.GetDirectoryName(_settingsFilePath),
Filter = Path.GetFileName(_settingsFilePath),
NotifyFilter = NotifyFilters.LastWrite
};

_settingsWatcher.Changed += OnSettingsChanged;
_settingsWatcher.EnableRaisingEvents = true;
}

private void OnSettingsChanged(object sender, FileSystemEventArgs e)
{
// Reload settings and update UI
Dispatcher.Invoke(() =>
{
_settings = LoadSettings();
UpdateUI();
});
}
private void UpdateUI()
{
// Update UI elements based on _settings
TeamsApiKeyBox.Text = _settings.TeamsToken;
// ... other UI updates
}
private AppSettings LoadSettings()
{
if (File.Exists(_settingsFilePath))
Expand Down Expand Up @@ -136,6 +166,7 @@ private void MyNotifyIcon_Click(object sender, EventArgs e)
protected override void OnClosing(CancelEventArgs e)
{
MyNotifyIcon.Dispose();
_settingsWatcher?.Dispose();
base.OnClosing(e);
}

Expand Down Expand Up @@ -253,20 +284,25 @@ private async void TestHomeassistantConnection_Click(object sender, RoutedEventA
// This method is called when the TestTeamsConnection button is clicked
private void TestTeamsConnection_Click(object sender, RoutedEventArgs e)
{
string teamsToken = _settings.TeamsToken; // Get the Teams token from the settings

// Create a URI with the necessary parameters for the WebSocket connection
try
{
InitializeWebSocketClient();
Debug.WriteLine("WebSocket client initialized");
}
catch (Exception ex)
{
Debug.WriteLine($"Error initializing WebSocket client: {ex.Message}");
}
}
private void InitializeWebSocketClient()
{
string teamsToken = _settings.TeamsToken;
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");

_teamsClient = new API.WebSocketClient(uri, new API.State(), _settingsFilePath, token => this.Dispatcher.Invoke(() => TeamsApiKeyBox.Text = token));

var state = new API.State(); // You would initialize this as necessary

// Create a new WebSocketClient with the URI, state, and settings file path
_teamsClient = new API.WebSocketClient(uri, state, _settingsFilePath);

// Subscribe to the ConnectionStatusChanged event of the WebSocketClient
_teamsClient.ConnectionStatusChanged += TeamsConnectionStatusChanged;
}

private void ApplyTheme(string theme)
{
isDarkTheme = theme == "Dark";
Expand Down

0 comments on commit 0a42cdf

Please sign in to comment.