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 #include "test_utils.h"
29
30 namespace pw::digital_io {
31 namespace {
32
33 using namespace std::chrono_literals;
34
35 constexpr auto kWaitForDataTimeout = 100ms;
36
37 class NotifierTest : public ::testing::Test {
38 protected:
SetUp()39 void SetUp() override {
40 ASSERT_OK_AND_ASSIGN(notifier_, LinuxGpioNotifier::Create());
41 }
42
notifier()43 LinuxGpioNotifier& notifier() { return *notifier_; }
44
45 private:
46 std::shared_ptr<LinuxGpioNotifier> notifier_;
47 };
48
49 class FakeLine : public LinuxGpioNotifier::Handler {
50 public:
FakeLine(LinuxGpioNotifier & notifier)51 explicit FakeLine(LinuxGpioNotifier& notifier)
52 : notifier_(notifier), event_fd_(eventfd(0, EFD_SEMAPHORE)) {
53 PW_CHECK_INT_GE(event_fd_, 0, "Failed to create event fd: %d", errno);
54 }
55
~FakeLine()56 ~FakeLine() override {
57 // Unregister now, if still registered, and make errors fail the test.
58 EXPECT_OK(Unregister());
59 int result = close(event_fd_);
60 PW_CHECK_INT_EQ(result, 0, "Failed to close event fd, err %d", errno);
61 }
62
63 FakeLine(const FakeLine&) = delete;
64 FakeLine& operator=(const FakeLine&) = delete;
65
66 // Register the line with the notifier.
Register()67 pw::Status Register() {
68 PW_CHECK(!registered_);
69 registered_ = true;
70 return notifier_.RegisterLine(event_fd_, *this);
71 }
72
73 // Unregister the line from the notifier.
Unregister()74 pw::Status Unregister() {
75 if (!registered_) {
76 return OkStatus();
77 }
78 registered_ = false;
79 return notifier_.UnregisterLine(event_fd_);
80 }
81
82 // Atomically send one or more events.
SendEvents(int count)83 void SendEvents(int count) {
84 PW_CHECK_INT_GE(count, 1, "Must send one or more events");
85 uint64_t data = count;
86 ssize_t result = write(event_fd_, &data, sizeof(data));
87 PW_CHECK_INT_EQ(result,
88 sizeof(data),
89 "Failed to write to event fd: " ERRNO_FORMAT_STRING,
90 ERRNO_FORMAT_ARGS(errno));
91 }
92
93 // Wait until the line has received an event or internal timeout expires.
TryWaitForData()94 bool TryWaitForData() {
95 return received_events_.try_acquire_for(kWaitForDataTimeout);
96 }
97
total_received_events() const98 unsigned int total_received_events() const { return total_received_events_; }
99
100 protected:
101 // Implement LinuxGpioNotifier::Handler
HandleEvents()102 void HandleEvents() override {
103 uint64_t val;
104 auto size_read = read(event_fd_, &val, sizeof(val));
105 PW_CHECK_INT_GE(size_read,
106 1,
107 "Failed to read an event: " ERRNO_FORMAT_STRING,
108 ERRNO_FORMAT_ARGS(errno));
109 ++total_received_events_;
110 received_events_.release(1);
111 }
112
notifier()113 LinuxGpioNotifier& notifier() { return notifier_; }
event_fd() const114 int event_fd() const { return event_fd_; }
115
116 private:
117 LinuxGpioNotifier& notifier_;
118 int event_fd_;
119 unsigned int total_received_events_ = 0;
120 pw::sync::CountingSemaphore received_events_;
121
122 bool registered_ = false;
123 };
124
TEST_F(NotifierTest,TestNoEvent)125 TEST_F(NotifierTest, TestNoEvent) {
126 FakeLine line(notifier());
127 ASSERT_OK(line.Register());
128
129 constexpr auto timeout = 0; // Don't block
130 auto result = notifier().WaitForEvents(timeout);
131 EXPECT_EQ(result.status(), pw::Status::DeadlineExceeded());
132
133 EXPECT_EQ(line.total_received_events(), 0u);
134
135 EXPECT_OK(line.Unregister());
136 }
137
TEST_F(NotifierTest,TestSendReceiveOneEventManual)138 TEST_F(NotifierTest, TestSendReceiveOneEventManual) {
139 FakeLine line(notifier());
140 ASSERT_OK(line.Register());
141
142 constexpr unsigned int num_events = 1;
143
144 line.SendEvents(num_events);
145
146 constexpr auto timeout = 0; // Don't block
147 ASSERT_OK_AND_ASSIGN(unsigned int count, notifier().WaitForEvents(timeout));
148
149 EXPECT_EQ(count, num_events);
150 EXPECT_EQ(line.total_received_events(), num_events);
151
152 EXPECT_OK(line.Unregister());
153 }
154
TEST_F(NotifierTest,TestSendReceiveMultipleEventsManual)155 TEST_F(NotifierTest, TestSendReceiveMultipleEventsManual) {
156 FakeLine line(notifier());
157 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 EXPECT_OK(line.Unregister());
180 }
181
TEST_F(NotifierTest,TestSendReceiveEventsThread)182 TEST_F(NotifierTest, TestSendReceiveEventsThread) {
183 FakeLine line(notifier());
184 ASSERT_OK(line.Register());
185
186 pw::thread::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 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 ASSERT_OK(line1.Register());
207
208 pw::thread::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 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 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 EXPECT_OK(line1.Unregister());
232
233 notifier().CancelWait();
234 notif_thread.join();
235 }
236
237 } // namespace
238 } // namespace pw::digital_io
239