|
| 1 | +using CommunityToolkit.Diagnostics; |
| 2 | +using UnitsNet; |
| 3 | +using WPIMath.Filter; |
| 4 | +using WPIUtil; |
| 5 | +using WPIUtil.Atomic; |
| 6 | + |
| 7 | +namespace WPILib.Event; |
| 8 | + |
| 9 | +public class BooleanEvent |
| 10 | +{ |
| 11 | + protected EventLoop Loop { get; } |
| 12 | + |
| 13 | + private readonly Func<bool> m_signal; |
| 14 | + private readonly AtomicBool m_state = new(false); |
| 15 | + |
| 16 | + public BooleanEvent(EventLoop loop, Func<bool> signal) |
| 17 | + { |
| 18 | + Loop = WpiGuard.RequireNotNull(loop); |
| 19 | + m_signal = WpiGuard.RequireNotNull(signal); |
| 20 | + m_state.Set(m_signal()); |
| 21 | + loop.Bind(() => m_state.Set(m_signal())); |
| 22 | + } |
| 23 | + |
| 24 | + public bool Get() |
| 25 | + { |
| 26 | + return m_state.Get(); |
| 27 | + } |
| 28 | + |
| 29 | + public void IfHigh(Action action) |
| 30 | + { |
| 31 | + Loop.Bind(() => |
| 32 | + { |
| 33 | + if (m_state.Get()) |
| 34 | + { |
| 35 | + action(); |
| 36 | + } |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + public BooleanEvent Rising() |
| 41 | + { |
| 42 | + bool previous = m_state.Get(); |
| 43 | + return new BooleanEvent(Loop, () => |
| 44 | + { |
| 45 | + bool present = m_state.Get(); |
| 46 | + bool ret = !previous && present; |
| 47 | + previous = present; |
| 48 | + return ret; |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + public BooleanEvent Falling() |
| 53 | + { |
| 54 | + bool previous = m_state.Get(); |
| 55 | + return new BooleanEvent(Loop, () => |
| 56 | + { |
| 57 | + bool present = m_state.Get(); |
| 58 | + bool ret = previous && !present; |
| 59 | + previous = present; |
| 60 | + return ret; |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + public BooleanEvent Debounce(Duration duration, Debouncer.DebounceType type = Debouncer.DebounceType.Rising) |
| 65 | + { |
| 66 | + Debouncer debouncer = new(duration, type); |
| 67 | + return new BooleanEvent(Loop, () => |
| 68 | + { |
| 69 | + return debouncer.Calculate(m_state.Get()); |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + public BooleanEvent Negate() |
| 74 | + { |
| 75 | + return new BooleanEvent(Loop, () => !m_state.Get()); |
| 76 | + } |
| 77 | + |
| 78 | + public BooleanEvent And(Func<bool> other) |
| 79 | + { |
| 80 | + Guard.IsNotNull(other); |
| 81 | + return new BooleanEvent(Loop, () => m_state.Get() && other()); |
| 82 | + } |
| 83 | + |
| 84 | + public BooleanEvent Or(Func<bool> other) |
| 85 | + { |
| 86 | + Guard.IsNotNull(other); |
| 87 | + return new BooleanEvent(Loop, () => m_state.Get() || other()); |
| 88 | + } |
| 89 | + |
| 90 | + public T CastTo<T>(Func<EventLoop, Func<bool>, T> ctor) |
| 91 | + { |
| 92 | + return ctor(Loop, m_state.Get); |
| 93 | + } |
| 94 | +} |
0 commit comments