Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020-2021 Project CHIP Authors
4 : * Copyright (c) 2016-2017 Nest Labs, Inc.
5 : *
6 : * Licensed under the Apache License, Version 2.0 (the "License");
7 : * you may not use this file except in compliance with the License.
8 : * You may obtain a copy of the License at
9 : *
10 : * http://www.apache.org/licenses/LICENSE-2.0
11 : *
12 : * Unless required by applicable law or agreed to in writing, software
13 : * distributed under the License is distributed on an "AS IS" BASIS,
14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 : * See the License for the specific language governing permissions and
16 : * limitations under the License.
17 : */
18 :
19 : /**
20 : * @file
21 : * This file contains declarations of the
22 : * chip::System::Layer class and its related types, data and
23 : * functions.
24 : */
25 :
26 : #pragma once
27 :
28 : #include <type_traits>
29 : #include <utility>
30 :
31 : // Include configuration headers
32 : #include <system/SystemConfig.h>
33 :
34 : #include <lib/core/CHIPCallback.h>
35 :
36 : #include <lib/support/CodeUtils.h>
37 : #include <lib/support/DLLUtil.h>
38 : #include <lib/support/LambdaBridge.h>
39 : #include <system/SystemClock.h>
40 : #include <system/SystemError.h>
41 : #include <system/SystemEvent.h>
42 :
43 : #if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
44 : #include <lib/support/IntrusiveList.h>
45 : #include <system/SocketEvents.h>
46 : #endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_USE_NETWORK_FRAMEWORK
47 :
48 : #if CHIP_SYSTEM_CONFIG_USE_DISPATCH
49 : #include <dispatch/dispatch.h>
50 : #elif CHIP_SYSTEM_CONFIG_USE_LIBEV
51 : #include <ev.h>
52 : #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH/LIBEV
53 :
54 : namespace chip {
55 : namespace System {
56 :
57 : class Layer;
58 : using TimerCompleteCallback = void (*)(Layer * aLayer, void * appState);
59 :
60 : /**
61 : * This provides access to timers according to the configured event handling model.
62 : *
63 : * The abstract class hierarchy is:
64 : * - Layer: Core timer methods.
65 : * - LayerFreeRTOS: Adds methods specific to CHIP_SYSTEM_CONFIG_USING_LWIP and CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT.
66 : * - LayerSockets: Adds I/O event methods specific to CHIP_SYSTEM_CONFIG_USING_SOCKETS.
67 : * - LayerSocketsLoop: Adds methods for event-loop-based implementations.
68 : *
69 : * Threading notes:
70 : *
71 : * The SDK is not generally thread safe. System::Layer methods should only be called from
72 : * a single context, or otherwise externally synchronized. For platforms that use a CHIP
73 : * event loop thread, timer callbacks are invoked on that thread; for platforms that use
74 : * a CHIP lock, the lock is held.
75 : */
76 : class DLL_EXPORT Layer
77 : {
78 : public:
79 : Layer() = default;
80 0 : virtual ~Layer() = default;
81 :
82 : /**
83 : * Initialize the Layer.
84 : */
85 : virtual CHIP_ERROR Init() = 0;
86 :
87 : /**
88 : * Shut down the Layer.
89 : *
90 : * Some other layers hold pointers to System::Layer, so care must be taken
91 : * to ensure that they are not used after calling Shutdown().
92 : */
93 : virtual void Shutdown() = 0;
94 :
95 : /**
96 : * True if this Layer is initialized. No method on Layer or its abstract descendants, other than this and `Init()`,
97 : * may be called from general code unless this is true. (Individual Impls may have looser constraints internally.)
98 : */
99 : virtual bool IsInitialized() const = 0;
100 :
101 : /**
102 : * @brief
103 : * This method starts a one-shot timer. This method must be called while in the Matter context (from
104 : * the Matter event loop, or while holding the Matter stack lock).
105 : *
106 : * @note
107 : * Only a single timer is allowed to be started with the same @a aComplete and @a aAppState
108 : * arguments. If called with @a aComplete and @a aAppState identical to an existing timer,
109 : * the currently-running timer will first be cancelled.
110 : *
111 : * @param[in] aDelay Time before this timer fires.
112 : * @param[in] aComplete A pointer to the function called when timer expires.
113 : * @param[in] aAppState A pointer to the application state object used when timer expires.
114 : *
115 : * @return CHIP_NO_ERROR On success.
116 : * @return CHIP_ERROR_NO_MEMORY If a timer cannot be allocated.
117 : * @return Other Value indicating timer failed to start.
118 : */
119 : virtual CHIP_ERROR StartTimer(Clock::Timeout aDelay, TimerCompleteCallback aComplete, void * aAppState) = 0;
120 :
121 : /**
122 : * @brief
123 : * This method extends the timer expiry to the provided aDelay. This method must be called while in the Matter context
124 : * (from the Matter event loop, or while holding the Matter stack lock).
125 : * aDelay is not added to the Remaining time of the timer. The finish line is pushed back to aDelay.
126 : *
127 : * @note The goal of this method is that the timer remaining time cannot be shrunk and only extended to a new time
128 : * If the provided new Delay is smaller than the timer's remaining time, the timer is left untouched.
129 : * In the other case the method acts like StartTimer
130 : *
131 : * @param[in] aDelay Time before this timer fires.
132 : * @param[in] aComplete A pointer to the function called when timer expires.
133 : * @param[in] aAppState A pointer to the application state object used when timer expires.
134 : *
135 : * @return CHIP_NO_ERROR On success.
136 : * @return CHIP_ERROR_INVALID_ARGUMENT If the provided aDelay value is 0
137 : * @return CHIP_ERROR_NO_MEMORY If a timer cannot be allocated.
138 : * @return Other Value indicating timer failed to start.
139 : */
140 : virtual CHIP_ERROR ExtendTimerTo(Clock::Timeout aDelay, TimerCompleteCallback aComplete, void * aAppState) = 0;
141 :
142 : /**
143 : * @brief
144 : * This method searches for the timer matching the provided parameters.
145 : * and returns whether it is still "running" and waiting to trigger or not.
146 : *
147 : * @note This is used to verify by how long the ExtendTimer method extends the timer, as it may ignore an extension request
148 : * if it is shorter than the current timer's remaining time.
149 : *
150 : * @param[in] onComplete A pointer to the function called when timer expires.
151 : * @param[in] appState A pointer to the application state object used when timer expires.
152 : *
153 : * @return True if there is a current timer set to call, at some point in the future, the provided onComplete callback
154 : * with the corresponding appState context. False otherwise.
155 : */
156 : virtual bool IsTimerActive(TimerCompleteCallback onComplete, void * appState) = 0;
157 :
158 : /**
159 : * @brief
160 : * This method searches for the timer matching the provided parameters
161 : * and returns the remaining time left before it expires.
162 : * @param[in] onComplete A pointer to the function called when timer expires.
163 : * @param[in] appState A pointer to the application state object used when timer expires.
164 : *
165 : * @return The remaining time left before the timer expires.
166 : */
167 : virtual Clock::Timeout GetRemainingTime(TimerCompleteCallback onComplete, void * appState) = 0;
168 :
169 : /**
170 : * @brief This method cancels a one-shot timer, started earlier through @p StartTimer(). This method must
171 : * be called while in the Matter context (from the Matter event loop, or while holding the Matter
172 : * stack lock).
173 : *
174 : * @note
175 : * The cancellation could fail silently if the timer specified by the combination of the callback
176 : * function and application state object couldn't be found.
177 : *
178 : * @param[in] aOnComplete A pointer to the callback function used in calling @p StartTimer().
179 : * @param[in] aAppState A pointer to the application state object used in calling @p StartTimer().
180 : *
181 : */
182 : virtual void CancelTimer(TimerCompleteCallback aOnComplete, void * aAppState) = 0;
183 :
184 : /**
185 : * @brief
186 : * Schedules a `TimerCompleteCallback` to be run as soon as possible in the Matter context.
187 : *
188 : * WARNING: This must only be called when already in the Matter context (from the Matter event loop, or
189 : * while holding the Matter stack lock). The `PlatformMgr::ScheduleWork()` equivalent method
190 : * is safe to call outside Matter context.
191 : *
192 : * @param[in] aComplete A pointer to a callback function to be called when this timer fires.
193 : * @param[in] aAppState A pointer to an application state object to be passed to the callback function as argument.
194 : *
195 : * @retval CHIP_ERROR_INCORRECT_STATE If the System::Layer has not been initialized.
196 : * @retval CHIP_ERROR_NO_MEMORY If the SystemLayer cannot allocate a new timer.
197 : * @retval CHIP_NO_ERROR On success.
198 : */
199 : virtual CHIP_ERROR ScheduleWork(TimerCompleteCallback aComplete, void * aAppState) = 0;
200 :
201 : /**
202 : * @brief
203 : * Schedules a lambda object to be run as soon as possible in the Matter context.
204 : *
205 : * This is safe to call from any context and will guarantee execution in Matter context.
206 : * Note that the Lambda's capture have to fit within `CHIP_CONFIG_LAMBDA_EVENT_SIZE` bytes.
207 : *
208 : * @param[in] lambda The Lambda to execute in Matter context.
209 : *
210 : * @retval CHIP_NO_ERROR On success.
211 : * @retval other Platform-specific errors generated indicating the reason for failure.
212 : */
213 : template <typename Lambda>
214 : CHIP_ERROR ScheduleLambda(const Lambda & lambda)
215 : {
216 : static_assert(std::is_invocable_v<Lambda>, "lambda argument must be an invocable with no arguments");
217 : LambdaBridge bridge;
218 : bridge.Initialize(lambda);
219 : return ScheduleLambdaBridge(std::move(bridge));
220 : }
221 :
222 : private:
223 : CHIP_ERROR ScheduleLambdaBridge(LambdaBridge && bridge);
224 :
225 : // Not copyable
226 : Layer(const Layer &) = delete;
227 : Layer & operator=(const Layer &) = delete;
228 : };
229 :
230 : #if CHIP_SYSTEM_CONFIG_USE_LWIP || CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
231 :
232 : class LayerFreeRTOS : public Layer
233 : {
234 : };
235 :
236 : #endif // CHIP_SYSTEM_CONFIG_USE_LWIP
237 :
238 : #if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
239 :
240 : class LayerSockets : public Layer
241 : {
242 : public:
243 : /**
244 : * Initialize watching for events on a file descriptor.
245 : *
246 : * Returns an opaque token through @a tokenOut that must be passed to subsequent operations for this file descriptor.
247 : * Multiple calls to start watching the same file descriptor will return the same token.
248 : * StopWatchingSocket() must be called before closing the file descriptor.
249 : */
250 : virtual CHIP_ERROR StartWatchingSocket(int fd, SocketWatchToken * tokenOut) = 0;
251 :
252 : /**
253 : * Register a callback function.
254 : *
255 : * The callback will be invoked (with the CHIP stack lock held) when requested event(s) are ready.
256 : */
257 : virtual CHIP_ERROR SetCallback(SocketWatchToken token, SocketWatchCallback callback, intptr_t data) = 0;
258 :
259 : /**
260 : * Request a callback when the associated file descriptor is readable.
261 : */
262 : virtual CHIP_ERROR RequestCallbackOnPendingRead(SocketWatchToken token) = 0;
263 :
264 : /**
265 : * Request a callback when the associated file descriptor is writable.
266 : */
267 : virtual CHIP_ERROR RequestCallbackOnPendingWrite(SocketWatchToken token) = 0;
268 :
269 : /**
270 : * Cancel a request for a callback when the associated file descriptor is readable.
271 : */
272 : virtual CHIP_ERROR ClearCallbackOnPendingRead(SocketWatchToken token) = 0;
273 :
274 : /**
275 : * Cancel a request for a callback when the associated file descriptor is writable.
276 : */
277 : virtual CHIP_ERROR ClearCallbackOnPendingWrite(SocketWatchToken token) = 0;
278 :
279 : /**
280 : * Stop watching for events on the associated file descriptor.
281 : *
282 : * This MUST be called before the file descriptor is closed.
283 : * It is not necessary to clear callback requests before calling this function.
284 : */
285 : virtual CHIP_ERROR StopWatchingSocket(SocketWatchToken * tokenInOut) = 0;
286 :
287 : /**
288 : * Return a SocketWatchToken that is guaranteed not to be valid. Clients may use this to initialize variables.
289 : */
290 : virtual SocketWatchToken InvalidSocketWatchToken() = 0;
291 : };
292 :
293 : class LayerSocketsLoop;
294 :
295 : /**
296 : * EventLoopHandlers can be registered with a LayerSocketsLoop instance to enable
297 : * participation of those handlers in the processing cycle of the event loop. This makes
298 : * it possible to implement adapters that allow components utilizing a third-party event
299 : * loop API to participate in the Matter event loop, instead of having to run an entirely
300 : * separate event loop on another thread.
301 : *
302 : * Specifically, the `PrepareEvents` and `HandleEvents` methods of registered event loop
303 : * handlers will be called from the LayerSocketsLoop methods of the same names.
304 : *
305 : * @see LayerSocketsLoop::PrepareEvents
306 : * @see LayerSocketsLoop::HandleEvents
307 : */
308 : class EventLoopHandler : public chip::IntrusiveListNodeBase<>
309 : {
310 : public:
311 : virtual ~EventLoopHandler() {}
312 :
313 : /**
314 : * Prepares events and returns the next requested wake time.
315 : */
316 : virtual Clock::Timestamp PrepareEvents(Clock::Timestamp now) { return Clock::Timestamp::max(); }
317 :
318 : /**
319 : * Handles / dispatches pending events.
320 : * Every call to this method will have been preceded by a call to `PrepareEvents`.
321 : */
322 : virtual void HandleEvents() = 0;
323 :
324 : private:
325 : // mState is provided exclusively for use by the LayerSocketsLoop implementation
326 : // sub-class and can be accessed by it via the LayerSocketsLoop::LoopHandlerState() helper.
327 : friend class LayerSocketsLoop;
328 : intptr_t mState = 0;
329 : };
330 :
331 : class LayerSocketsLoop : public LayerSockets
332 : {
333 : public:
334 : virtual void Signal() = 0;
335 : virtual void EventLoopBegins() = 0;
336 : virtual void PrepareEvents() = 0;
337 : virtual void WaitForEvents() = 0;
338 : virtual void HandleEvents() = 0;
339 : virtual void EventLoopEnds() = 0;
340 :
341 : #if !CHIP_SYSTEM_CONFIG_USE_DISPATCH
342 : virtual void AddLoopHandler(EventLoopHandler & handler) = 0;
343 : virtual void RemoveLoopHandler(EventLoopHandler & handler) = 0;
344 : #endif // !CHIP_SYSTEM_CONFIG_USE_DISPATCH
345 :
346 : #if CHIP_SYSTEM_CONFIG_USE_DISPATCH
347 : virtual void SetDispatchQueue(dispatch_queue_t dispatchQueue) = 0;
348 : virtual dispatch_queue_t GetDispatchQueue() = 0;
349 : #elif CHIP_SYSTEM_CONFIG_USE_LIBEV
350 : virtual void SetLibEvLoop(struct ev_loop * aLibEvLoopP) = 0;
351 : virtual struct ev_loop * GetLibEvLoop() = 0;
352 : #endif // CHIP_SYSTEM_CONFIG_USE_DISPATCH/LIBEV
353 :
354 : protected:
355 : // Expose EventLoopHandler.mState as a non-const reference to sub-classes
356 12 : decltype(EventLoopHandler::mState) & LoopHandlerState(EventLoopHandler & handler) { return handler.mState; }
357 : };
358 :
359 : #endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
360 :
361 : } // namespace System
362 : } // namespace chip
|