Skip to content

Commit

Permalink
added error trapping and logging
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmyeao committed Jul 14, 2024
1 parent 1c52183 commit 5cf7537
Show file tree
Hide file tree
Showing 7 changed files with 264 additions and 140 deletions.
6 changes: 3 additions & 3 deletions API/MeetingState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class MeetingState
public bool IsRecordingOn { get; set; }
public bool IsSharing { get; set; }
public bool IsVideoOn { get; set; }
public bool teamsRunning { get; set; }
public bool TeamsRunning { get; set; }

#endregion Public Properties
}
Expand All @@ -45,8 +45,8 @@ public class MeetingUpdate
{
#region Public Properties

public MeetingPermissions MeetingPermissions { get; set; }
public MeetingState MeetingState { get; set; }
public MeetingPermissions? MeetingPermissions { get; set; }
public MeetingState? MeetingState { get; set; }

#endregion Public Properties
}
Expand Down
40 changes: 30 additions & 10 deletions API/MqttService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public void Initialize(AppSettings settings, string deviceId, List<string> senso

_sensorNames = sensorNames;
_isInitialized = true;
//_mqttClient.ApplicationMessageReceivedAsync += OnMessageReceivedAsync;


}
else
{
Expand Down Expand Up @@ -108,7 +107,7 @@ private MqttService()
await Task.CompletedTask;
};
Log.Information("MQTT client created.");
// _mqttClient.ApplicationMessageReceivedAsync += OnMessageReceivedAsync;


}
public async Task SubscribeToReactionButtonsAsync()
Expand Down Expand Up @@ -164,7 +163,14 @@ private Task OnMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e) /
string reactionPayloadJson = JsonConvert.SerializeObject(reactionPayload);

// Invoke the command to send the reaction to Teams
CommandToTeams?.Invoke(reactionPayloadJson);
try
{
CommandToTeams?.Invoke(reactionPayloadJson);
}
catch (Exception ex)
{
Log.Error($"Error sending reaction to Teams: {ex.Message}");
}
}
}

Expand Down Expand Up @@ -218,7 +224,14 @@ private void HandleSwitchCommand(string topic, string command)
if (!string.IsNullOrEmpty(jsonMessage))
{
// Raise the event
CommandToTeams?.Invoke(jsonMessage);
try
{
CommandToTeams?.Invoke(jsonMessage);
}
catch (Exception ex)
{
Log.Error($"Error sending command to Teams: {ex.Message}");
}
}
}
public async Task ConnectAsync(AppSettings settings)
Expand Down Expand Up @@ -333,7 +346,14 @@ public async Task PublishReactionButtonsAsync()
.Build();
if (_mqttClient.IsConnected)
{
await PublishAsync(message);
try
{
await PublishAsync(message);
}
catch (Exception ex)
{
Log.Error($"Error publishing reaction button configuration: {ex.Message}");
}
}

}
Expand Down Expand Up @@ -499,7 +519,7 @@ public async Task PublishConfigurations(MeetingUpdate meetingUpdate, AppSettings
IsBackgroundBlurred = false,
IsSharing = false,
HasUnreadMessages = false,
teamsRunning = IsTeamsRunning()
TeamsRunning = IsTeamsRunning()
}
};
}
Expand Down Expand Up @@ -662,7 +682,7 @@ private string GetStateValue(string sensor, MeetingUpdate meetingUpdate)
// Similar casting for these properties
return (bool)meetingUpdate.MeetingState.GetType().GetProperty(sensor).GetValue(meetingUpdate.MeetingState, null) ? "True" : "False";

case "teamsRunning":
case "TeamsRunning":
return (bool)meetingUpdate.MeetingState.GetType().GetProperty(sensor).GetValue(meetingUpdate.MeetingState, null) ? "True" : "False";

default:
Expand All @@ -682,7 +702,7 @@ private string DetermineDeviceClass(string sensor)
case "HasUnreadMessages":
case "IsRecordingOn":
case "IsSharing":
case "teamsRunning":
case "TeamsRunning":
return "binary_sensor"; // These are true/false sensors
default:
return "unknown"; // Or a default device class if appropriate
Expand All @@ -703,7 +723,7 @@ public async Task SetupMqttSensors()
IsBackgroundBlurred = false,
IsSharing = false,
HasUnreadMessages = false,
teamsRunning = false
TeamsRunning = false
}
};

Expand Down
2 changes: 1 addition & 1 deletion API/State.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public string Status
}
}

public bool teamsRunning { get; set; }
public bool TeamsRunning { get; set; }
public bool CanToggleMute { get; set; }
public bool CanToggleVideo { get; set; }
public bool CanToggleHand { get; set; }
Expand Down
59 changes: 42 additions & 17 deletions API/WebSocketManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public async Task ConnectAsync(Uri uri)
}
catch (Exception ex)
{
Log.Error("Failed to connect: " + ex.Message);
Log.Error("Failed to connect to Teams: " + ex.Message);
SetIsConnected(false);
}
finally
Expand All @@ -92,7 +92,7 @@ private void SetIsConnected(bool value)
if (_isConnected != value)
{
_isConnected = value;
State.Instance.teamsRunning = value; //update the MQTT state
State.Instance.TeamsRunning = value; //update the MQTT state

ConnectionStatusChanged?.Invoke(IsConnected); //update the UI
}
Expand All @@ -105,8 +105,12 @@ public async Task PairWithTeamsAsync(Action<string> updateTokenCallback)
_pairingResponseTaskSource = new TaskCompletionSource<string>();

