xref: /aosp_15_r20/external/pigweed/pw_digital_io/public/pw_digital_io/digital_io_mock.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include "pw_assert/check.h"
17 #include "pw_chrono/system_clock.h"
18 #include "pw_containers/inline_deque.h"
19 #include "pw_digital_io/digital_io.h"
20 #include "pw_result/result.h"
21 
22 namespace pw::digital_io {
23 
24 /// Mock implementation of `DigitalInOut` for testing.
25 ///
26 /// Records the times at which the state is changed using a provided clock. This
27 /// class cannot be instantiated directly. Instead, use
28 /// ``DigitalInOutMock<kCapacity>``.
29 class DigitalInOutMockImpl : public pw::digital_io::DigitalInOut {
30  public:
31   using State = ::pw::digital_io::State;
32   using Clock = ::pw::chrono::VirtualSystemClock;
33 
34   struct Event {
35     pw::chrono::SystemClock::time_point timestamp;
36     State state;
37   };
38 
events()39   pw::InlineDeque<Event>& events() { return events_; }
40 
41  protected:
42   DigitalInOutMockImpl(Clock& clock, pw::InlineDeque<Event>& events);
43 
44  private:
DoEnable(bool)45   pw::Status DoEnable(bool) override { return pw::OkStatus(); }
46 
47   pw::Result<State> DoGetState() override;
48 
49   pw::Status DoSetState(State state) override;
50 
51   Clock& clock_;
52   pw::InlineDeque<Event>& events_;
53 };
54 
55 template <size_t kCapacity>
56 class DigitalInOutMock : public DigitalInOutMockImpl {
57  public:
58   static_assert(kCapacity > 0);
59 
DigitalInOutMock()60   DigitalInOutMock() : DigitalInOutMock(Clock::RealClock()) {}
DigitalInOutMock(Clock & clock)61   DigitalInOutMock(Clock& clock) : DigitalInOutMockImpl(clock, events_) {
62     PW_CHECK_OK(SetState(State::kInactive));
63   }
64 
65  private:
66   pw::InlineDeque<Event, kCapacity> events_;
67 };
68 
69 }  // namespace pw::digital_io
70