Skip to content

Commit

Permalink
Merge pull request #11 from theyo/feature/5/fix-timer-drift
Browse files Browse the repository at this point in the history
Fixes timer drift and updates readme
  • Loading branch information
theyo authored May 31, 2023
2 parents 79bf13d + 9f2ecab commit c601436
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 81 deletions.
120 changes: 48 additions & 72 deletions AuraScheduler.Worker/AuraScheduleWorker.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Drawing;
using System.Threading.Tasks;

using AuraScheduler.Worker.Aura;

Expand All @@ -13,15 +14,21 @@ public class AuraScheduleWorker : BackgroundService

private readonly AuraHelper _auraHelper;

private double _countDownForDriftCheck = 0;
private double _countDown = 0;
private readonly IDisposable? _settingsChangeEvent;

private readonly TimeSpan _defaultTimeSpan = TimeSpan.FromSeconds(1);

private readonly CancellationTokenSource _timerCTS = new();

private readonly PeriodicTimer _timer;

public AuraScheduleWorker(ILogger<AuraScheduleWorker> logger, IOptionsMonitor<LightOptions> optionsMonitor)
{
_logger = logger;
_lightOptionsMonitor = optionsMonitor;
_timer = new PeriodicTimer(_defaultTimeSpan);

_lightOptionsMonitor.OnChange(SettingsChanged);
_settingsChangeEvent = _lightOptionsMonitor.OnChange(UpdateLightsAndSetTimer);

_auraHelper = new AuraHelper();
}
Expand All @@ -30,53 +37,19 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Worker starting...");

CheckAndSetLights();

_countDown = _lightOptionsMonitor.CurrentValue.SecondsUntilNextScheduledTime(TimeOnly.FromDateTime(DateTime.Now));

await Task.Delay(1000, stoppingToken);

try
{
CheckAndSetLights(_lightOptionsMonitor.CurrentValue);

_logger.LogInformation("Worker running!");

while (!stoppingToken.IsCancellationRequested)
while (!stoppingToken.IsCancellationRequested && await _timer.WaitForNextTickAsync(_timerCTS.Token))
{
_logger.LogDebug("Checking reset countdown...");

if (_countDownForDriftCheck-- <= 0)
if (_lightOptionsMonitor.CurrentValue.ScheduleEnabled)
{
_logger.LogDebug("Updating reset countdown...");

UpdateCountdown();

_logger.LogDebug("Reset countdown updated!");
CheckAndSetLights(_lightOptionsMonitor.CurrentValue);
}

_logger.LogDebug("Finished checking rest countdown!");


if (_lightOptionsMonitor.CurrentValue.ScheduleEnabled && _countDown-- <= 0)
{
_logger.LogDebug("Schedule Enabled and countdown time has passed, checking and setting lights...");

CheckAndSetLights();

_logger.LogDebug("Done checking and setting lights!");

_logger.LogDebug("Updating countdown to next scheduled time...");

UpdateCountdown();

_logger.LogDebug("Countdown updated!");

}

_logger.LogDebug("Nothing more to do, waiting...");

await Task.Delay(1000, stoppingToken);
}

}
catch (TaskCanceledException)
{
Expand Down Expand Up @@ -104,57 +77,60 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
_logger.LogInformation("Worker shutting down, releasing control");

_auraHelper.ReleaseControl();
}


_settingsChangeEvent?.Dispose();
}
}

