Last active
January 8, 2023 05:18
-
-
Save adrianstevens/33452d648bd76bbd284213cf194f352d to your computer and use it in GitHub Desktop.
MicroGraphics with update governing and frame rate limiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Meadow.Foundation.Graphics.Buffers; | |
using System; | |
using System.Threading.Tasks; | |
namespace Meadow.Foundation.Graphics | |
{ | |
/// <summary> | |
/// Feature extended version of MicroGraphics | |
/// </summary> | |
public class MicroGraphicsEx : MicroGraphics | |
{ | |
/// <summary> | |
/// Minimum time between updates | |
/// </summary> | |
public TimeSpan MinimumTimeBetweenFrames { get; set; } = TimeSpan.FromMilliseconds(250); | |
object _lock = new object(); | |
bool isUpdating = false; | |
bool isUpdateRequested = false; | |
DateTime lastUpdated; | |
public MicroGraphicsEx(IGraphicsDisplay display) : | |
base(display) | |
{ } | |
public MicroGraphicsEx(PixelBufferBase pixelBuffer, bool initializeBuffer) : | |
base(pixelBuffer, initializeBuffer) | |
{ } | |
/// <summary> | |
/// Request an update to the Display | |
/// </summary> | |
/// <returns></returns> | |
public async Task UpdateDisplay() | |
{ | |
lock (_lock) | |
{ | |
if (isUpdating) | |
{ | |
isUpdateRequested = true; | |
return; | |
} | |
} | |
isUpdating = true; | |
var timeSinceLastUpdate = DateTime.Now - lastUpdated; | |
if(timeSinceLastUpdate < MinimumTimeBetweenFrames) | |
{ | |
await Task.Delay(MinimumTimeBetweenFrames - timeSinceLastUpdate); | |
} | |
base.Show(); | |
lastUpdated = DateTime.Now; | |
if (isUpdateRequested) | |
{ | |
isUpdateRequested = false; | |
await Task.Delay(MinimumTimeBetweenFrames); | |
await UpdateDisplay(); | |
} | |
isUpdating = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment