Skip to content

Commit

Permalink
Merge pull request #867 from WildernessLabs/bug/relay
Browse files Browse the repository at this point in the history
Updated relay to use open/closed semantics
  • Loading branch information
adrianstevens authored Dec 20, 2023
2 parents 49bf560 + e9de355 commit 61ea208
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Meadow;
using Meadow.Devices;
using Meadow.Foundation.Relays;
using Meadow.Peripherals.Relays;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -23,14 +24,16 @@ public override Task Initialize()

public override Task Run()
{
var state = false;

while (true)
{
state = !state;

Resolver.Log.Info($"- State: {state}");
relay.IsOn = state;
var newState = relay.State switch
{
RelayState.Open => RelayState.Closed,
_ => RelayState.Open
};

Resolver.Log.Info($"- State: {newState}");
relay.State = newState;

Thread.Sleep(500);
}
Expand Down
30 changes: 20 additions & 10 deletions Source/Meadow.Foundation.Core/Relays/Relay.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ namespace Meadow.Foundation.Relays
/// </summary>
public class Relay : IRelay
{
private RelayState _state;
private readonly bool _closedValue = true;

/// <inheritdoc/>
public event EventHandler<bool> OnRelayChanged = default!;
public event EventHandler<RelayState> OnChanged = default!;

/// <summary>
/// Returns digital output port
Expand All @@ -25,18 +28,21 @@ public class Relay : IRelay
/// <summary>
/// Whether or not the relay is on. Setting this property will turn it on or off.
/// </summary>
public bool IsOn
public RelayState State
{
get => isOn;
get => _state;
set
{
isOn = value;
DigitalOut.State = isOn ? onValue : !onValue;
OnRelayChanged?.Invoke(this, isOn);
_state = value;
DigitalOut.State = State switch
{
RelayState.Open => !_closedValue,
_ => _closedValue
};

OnChanged?.Invoke(this, State);
}
}
bool isOn = false;
readonly bool onValue = true;

/// <summary>
/// Creates a new Relay on an IDigitalOutputPort.
Expand All @@ -58,7 +64,7 @@ public Relay(IDigitalOutputPort port, RelayType type = RelayType.NormallyOpen)
{
// if it's normally closed, we have to invert the "on" value
Type = type;
onValue = Type != RelayType.NormallyClosed;
_closedValue = Type != RelayType.NormallyClosed;

DigitalOut = port;
}
Expand All @@ -68,7 +74,11 @@ public Relay(IDigitalOutputPort port, RelayType type = RelayType.NormallyOpen)
/// </summary>
public void Toggle()
{
IsOn = !IsOn;
State = State switch
{
RelayState.Open => RelayState.Closed,
_ => RelayState.Open,
};
}
}
}

0 comments on commit 61ea208

Please sign in to comment.