Skip to content

Commit

Permalink
feat: auto reconnect (#606)
Browse files Browse the repository at this point in the history
Adapted from PR #568.

Closes #605
  • Loading branch information
andrew-codes authored Oct 29, 2024
2 parents 79a3fc1 + 170727d commit e1b976c
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions apps/PlayniteWebPlugin/src/PlayniteWeb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public class PlayniteWeb : GenericPlugin
private readonly ILogger logger = LogManager.GetLogger();
private readonly Regex pcExpression = new Regex("Windows.*");
private readonly string _version;
private bool IsReconnectInProgress = false;
private bool IsShutDownInProgress = false;

public override Guid Id { get; } = Guid.Parse("ec3439e3-51ee-43cb-9a8a-5d82cf45edac");

Expand Down Expand Up @@ -260,6 +262,7 @@ public override void OnGameUninstalled(OnGameUninstalledEventArgs args)

public override void OnApplicationStopped(OnApplicationStoppedEventArgs args)
{
IsShutDownInProgress = true;
publisher.StartDisconnect().ContinueWith(t =>
{
publisher.ConnectedAsync -= HandlePublisherConnected;
Expand Down Expand Up @@ -351,6 +354,10 @@ public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
private async Task HandlePublisherDisconnecting()
{
await publisher.PublishStringAsync(topicManager.GetPublishTopic(PublishTopics.Connection()), serializer.Serialize(new Connection(_version, ConnectionState.offline)), MqttQualityOfServiceLevel.ExactlyOnce, retain: false, cancellationToken: default);
if (!IsShutDownInProgress)
{
await AttemptReconnect();
}
}

private void Subscriber_OnUninstallRelease(object sender, Release e)
Expand Down Expand Up @@ -520,6 +527,44 @@ public override UserControl GetSettingsView(bool firstRunSettings)
public override IEnumerable<MainMenuItem> GetMainMenuItems(GetMainMenuItemsArgs args)
{
return mainMenuItems.AsEnumerable();
}

private async Task AttemptReconnect()
{
int retryCount = 0;
const int maxDelayInMinutes = 60;

if (IsReconnectInProgress)
{
return;
}

IsReconnectInProgress = true;

while (!publisher.IsConnected)
{
try
{
retryCount++;
int delayInSeconds = (int)Math.Min(Math.Pow(2, retryCount), maxDelayInMinutes * 60);

logger.Info($"Attempting to reconnect... (Attempt {retryCount}, waiting {delayInSeconds} seconds)");
await Task.Delay(TimeSpan.FromSeconds(delayInSeconds));

StartConnection(settings.Settings);

if (publisher.IsConnected)
{
logger.Info("Reconnected to MQTT server.");
}
}
catch (Exception ex)
{
logger.Error(ex, "Reconnection attempt failed.");
}
}

IsReconnectInProgress = false;
}
}
}

0 comments on commit e1b976c

Please sign in to comment.