string pairingCommand = "{\"action\":\"pair\",\"parameters\":{},\"requestId\":1}";
await SendMessageAsync(pairingCommand);

try
{
await SendMessageAsync(pairingCommand);
} catch (Exception ex) {
Log.Error("Error sending pairing command: " + ex.Message);
}
var responseTask = await Task.WhenAny(_pairingResponseTaskSource.Task, Task.Delay(TimeSpan.FromSeconds(30)));

if (responseTask == _pairingResponseTaskSource.Task)
Expand Down Expand Up @@ -174,16 +178,29 @@ public async Task SendMessageAsync(string message, CancellationToken cancellatio
Log.Warning("WebSocket is not connected. Message not sent.");
return;
}

byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await _clientWebSocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, cancellationToken);
Log.Debug($"Message Sent: {message}");
try
{
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await _clientWebSocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, cancellationToken);
Log.Debug($"Message Sent: {message}");
}
catch (Exception ex)
{
Log.Error("Error sending message from websocket manager: " + ex.Message);
}
}
public async Task EnsureConnectedAsync()
{
if (_clientWebSocket.State != WebSocketState.Open)
{
await ConnectAsync(_currentUri);
Log.Information("Reconnecting to Teams...");
try
{
await ConnectAsync(_currentUri);
} catch (Exception ex)
{
Log.Error("Error reconnecting to Teams: " + ex.Message);
}
}
}
public async Task SendReactionToTeamsAsync(string reactionType)
Expand Down Expand Up @@ -333,7 +350,7 @@ private void OnMessageReceived(object sender, string message)
meetingState["isRecordingOn"] = meetingUpdate.MeetingState.IsRecordingOn;
meetingState["isBackgroundBlurred"] = meetingUpdate.MeetingState.IsBackgroundBlurred;
meetingState["isSharing"] = meetingUpdate.MeetingState.IsSharing;
meetingUpdate.MeetingState.teamsRunning = IsConnected;
meetingUpdate.MeetingState.TeamsRunning = IsConnected;
if (meetingUpdate.MeetingState.IsVideoOn)
{
State.Instance.Camera = "On";
Expand All @@ -342,13 +359,13 @@ private void OnMessageReceived(object sender, string message)
{
State.Instance.Camera = "Off";
}
if (meetingUpdate.MeetingState.teamsRunning)
if (meetingUpdate.MeetingState.TeamsRunning)
{
State.Instance.teamsRunning = true;
State.Instance.TeamsRunning = true;
}
else
{
State.Instance.teamsRunning = false;
State.Instance.TeamsRunning = false;
}
if (meetingUpdate.MeetingState.IsInMeeting)
{
Expand Down Expand Up @@ -404,23 +421,31 @@ private void OnMessageReceived(object sender, string message)
}
try
{
Log.Information("Meeting State Updated: {meetingState}", meetingState);
TeamsUpdateReceived?.Invoke(this, new TeamsUpdateEventArgs { MeetingUpdate = meetingUpdate });
}
catch (Exception ex)
{
Log.Error(ex, "Error in TeamsUpdateReceived");
}
Log.Debug($"Meeting State Updated: {meetingState}");

}
}
}
public async Task DisconnectAsync()
{
if (_clientWebSocket.State == WebSocketState.Open)
{
await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client disconnect", CancellationToken.None);
SetIsConnected(false);
Log.Information("Disconnected from server.");
try
{
await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client disconnect", CancellationToken.None);
SetIsConnected(false);
Log.Information("Disconnected from server.");
}
catch (Exception ex)
{
Log.Error("Error disconnecting from server: " + ex.Message);
}
}
}
}
Expand Down
38 changes: 30 additions & 8 deletions App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Serilog; // Ensure Serilog is configured properly in the project

namespace TEAMS2HA
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private static Mutex mutex = null;
Expand All @@ -31,7 +24,36 @@ protected override void OnStartup(StartupEventArgs e)
return;
}

// Configure logging here if not already configured
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File("logs\\TEAMS2HA_.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

// Handle unhandled exceptions
this.DispatcherUnhandledException += App_DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

base.OnStartup(e);
}

private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
Log.Error($"Unhandled exception caught on dispatcher thread: {e.Exception}");
// Optionally, prevent application exit
e.Handled = true;
}

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Log.Error($"Unhandled exception caught on current domain: {e.ExceptionObject}");
}

protected override void OnExit(ExitEventArgs e)
{
Log.CloseAndFlush(); // Ensure all logs are flushed properly
mutex?.ReleaseMutex(); // Release the mutex when application is exiting
base.OnExit(e);
}
}
}
Loading

0 comments on commit 5cf7537

Please sign in to comment.