Skip to content

Commit

Permalink
Prevent batch flood
Browse files Browse the repository at this point in the history
  • Loading branch information
aritchie committed Jun 11, 2024
1 parent 4b211b2 commit c6abb6b
Showing 1 changed file with 39 additions and 33 deletions.
72 changes: 39 additions & 33 deletions src/Shiny.Locations/GpsDelegate.cs
Original file line number Diff line number Diff line change
@@ -1,57 +1,63 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Shiny.Locations;


public abstract class GpsDelegate : NotifyPropertyChanged, IGpsDelegate
public abstract class GpsDelegate(ILogger logger) : NotifyPropertyChanged, IGpsDelegate
{

public GpsDelegate(ILogger logger) => this.Logger = logger;


protected ILogger Logger { get; }
readonly SemaphoreSlim semaphore = new(1);
protected ILogger Logger => logger;


public async Task OnReading(GpsReading reading)
{
var fireReading = false;

if (this.LastReading == null)
{
fireReading = true;
this.Logger.LogDebug("No previous reading");
}
else
try
{
if (this.MinimumDistance != null)
{
var dist = this.LastReading.Position.GetDistanceTo(reading.Position);
fireReading = dist >= this.MinimumDistance;
await this.semaphore.WaitAsync().ConfigureAwait(false);

this.Logger.DeferDistanceInfo(this.MinimumDistance!.TotalMeters, dist.TotalMeters, fireReading);
var fireReading = false;
if (this.LastReading == null)
{
fireReading = true;
this.Logger.LogDebug("No previous reading");
}

if (!fireReading && this.MinimumTime != null)
else
{
var timeDiff = reading.Timestamp.Subtract(this.LastReading.Timestamp);
fireReading = timeDiff >= this.MinimumTime;
if (this.MinimumDistance != null)
{
var dist = this.LastReading.Position.GetDistanceTo(reading.Position);
fireReading = dist >= this.MinimumDistance;

this.Logger.DeferTimeInfo(this.MinimumTime!.Value, timeDiff, fireReading);
this.Logger.DeferDistanceInfo(this.MinimumDistance!.TotalMeters, dist.TotalMeters, fireReading);
}

if (!fireReading && this.MinimumTime != null)
{
var timeDiff = reading.Timestamp.Subtract(this.LastReading.Timestamp);
fireReading = timeDiff >= this.MinimumTime;

this.Logger.DeferTimeInfo(this.MinimumTime!.Value, timeDiff, fireReading);
}
}
}

if (fireReading)
{
try
if (fireReading)
{
await this.OnGpsReading(reading).ConfigureAwait(false);
try
{
await this.OnGpsReading(reading).ConfigureAwait(false);
}
finally
{
this.LastReading = reading;
}
}
finally
{
this.LastReading = reading;
}
}
finally
{
this.semaphore.Release();
}
}

Expand Down

0 comments on commit c6abb6b

Please sign in to comment.