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 #include "pw_digital_io_linux/notifier.h"
15
16 #include <sys/eventfd.h>
17
18 #include <chrono>
19 #include <thread>
20
21 #include "log_errno.h"
22 #include "pw_assert/check.h"
23 #include "pw_log/log.h"
24 #include "pw_sync/counting_semaphore.h"
25 #include "pw_thread/thread.h"
26 #include "pw_thread_stl/options.h"
27 #include "pw_unit_test/framework.h"
28
29 namespace pw::digital_io {
30 namespace {
31
32 using namespace std::chrono_literals;
33
34 constexpr auto kWaitForDataTimeout = 100ms;
35
36 class NotifierTest : public ::testing::Test {
37 protected:
SetUp()38 void SetUp() override {
39 PW_TEST_ASSERT_OK_AND_ASSIGN(notifier_, LinuxGpioNotifier::Create());
40 }
41
notifier()42 LinuxGpioNotifier& notifier() { return *notifier_; }
43
44 private:
45 std::shared_ptr<LinuxGpioNotifier> notifier_;
46 };
47
48 class FakeLine : public LinuxGpioNotifier::Handler {
49 public:
FakeLine(LinuxGpioNotifier & notifier)50 explicit FakeLine(LinuxGpioNotifier& notifier)
51 : notifier_(notifier), event_fd_(eventfd(0, EFD_SEMAPHORE)) {
52 PW_CHECK_INT_GE(event_fd_, 0, "Failed to create event fd: %d", errno);
53 }
54
~FakeLine()55 ~FakeLine() override {
56 // Unregister now, if still registered, and make errors fail the test.
57 PW_TEST_EXPECT_OK(Unregister());
58 int result = close(event_fd_);
59 PW_CHECK_INT_EQ(result, 0, "Failed to close event fd, err %d", errno);
60 }
61
62 FakeLine(const FakeLine&) = delete;
63 FakeLine& operator=(const FakeLine&) = delete;
64
65 // Register the line with the notifier.
Register()66 pw::Status Register() {
67 PW_CHECK(!registered_);
68 registered_ = true;
69 return notifier_.RegisterLine(event_fd_, *this);
70 }
71
72 // Unregister the line from the notifier.
Unregister()73 pw::Status Unregister() {
74 if (!registered_) {
75 return OkStatus();
76 }
77 registered_ = false;
78 return notifier_.UnregisterLine(event_fd_);
79 }
80
81 // Atomically send one or more events.
SendEvents(int count)82 void SendEvents(int count) {
83 PW_CHECK_INT_GE(count, 1, "Must send one or more events");
84 uint64_t data = count;
85 ssize_t result = write(event_fd_, &data, sizeof(data));
86 PW_CHECK_INT_EQ(result,
87 sizeof(data),
88 "Failed to write to event fd: " ERRNO_FORMAT_STRING,
89 ERRNO_FORMAT_ARGS(errno));
90 }
91
92 // Wait until the line has received an event or internal timeout expires.
TryWaitForData()93 bool TryWaitForData() {
94 return received_events_.try_acquire_for(kWaitForDataTimeout);
95 }
96
total_received_events() const97 unsigned int total_received_events() const { return total_received_events_; }
98
99 protected:
100 // Implement LinuxGpioNotifier::Handler
HandleEvents()101 void HandleEvents() override {
102 uint64_t val;
103 auto size_read = read(event_fd_, &val, sizeof(val));
104 PW_CHECK_INT_GE(size_read,
105 1,
106 "Failed to read an event: " ERRNO_FORMAT_STRING,
107 ERRNO_FORMAT_ARGS(errno));
108 ++total_received_events_;
109 received_events_.release(1);
110 }
111
notifier()112 LinuxGpioNotifier& notifier() { return notifier_; }
event_fd() const113 int event_fd() const { return event_fd_; }
114
115 private:
116 LinuxGpioNotifier& notifier_;
117 int event_fd_;
118 unsigned int total_received_events_ = 0;
119 pw::sync::CountingSemaphore received_events_;
120
121 bool registered_ = false;
122 };
123
TEST_F(NotifierTest,TestNoEvent)124 TEST_F(NotifierTest, TestNoEvent) {
125 FakeLine line(notifier());
126 PW_TEST_ASSERT_OK(line.Register());
127
128 constexpr auto timeout = 0; // Don't block
129 auto result = notifier().WaitForEvents(timeout);
130 EXPECT_EQ(result.status(), pw::Status::DeadlineExceeded());
131
132 EXPECT_EQ(line.total_received_events(), 0u);
133
134 PW_TEST_EXPECT_OK(line.Unregister());
135 }
136
TEST_F(NotifierTest,TestSendReceiveOneEventManual)137 TEST_F(NotifierTest, TestSendReceiveOneEventManual) {
138 FakeLine line(notifier());
139 PW_TEST_ASSERT_OK(line.Register());
140
141 constexpr unsigned int num_events = 1;
142
143 line.SendEvents(num_events);
144
145 constexpr auto timeout = 0; // Don't block
146 PW_TEST_ASSERT_OK_AND_ASSIGN(unsigned int count,
147 notifier().WaitForEvents(timeout));
148
149 EXPECT_EQ(count, num_events);
150 EXPECT_EQ(line.total_received_events(), num_events);
151
152 PW_TEST_EXPECT_OK(line.Unregister());
153 }
154
TEST_F(NotifierTest,TestSendReceiveMultipleEventsManual)155 TEST_F(NotifierTest, TestSendReceiveMultipleEventsManual) {
156 FakeLine line(notifier());
157 PW_TEST_ASSERT_OK(line.Register());
158
159 constexpr unsigned int num_events = 4;
160
161 line.SendEvents(num_events);
162
163 // WaitForEvents will only handle one event per line, per iteration.
164 // So call it in a loop until it expires.
165 unsigned int total_result = 0;
166 while (true) {
167 constexpr auto timeout = 0; // Don't block
168 auto result = notifier().WaitForEvents(timeout);
169 if (!result.ok()) {
170 EXPECT_EQ(result.status(), pw::Status::DeadlineExceeded());
171 break;
172 }
173 total_result += result.value();
174 }
175
176 EXPECT_EQ(total_result, num_events);
177 EXPECT_EQ(line.total_received_events(), num_events);
178
179 PW_TEST_EXPECT_OK(line.Unregister());
180 }
181
TEST_F(NotifierTest,TestSendReceiveEventsThread)182 TEST_F(NotifierTest, TestSendReceiveEventsThread) {
183 FakeLine line(notifier());
184 PW_TEST_ASSERT_OK(line.Register());
185
186 pw::Thread notif_thread(pw::thread::stl::Options(), notifier());
187
188 constexpr unsigned int num_events = 3;
189
190 line.SendEvents(num_events);
191
192 while (line.TryWaitForData()) {
193 }
194
195 EXPECT_EQ(line.total_received_events(), num_events);
196
197 PW_TEST_EXPECT_OK(line.Unregister());
198
199 notifier().CancelWait();
200 notif_thread.join();
201 }
202
TEST_F(NotifierTest,TestRegisterLineMultipleLinesThread)203 TEST_F(NotifierTest, TestRegisterLineMultipleLinesThread) {
204 // Make primary line
205 FakeLine line1(notifier());
206 PW_TEST_ASSERT_OK(line1.Register());
207
208 pw::Thread notif_thread(pw::thread::stl::Options(), notifier());
209
210 line1.SendEvents(1);
211 EXPECT_TRUE(line1.TryWaitForData());
212
213 {
214 // Make secondary line in smaller scope
215 FakeLine line2(notifier());
216 PW_TEST_ASSERT_OK(line2.Register());
217
218 line1.SendEvents(1);
219 line2.SendEvents(1);
220
221 EXPECT_TRUE(line1.TryWaitForData());
222 EXPECT_TRUE(line2.TryWaitForData());
223
224 PW_TEST_EXPECT_OK(line2.Unregister());
225 }
226
227 // Line 1 is once again the only line that is registered.
228 line1.SendEvents(1);
229 EXPECT_TRUE(line1.TryWaitForData());
230
231 PW_TEST_EXPECT_OK(line1.Unregister());
232
233 notifier().CancelWait();
234 notif_thread.join();
235 }
236
237 } // namespace
238 } // namespace pw::digital_io
239