private void CheckAndSetLights()
private void CheckAndSetLights(LightOptions options)
{
var now = TimeOnly.FromDateTime(DateTime.Now);

if (!_lightOptionsMonitor.CurrentValue.ShouldLightsBeOn(now))
{
if (!_auraHelper.HasControl)
{
_logger.LogInformation("Lights should be off, taking control");
var lightsShouldBeOn = options.ShouldLightsBeOn(now);

_auraHelper.TakeControl();
}
_logger.LogDebug("Lights should be {lightStatus}...", lightsShouldBeOn ? "ON" : "OFF");

_logger.LogDebug("Setting color to: {color}", Color.Black);
if (lightsShouldBeOn)
{
if (_auraHelper.HasControl)
{
_logger.LogInformation("Lights should be on, releasing control");

_auraHelper.SetLightsToColor(Color.Black);
_auraHelper.ReleaseControl();

_logger.LogDebug("Color set to: {color}", Color.Black);
_logger.LogDebug("Control released");
}
else
{
_logger.LogDebug("Lights are already on, nothing to do");
}
}
else
{
_logger.LogInformation("Lights should be on, releasing control");
if (!_auraHelper.HasControl)
{
_logger.LogInformation("Lights should be off, taking control");

_auraHelper.ReleaseControl();
_auraHelper.TakeControl();

_logger.LogDebug("Control released");
}
}
_logger.LogDebug("Setting color to: {color}", Color.Black);

private void SettingsChanged(LightOptions options)
{
_logger.LogInformation("Settings changed, updating lights");
_auraHelper.SetLightsToColor(Color.Black);

if (_lightOptionsMonitor.CurrentValue.ScheduleEnabled)
{
UpdateCountdown();
_logger.LogDebug("New Countdown: {countdown}", _countDown);
_logger.LogDebug("Color set to: {color}", Color.Black);
}
else
{
_logger.LogDebug("Lights are already off, nothing to do");
}
}

CheckAndSetLights();
}

private void UpdateCountdown()
private void UpdateLightsAndSetTimer(LightOptions options)
{
_countDown = _lightOptionsMonitor.CurrentValue.SecondsUntilNextScheduledTime(TimeOnly.FromDateTime(DateTime.Now));
_countDownForDriftCheck = 5;
_logger.LogInformation("Settings changed, updating lights");

CheckAndSetLights(options);
}
}
}
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<Company>TheYo</Company>
<Product>AURA Scheduler</Product>
<Copyright>Copyright © 2023</Copyright>
<VersionSuffix>0.0.1</VersionSuffix>
<VersionSuffix>0.0.2</VersionSuffix>
<AssemblyVersion>$(VersionSuffix)</AssemblyVersion>
<Version>$(VersionSuffix)</Version>
<BuildVersion>$(VersionSuffix)</BuildVersion>
Expand Down
3 changes: 2 additions & 1 deletion InstallerSandboxStart.cmd
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ start appwiz.cpl
start services.msc
start "" "C:\source\Setup\bin\x64\Release\en-US"
start "" "C:\Program Files"
start "" "C:\Users\WDAGUtilityAccount\AppData\Local"
start "" "C:\Users\WDAGUtilityAccount\AppData\Local"
start "" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
24 changes: 18 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@ Uses the Asus AURA SDK to turn LEDs on/off on a schedule
The Asus AURA SDK `Interop.AuraServiceLib.dll` needs to be present on the system. Normally this dll is installed with ASUS AURA (through ARMOURY CRATE).

# Instructions
1. Run `AURAScheduler.Setup.msi` to install
1. Set your preferred configuration in the `LightOptions` section of the `LightSetting.json` file located in `C:\ProgramData\TheYo\AURA Scheduler`. The configuration can be changed on-the-fly while the app is running.
1. Run `AURAScheduler.Setup.msi` to install, the application will be added to startup and begin running
1. AURA Scheduler will minimize to the system tray.

a. To open the application, double-click the icon in teh system tray or right-click on the icon and choose "Show"
a. To exit the application, right-click on the icon in the system tray and choose "Exit"

# Settings File
You may backup or set your preferred configuration manually in the `LightOptions` section of the `LightSetting.json` file located in `%LOCALAPPDATA%\TheYo\AURA Scheduler`. The configuration can be changed on-the-fly while the app is running.

`LightMode`: `On`, `Off`, or `Schedule`

Expand All @@ -33,23 +39,29 @@ Default Settings:
}
```

# To test AURA Scheduler
1. Run the `AuraScheduler.Worker` project
1. Change the configuration in the `LightOptions` section of the `appsettings.json` file. The configuration can be changed on-the-fly while the app is running
# To test the AURA Scheduler project
1. Run the `AuraScheduler.UI` project
1. Set the configuration in the UI and verify the configuration saved in the `LightOptions` section of the `appsettings.json` file. The configuration can be changed on-the-fly while the app is running

# To test the Setup project
Prerequisites:
1. Ensure the Windows Sandbox feature is installed on your maching (press Start and search for `Turn Windows features on or off`)
1. Edit `InstallerSandbox.wsb`

a. Update the `HostFolder` node with the correct path to the output of the Setup project on your machine

Test the installer
1. Build the Setup project
1. Run `InstallerSandbox.wsb`, Windows Sandbox will start and a few windows will open:

a. File Explorer open to c:\Program Files
a. File Explorer open to c:\ProgramData
a. File Explorer open to the folder with the output from the Setup project
a. Add/Remove Programs
a. Services
1. Run the `AURAScheduler.Setup.msi` and verify that the installation succeeded (service may not start due to missing AURA SDK in the sanbox

1. Run the `AURAScheduler.Setup.msi` and verify that the installation succeeded

a. The application will start, and an error message will be logged due to the worker being unable to start because the `Interop.AuraServiceLib.dll` is not available in the sandbox

1. Uninstall AURA Scheduler and verify that everything is cleaned up properly
2 changes: 1 addition & 1 deletion Setup/Package.wxs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs">
<Package Name="AURA Scheduler" Manufacturer="TheYo" Version="$(Version)" UpgradeCode="264899C9-951A-4545-9D88-DAB9E2E95FC8" Scope="perUserOrMachine">
<Package Name="AURA Scheduler" Manufacturer="TheYo" Version="$(Version)" UpgradeCode="264899C9-951A-4545-9D88-DAB9E2E95FC8" Scope="perMachine">
<MajorUpgrade DowngradeErrorMessage="!(loc.DowngradeError)" />

<Property Id="ARPPRODUCTICON" Value="uiapp.exe" />
Expand Down

0 comments on commit c601436

Please sign in to comment.