Skip to content

Commit

Permalink
Merge pull request #225 from WildernessLabs/feature/PinDefinitionBase
Browse files Browse the repository at this point in the history
pushed common code to PinDefinitionBase
  • Loading branch information
adrianstevens committed May 1, 2024
2 parents 95964a9 + 52d6e3e commit d599279
Showing 1 changed file with 54 additions and 3 deletions.
57 changes: 54 additions & 3 deletions Source/Meadow.Contracts/Hardware/PinDefinitionBase.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Meadow.Hardware;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Meadow;

Expand All @@ -9,14 +10,64 @@ namespace Meadow;
/// </summary>
public abstract class PinDefinitionBase : IPinDefinitions
{
private readonly List<IPin> _pins = new();
private List<IPin>? _pins;

/// <inheritdoc/>
public IList<IPin> AllPins => _pins;
public virtual IList<IPin> AllPins
{
// lazy load
get => _pins ??= DiscoverAllPinsViaReflection();
}

/// <inheritdoc/>
public IPinController? Controller { get; set; }

/// <summary>
/// Retrieves a pin from <see cref="AllPins"/> by Name or Key
/// </summary>
public IPin this[string name]
{
get => AllPins.FirstOrDefault(p =>
string.Compare(p.Name, name, true) == 0
|| string.Compare($"{p.Key}", name, true) == 0)
?? throw new KeyNotFoundException();
}

/// <summary>
/// Creates a PinDefinitionBase
/// </summary>
protected PinDefinitionBase()
{
}

/// <summary>
/// Uses reflection to discover all IPin properties
/// </summary>
private List<IPin> DiscoverAllPinsViaReflection()
{
var list = new List<IPin>();

foreach (var prop in this.GetType()
.GetProperties(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public)
.Where(p => p.CanRead && p.GetIndexParameters().Length == 0 && p.PropertyType == typeof(IPin))
)
{
var pin = prop.GetValue(this) as IPin;

if (pin != null)
{
if (!list.Any(p => p.Name == pin.Name))
{
list.Add(pin);
}
}
}
return list;
}

/// <inheritdoc/>
public IEnumerator<IPin> GetEnumerator() => _pins.GetEnumerator();
public IEnumerator<IPin> GetEnumerator() => AllPins.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

0 comments on commit d599279

Please sign in to comment.