xref: /aosp_15_r20/system/chre/core/include/chre/core/wifi_request_manager.h (revision 84e339476a462649f82315436d70fd732297a399)
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef CHRE_CORE_WIFI_REQUEST_MANAGER_H_
18 #define CHRE_CORE_WIFI_REQUEST_MANAGER_H_
19 
20 #ifdef CHRE_WIFI_SUPPORT_ENABLED
21 
22 #include "chre/core/api_manager_common.h"
23 #include "chre/core/nanoapp.h"
24 #include "chre/core/settings.h"
25 #include "chre/core/timer_pool.h"
26 #include "chre/platform/platform_wifi.h"
27 #include "chre/util/buffer.h"
28 #include "chre/util/non_copyable.h"
29 #include "chre/util/optional.h"
30 #include "chre/util/system/debug_dump.h"
31 #include "chre/util/time.h"
32 #include "chre_api/chre/wifi.h"
33 
34 namespace chre {
35 
36 /**
37  * The WifiRequestManager handles requests from nanoapps for Wifi information.
38  * This includes multiplexing multiple requests into one for the platform to
39  * handle.
40  *
41  * This class is effectively a singleton as there can only be one instance of
42  * the PlatformWifi instance.
43  */
44 class WifiRequestManager : public NonCopyable {
45  public:
46   /**
47    * Specifies what type of ranging request is being issued.
48    *
49    * WIFI_AP denotes a ranging request to a (list of) device(s) via an access
50    * point. WIFI_AWARE denotes  a NAN ranging request to a single peer NAN
51    * device. Even though the abbreviation 'NAN' is used throughout the CHRE
52    * WiFi code and documentation, the simplified enumerator NAN is avoided here
53    * to prevent possible symbol/identifier clashes to a NAN (not-a-number)
54    * defines in clang and GCC's math header.
55    */
56   enum class RangingType { WIFI_AP, WIFI_AWARE };
57 
58   /**
59    * Initializes the WifiRequestManager with a default state and memory for any
60    * requests.
61    */
62   WifiRequestManager();
63 
64   /**
65    * Initializes the underlying platform-specific WiFi module. Must be called
66    * prior to invoking any other methods in this class.
67    */
68   void init();
69 
70   /**
71    * @return the WiFi capabilities exposed by this platform.
72    */
73   uint32_t getCapabilities();
74 
75   /**
76    * Handles a request from a nanoapp to configure the scan monitor. This
77    * includes merging multiple requests for scan monitoring to the PAL (ie: if
78    * multiple apps enable the scan monitor the PAL is only enabled once).
79    *
80    * @param nanoapp The nanoapp that has requested that the scan monitor be
81    *        configured.
82    * @param enable true to enable scan monitoring, false to disable scan
83    *        monitoring.
84    * @param cookie A cookie that is round-tripped back to the nanoapp to
85    *        provide a context when making the request.
86    *
87    * @return true if the request was accepted. The result is delivered
88    *         asynchronously through a CHRE event.
89    */
90   bool configureScanMonitor(Nanoapp *nanoapp, bool enable, const void *cookie);
91 
92   /**
93    * Handles a nanoapp's request for RTT ranging against a set of devices.
94    *
95    * @param rangingType Specifies if ranging is desired for a single NAN device
96    *        or an AP (access point) ranging request for a list of devices.
97    * @param nanoapp Nanoapp issuing the request.
98    * @param params Non-null pointer to parameters, supplied by the nanoapp via
99    *        chreWifiRequestRangingAsync() or chreWifiNanRequestRangingAsync().
100    * @param cookie Opaque pointer supplied by the nanoapp and passed back in the
101    *        async result.
102    *
103    * @return true if the request was accepted. The result is delivered
104    *         asynchronously through a CHRE event.
105    */
106   bool requestRanging(RangingType rangingType, Nanoapp *nanoapp,
107                       const void *params, const void *cookie);
108 
109   /**
110    * Performs an active wifi scan.
111    *
112    * This is currently a 1:1 mapping into the PAL. If more than one nanoapp
113    * requests an active wifi scan, this will be an assertion failure for
114    * debug builds and a no-op in production (ie: subsequent requests are
115    * ignored).
116    *
117    * @param nanoapp The nanoapp that has requested an active wifi scan.
118    * @param params Non-null pointer to the scan parameters structure
119    *        supplied by the nanoapp.
120    * @param cookie A cookie that is round-tripped back to the nanoapp to
121    *        provide a context when making the request.
122    * @return true if the request was accepted. The result is delivered
123    *         asynchronously through a CHRE event.
124    */
125   bool requestScan(Nanoapp *nanoapp, const chreWifiScanParams *params,
126                    const void *cookie);
127 
128   /**
129    * Subscribe to a NAN service.
130    *
131    * @param nanoapp The nanoapp that has requested a service subscription.
132    * @param config Service-specific nanoapp subscription configuration
133    *        parameters.
134    * @param cookie A cookie that is round-tripped back to the nanoapp to provide
135    *        a context when making the request.
136    * @return true if a subscription request was successful. The result is
137    *         provided asynchronously through a CHRE event.
138    */
139   bool nanSubscribe(Nanoapp *nanoapp,
140                     const struct chreWifiNanSubscribeConfig *config,
141                     const void *cookie);
142 
143   /**
144    * Cancel a NAN subscription.
145    *
146    * @param nanoapp The nanoapp that has requested a subscription cancelation.
147    * @param subscriptionId The subscription ID assigned by the NAN engine for
148    *        the original subscription request.
149    *        cancelation request was successful.
150    * @return true if the cancelation was successful, false otherwise.
151    */
152   bool nanSubscribeCancel(Nanoapp *nanoapp, uint32_t subscriptionId);
153 
154   /**
155    * Passes the result of an RTT ranging request on to the requesting nanoapp.
156    *
157    * @param errorCode Value from enum chreError
158    * @param event Event containing ranging results, or null if errorCode is not
159    *        chreError
160    */
161   void handleRangingEvent(uint8_t errorCode,
162                           struct chreWifiRangingEvent *event);
163 
164   /**
165    * Handles the result of a request to PlatformWifi to change the state of the
166    * scan monitor.
167    *
168    * @param enabled true if the result of the operation was an enabled scan
169    *        monitor.
170    * @param errorCode an error code that is provided to indicate success or what
171    *        type of error has occurred. See the chreError enum in the CHRE API
172    *        for additional details.
173    */
174   void handleScanMonitorStateChange(bool enabled, uint8_t errorCode);
175 
176   /**
177    * Handles the result of a request to the PlatformWifi to request an active
178    * Wifi scan.
179    *
180    * @param pending The result of the request was successful and the results
181    *        will be sent via the handleScanEvent method.
182    * @param errorCode an error code that is used to indicate success or what
183    *        type of error has occurred. See the chreError enum in the CHRE API
184    *        for additional details.
185    */
186   void handleScanResponse(bool pending, uint8_t errorCode);
187 
188   /**
189    * Handles a CHRE wifi scan event.
190    *
191    * @param event The wifi scan event provided to the wifi request manager. This
192    *        memory is guaranteed not to be modified until it has been explicitly
193    *        released through the PlatformWifi instance.
194    */
195   void handleScanEvent(struct chreWifiScanEvent *event);
196 
197   /**
198    * Updates the NAN availability state.
199    *
200    * @param available Whether NAN is available to use.
201    */
202   void updateNanAvailability(bool available);
203 
204   /**
205    * Handles a NAN service identifier event. This event is the asynchronous
206    * result of a NAN subscription request by a nanoapp.
207    *
208    * @param errorCode CHRE_ERROR_NONE if the NAN engine was able to successfully
209    *        assign an ID to the subscription request, an appropriate error code
210    *        from @ref enum chreError otherwise.
211    * @param subscriptionId The ID assigned by the NAN engine to the subscription
212    *        request. Note that this argument is invalid if the errorCode is not
213    *        CHRE_ERROR_NONE.
214    */
215   void handleNanServiceIdentifierEvent(uint8_t errorCode,
216                                        uint32_t subscriptionId);
217 
218   /**
219    * Handles a NAN service discovery event. This event is invoked when a NAN
220    * publisher was found that conforms to the configuration parameters in the
221    * service subscription request.
222    *
223    * @param event Structure that contains information specific to the publisher
224    *        that was discovered.
225    */
226   void handleNanServiceDiscoveryEvent(struct chreWifiNanDiscoveryEvent *event);
227 
228   /**
229    * Handles a NAN service lost event that is initiated when a publisher has
230    * disappeared.
231    *
232    * @param subscriptionId The subscriber to notify of the publisher's
233    *        disappearance.
234    * @param publisherId The publisher who has gone away.
235    */
236   void handleNanServiceLostEvent(uint32_t subscriptionId, uint32_t publisherId);
237 
238   /**
239    * Handles a NAN service terminated event.
240    *
241    * @param errorCode A value in @ref enum chreError that indicates the reason
242    *        for the termination.
243    * @param subscriptionId The ID of the subscriber who should be notified of
244    *        the service termination.
245    */
246   void handleNanServiceTerminatedEvent(uint8_t errorCode,
247                                        uint32_t subscriptionId);
248 
249   /**
250    * Handles a NAN service subscription cancelation event.
251    *
252    * @param errorCode An error code from enum chreError, with CHRE_ERROR_NONE
253    *        indicating successfully canceling a subscription.
254    * @param subscriptionId The ID of the subscribe session which has now been
255    *        canceled.
256    */
257   void handleNanServiceSubscriptionCanceledEvent(uint8_t errorCode,
258                                                  uint32_t subscriptionId);
259 
260   /**
261    * Prints state in a string buffer. Must only be called from the context of
262    * the main CHRE thread.
263    *
264    * @param debugDump The debug dump wrapper where a string can be printed
265    *     into one of the buffers.
266    */
267   void logStateToBuffer(DebugDumpWrapper &debugDump) const;
268 
269   /**
270    * Invoked when the host notifies CHRE that there has been a change in the
271    * WiFi access via the user settings.
272    *
273    * @param setting The setting that changed.
274    * @param enabled Whether setting is enabled or not.
275    */
276   void onSettingChanged(Setting setting, bool enabled);
277 
278   /**
279    * Disables pending scan monitoring and NAN subscription for a nanoapp
280    *
281    * @param nanoapp A non-null pointer to the nanoapp.
282    *
283    * @return The number of subscriptions disabled.
284    */
285   uint32_t disableAllSubscriptions(Nanoapp *nanoapp);
286 
287   /**
288    * Get the number of current active NAN subscriptions.
289    *
290    * @return Number of active NAN subscriptions.
291    */
getNumNanSubscriptions()292   size_t getNumNanSubscriptions() const {
293     return mNanoappSubscriptions.size();
294   }
295 
296  private:
297   struct PendingRequestBase {
298     uint16_t nanoappInstanceId;  //!< ID of the Nanoapp issuing this request
299     const void *cookie;          //!< User data supplied by the nanoapp
300 
301     PendingRequestBase() = default;
PendingRequestBasePendingRequestBase302     PendingRequestBase(uint16_t nanoappInstanceId_, const void *cookie_)
303         : nanoappInstanceId(nanoappInstanceId_), cookie(cookie_) {}
304   };
305 
306   struct PendingRangingRequestBase : public PendingRequestBase {
307     RangingType type;
308   };
309 
310   struct PendingNanSubscribeRequest : public PendingRequestBase {
311     uint8_t type;
312     Buffer<char> service;
313     Buffer<uint8_t> serviceSpecificInfo;
314     Buffer<uint8_t> matchFilter;
315   };
316 
317   /**
318    * Structure used to store ranging target information in the ranging
319    * requests pending queue. Since NAN and AP ranging target params are
320    * heterogeneous structures (NAN ranging params is a small subset of an AP
321    * ranging target), both structures are included in the pending request
322    * with the appropriate structure populated based on the ranging type.
323    */
324   struct PendingRangingRequest : public PendingRangingRequestBase {
325     //! If the request was queued, a variable-length list of devices to
326     //! perform ranging against (used to reconstruct chreWifiRangingParams).
327     Buffer<struct chreWifiRangingTarget> targetList;
328 
329     //! Structure which contains the MAC address of a peer NAN device with
330     //! which ranging is desired.
331     struct chreWifiNanRangingParams nanRangingParams;
332   };
333 
334   struct PendingScanMonitorRequest : public PendingRequestBase {
335     bool enable;  //!< Requested scan monitor state
336   };
337 
338   struct PendingScanRequest : public PendingRequestBase {
339     struct chreWifiScanParams scanParams;
340 
PendingScanRequestPendingScanRequest341     PendingScanRequest(uint16_t nanoappInstanceId_, const void *cookie_,
342                        const struct chreWifiScanParams *scanParams_)
343         : PendingRequestBase(nanoappInstanceId_, cookie_),
344           scanParams(*scanParams_) {}
345   };
346 
347   //! An internal struct to hold scan request data for logging
348   struct WifiScanRequestLog {
WifiScanRequestLogWifiScanRequestLog349     WifiScanRequestLog(Nanoseconds timestampIn, uint16_t instanceIdIn,
350                        chreWifiScanType scanTypeIn, Milliseconds maxScanAgeMsIn)
351         : timestamp(timestampIn),
352           instanceId(instanceIdIn),
353           scanType(scanTypeIn),
354           maxScanAgeMs(maxScanAgeMsIn) {}
355 
356     Nanoseconds timestamp;
357     uint16_t instanceId;
358     enum chreWifiScanType scanType;
359     Milliseconds maxScanAgeMs;
360   };
361 
362   struct NanoappNanSubscriptions {
363     uint16_t nanoappInstanceId;
364     uint32_t subscriptionId;
365 
NanoappNanSubscriptionsNanoappNanSubscriptions366     NanoappNanSubscriptions(uint16_t nappId, uint32_t subId)
367         : nanoappInstanceId(nappId), subscriptionId(subId) {}
368   };
369 
370   enum class PendingNanConfigType { UNKNOWN, ENABLE, DISABLE };
371 
372   static constexpr size_t kMaxPendingScanRequest = 4;
373   static constexpr size_t kMaxScanMonitorStateTransitions = 8;
374   static constexpr size_t kMaxPendingRangingRequests = 4;
375   static constexpr size_t kMaxPendingNanSubscriptionRequests = 4;
376 
377   PlatformWifi mPlatformWifi;
378 
379   //! The queue of state transition requests for the scan monitor. Only one
380   //! asynchronous scan monitor state transition can be in flight at one time.
381   //! Any further requests are queued here.
382   ArrayQueue<PendingScanMonitorRequest, kMaxScanMonitorStateTransitions>
383       mPendingScanMonitorRequests;
384 
385   //! The queue of scan request. Only one asynchronous scan monitor state
386   //! transition can be in flight at one time. Any further requests are queued
387   //! here.
388   ArrayQueue<PendingScanRequest, kMaxPendingScanRequest> mPendingScanRequests;
389 
390   //! The list of nanoapps who have enabled scan monitoring. This list is
391   //! maintained to ensure that nanoapps are always subscribed to wifi scan
392   //! results as requested. Note that a request for wifi scan monitoring can
393   //! exceed the duration of a single active wifi scan request. This makes it
394   //! insuitable only subscribe to wifi scan events when an active request is
395   //! made and the scan monitor must remain enabled when an active request has
396   //! completed.
397   DynamicVector<uint16_t> mScanMonitorNanoapps;
398 
399   //! The list of nanoapps that have an active NAN subscription. The pair
400   //! format that is used is <subscriptionId, nanoappInstanceId>.
401   DynamicVector<NanoappNanSubscriptions> mNanoappSubscriptions;
402 
403   //! This is set to true if the results of an active scan request are pending.
404   bool mScanRequestResultsArePending = false;
405 
406   //! Accumulates the number of scan event results to determine when the last
407   //! in a scan event stream has been received.
408   uint8_t mScanEventResultCountAccumulator = 0;
409 
410   bool mNanIsAvailable = false;
411   bool mNanConfigRequestToHostPending = false;
412   PendingNanConfigType mNanConfigRequestToHostPendingType =
413       PendingNanConfigType::UNKNOWN;
414 
415   //! Tracks the in-flight ranging request and any others queued up behind it
416   ArrayQueue<PendingRangingRequest, kMaxPendingRangingRequests>
417       mPendingRangingRequests;
418 
419   //! Tracks pending NAN subscribe requests.
420   ArrayQueue<PendingNanSubscribeRequest, kMaxPendingNanSubscriptionRequests>
421       mPendingNanSubscribeRequests;
422 
423   //! List of most recent wifi scan request logs
424   static constexpr size_t kNumWifiRequestLogs = 10;
425   ArrayQueue<WifiScanRequestLog, kNumWifiRequestLogs> mWifiScanRequestLogs;
426 
427   //! Manages the timer when a ranging request is dispatched to the PAL.
428   TimerHandle mRequestRangingTimeoutHandle;
429 
430   //! Manages the timer that starts when a configure scan monitor request is
431   //! dispatched to the PAL.
432   TimerHandle mConfigureScanMonitorTimeoutHandle;
433 
434   //! Manages the timer that starts when a configure scan request is dispatched
435   //! to the PAL.
436   TimerHandle mScanRequestTimeoutHandle = CHRE_TIMER_INVALID;
437 
438   //! System time when the last WiFi scan event was received.
439   Milliseconds mLastScanEventTime;
440 
441   //! ErrorCode Histogram for collected errors, the index of this array
442   //! corresponds to the type of the errorcode
443   uint32_t mScanMonitorErrorHistogram[CHRE_ERROR_SIZE] = {0};
444   uint32_t mActiveScanErrorHistogram[CHRE_ERROR_SIZE] = {0};
445 
446   /**
447    * @return true if the scan monitor is enabled by any nanoapps.
448    */
449   bool scanMonitorIsEnabled() const;
450 
451   /**
452    * Check if a nanoapp already has a pending scan request.
453    *
454    * @param instanceId the instance ID of the nanoapp.
455    * @return true if the nanoapp already has a pending scan request in queue.
456    */
457   bool nanoappHasPendingScanRequest(uint16_t instanceId) const;
458 
459   /**
460    * @param instanceId the instance ID of the nanoapp.
461    * @param index an optional pointer to a size_t to populate with the index of
462    *        the nanoapp in the list of nanoapps.
463    *
464    * @return true if the nanoapp has an active request for scan monitoring.
465    */
466   bool nanoappHasScanMonitorRequest(uint16_t instanceId,
467                                     size_t *index = nullptr) const;
468 
469   /**
470    * Returns whether the nanoapp has a pending activation for scan monitoring.
471    *
472    * @param instanceId the instance ID of the nanoapp.
473    *
474    * @return whether the nanoapp has a pending request for scan monitoring.
475    */
476   bool nanoappHasPendingScanMonitorRequest(uint16_t instanceId) const;
477 
478   /**
479    * @param requestedState The requested state to compare against.
480    * @param nanoappHasRequest The requesting nanoapp has an existing request.
481    *
482    * @return true if the scan monitor is in the requested state.
483    */
484   bool scanMonitorIsInRequestedState(bool requestedState,
485                                      bool nanoappHasRequest) const;
486 
487   /**
488    * @param requestedState The requested state to compare against.
489    * @param nanoappHasRequest The requesting nanoapp has an existing request.
490    *
491    * @return true if a state transition is required to reach the requested
492    * state.
493    */
494   bool scanMonitorStateTransitionIsRequired(bool requestedState,
495                                             bool nanoappHasRequest) const;
496 
497   /**
498    * Builds a scan monitor state transition and adds it to the queue of incoming
499    * requests.
500    * @param nanoapp A non-null pointer to a nanoapp that is requesting the
501    *        change.
502    * @param enable The target requested scan monitoring state.
503    * @param cookie The pointer cookie passed in by the calling nanoapp to return
504    *        to the nanoapp when the request completes.
505    *
506    * @return true if the request is enqueued or false if the queue is full.
507    */
508   bool addScanMonitorRequestToQueue(Nanoapp *nanoapp, bool enable,
509                                     const void *cookie);
510 
511   /**
512    * Adds a nanoapp to the list of nanoapps that are monitoring for wifi scans.
513    * @param enable true if enabling scan monitoring.
514    * @param instanceId The instance ID of the scan monitoring nanoapp.
515    *
516    * @return true if the nanoapp was added to the list.
517    */
518   bool updateNanoappScanMonitoringList(bool enable, uint16_t instanceId);
519 
520   /**
521    * Posts an event to a nanoapp indicating the result of a wifi scan monitoring
522    * configuration change.
523    *
524    * @param nanoappInstanceId The nanoapp instance ID to direct the event to.
525    * @param success If the request for a wifi resource was successful.
526    * @param enable The target state of the request. If enable is set to false
527    *        and the request was successful, the nanoapp is removed from the
528    *        list of nanoapps requesting scan monitoring.
529    * @param errorCode The error code when success is set to false.
530    * @param cookie The cookie to be provided to the nanoapp. This is
531    *        round-tripped from the nanoapp to provide context.
532    *
533    * @return true if the event was successfully posted to the event loop.
534    */
535   bool postScanMonitorAsyncResultEvent(uint16_t nanoappInstanceId, bool success,
536                                        bool enable, uint8_t errorCode,
537                                        const void *cookie);
538 
539   /**
540    * Calls through to postScanMonitorAsyncResultEvent but invokes the
541    * FATAL_ERROR macro if the event is not posted successfully. This is used in
542    * asynchronous contexts where a nanoapp could be stuck waiting for a response
543    * but CHRE failed to enqueue one. For parameter details,
544    * @see postScanMonitorAsyncResultEvent
545    */
546   void postScanMonitorAsyncResultEventFatal(uint16_t nanoappInstanceId,
547                                             bool success, bool enable,
548                                             uint8_t errorCode,
549                                             const void *cookie);
550 
551   /**
552    * Posts an event to a nanoapp indicating the result of a request for an
553    * active wifi scan.
554    *
555    * @param nanoappInstanceId The nanoapp instance ID to direct the event to.
556    * @param success If the request for a wifi resource was successful.
557    * @param errorCode The error code when success is set to false.
558    * @param cookie The cookie to be provided to the nanoapp. This is
559    *        round-tripped from the nanoapp to provide context.
560    *
561    * @return true if the event was successfully posted to the event loop.
562    */
563   bool postScanRequestAsyncResultEvent(uint16_t nanoappInstanceId, bool success,
564                                        uint8_t errorCode, const void *cookie);
565 
566   /**
567    * Calls through to postScanRequestAsyncResultEvent but invokes the
568    * FATAL_ERROR macro if the event is not posted successfully. This is used in
569    * asynchronous contexts where a nanoapp could be stuck waiting for a response
570    * but CHRE failed to enqueue one. For parameter details,
571    * @see postScanRequestAsyncResultEvent
572    */
573   void postScanRequestAsyncResultEventFatal(uint16_t nanoappInstanceId,
574                                             bool success, uint8_t errorCode,
575                                             const void *cookie);
576 
577   /**
578    * Posts a broadcast event containing the results of a wifi scan. Failure to
579    * post this event is a FATAL_ERROR. This is unrecoverable as the nanoapp will
580    * be stuck waiting for wifi scan results but there may be a gap.
581    *
582    * @param event the wifi scan event.
583    */
584   void postScanEventFatal(chreWifiScanEvent *event);
585 
586   /**
587    * Posts an event to a nanoapp indicating the async result of a NAN operation.
588    *
589    * @param nanoappInstanceId Instance ID of the nanoapp to post the event to.
590    * @param requestType A value in @ref enum chreWifiRequestType that indicates
591    *        the type of the NAN request this event is a response to.
592    * @param success true if the request was successful, false otherwise.
593    * @param errorCode A value in @ref enum chreError that indicates a failure
594    *        reason (if any, CHRE_ERROR_NONE indicates success) for the request.
595    * @param cookie A cookie that is round-tripped back to the nanoapp to
596    *        provide a context when making the request.
597    */
598   void postNanAsyncResultEvent(uint16_t nanoappInstanceId, uint8_t requestType,
599                                bool success, uint8_t errorCode,
600                                const void *cookie);
601 
602   /**
603    * Handles the result of a request to PlatformWifi to change the state of the
604    * scan monitor. See the handleScanMonitorStateChange method which may be
605    * called from any thread. This method is intended to be invoked on the CHRE
606    * event loop thread.
607    *
608    * @param enabled true if the result of the operation was an enabled scan
609    *        monitor.
610    * @param errorCode an error code that is provided to indicate success or what
611    *        type of error has occurred. See the chreError enum in the CHRE API
612    *        for additional details.
613    */
614   void handleScanMonitorStateChangeSync(bool enabled, uint8_t errorCode);
615 
616   /**
617    * Handles the result of a request to PlatformWifi to perform an active WiFi
618    * scan. See the handleScanResponse method which may be called from any
619    * thread. This method is intended to be invoked on the CHRE event loop
620    * thread.
621    *
622    * @param pending The result of the request was successful and the results
623    *        will be sent via the handleScanEvent method.
624    * @param errorCode an error code that is provided to indicate success or what
625    *        type of error has occurred. See the chreError enum in the CHRE API
626    *        for additional details.
627    */
628   void handleScanResponseSync(bool pending, uint8_t errorCode);
629 
630   /**
631    * Handles the result of a NAN subscription request.
632    *
633    * @param errorCode A value in @ref enum chrError that indicates the status
634    *        of the operation, with CHRE_ERROR_NONE indicating success.
635    * @param subscriptionId An identifier that is assigned to the subscribing
636    *        NAN service after a subscription request. This ID is only valid
637    *        if the errorCode is CHRE_ERROR_NONE.
638    */
639   void handleNanServiceIdentifierEventSync(uint8_t errorCode,
640                                            uint32_t subscriptionId);
641 
642   /**
643    * Handles the result of the successful discovery of a publishing service
644    * that matches the configuration specified by the subscription request.
645    *
646    * @param event Structure containing information specific to the publishing
647    *        service. CHRE retains ownership of the memory associated with this
648    *        structure until it releases it via a call to the function
649    *        freeNanDiscoveryEventCallback().
650    */
651   void handleNanServiceDiscoveryEventSync(
652       struct chreWifiNanDiscoveryEvent *event);
653 
654   /**
655    * Handles the event informing CHRE that a publishing service has gone away.
656    *
657    * @param subscriptionId The ID of the subscribing service which will be
658    *        informed of the publisher's disappearance.
659    * @param publisherId The ID of the publishing service that has gone away.
660    */
661   void handleNanServiceLostEventSync(uint32_t subscriptionId,
662                                      uint32_t publisherId);
663 
664   /**
665    * Handles the event informing CHRE that a subscription has been terminated.
666    *
667    * @param errorCode A value in @ref enum chreError that indicates the reason
668    *        for the service's subscription termination.
669    * @param subscriptionId The ID of the service whose subscription has ended.
670    */
671   void handleNanServiceTerminatedEventSync(uint8_t errorCode,
672                                            uint32_t subscriptionId);
673 
674   /**
675    * Handles the event informing CHRE the result of a subscription cancelation.
676    *
677    * @param errorCode A value in @ref enum chreError with CHRE_ERROR_NONE
678    *        indicating successful cancelation, an error code otherwise.
679    * @param subscriptionId The ID of the service whose subscription has been
680    *        canceled.
681    */
682   void handleNanServiceSubscriptionCanceledEventSync(uint8_t errorCode,
683                                                      uint32_t subscriptionId);
684 
685   /**
686    * Handles event informing CHRE whether NAN is available.
687    *
688    * @param available Whether NAN is available to use.
689    */
690   void handleNanAvailabilitySync(bool available);
691 
692   /**
693    * Sends CHRE_EVENT_WIFI_ASYNC_RESULT for the ranging request at the head
694    * of the pending queue.
695    *
696    * @param errorCode Indicates the overall result of the ranging operation
697    *
698    * @return true on success
699    */
700   bool postRangingAsyncResult(uint8_t errorCode);
701 
702   /**
703    * Keep issuing pending configure scan monitor request to the platform in
704    * queued order util a successful dispatch or the queue is empty
705    */
706   void dispatchQueuedConfigureScanMonitorRequests();
707 
708   /**
709    * Issues the pending scan requests to the platform in queued order until one
710    * dispatched successfully or the queue is empty.
711    *
712    * @param postAsyncResult if a dispatch failure should post a async result.
713    * @return true if successfully dispatched one request.
714    */
715   bool dispatchQueuedScanRequests(bool postAsyncResult);
716 
717   /**
718    * Issues the next pending ranging request to the platform.
719    *
720    * @return Result of PlatformWifi::requestRanging()
721    */
722   bool dispatchQueuedRangingRequest();
723 
724   /**
725    * Issues the next pending NAN ranging request to the platform.
726    */
727   bool dispatchQueuedNanSubscribeRequest();
728 
729   /**
730    * If a failure while dispatching the NAN subscribe requests, tries to
731    * dispatch it again until the first one succeeds.
732    */
733   void dispatchQueuedNanSubscribeRequestWithRetry();
734 
735   /**
736    * Processes the result of a ranging request within the context of the CHRE
737    * thread.
738    *
739    * @param errorCode Result of the ranging operation
740    * @param event On success, pointer to event data provided by platform
741    */
742   void handleRangingEventSync(uint8_t errorCode,
743                               struct chreWifiRangingEvent *event);
744 
745   /**
746    * Handles the releasing of a WiFi scan event and unsubscribes a nanoapp who
747    * has made an active request for a wifi scan from WiFi scan events in the
748    * future (if it has not subscribed to passive events).
749    *
750    * @param scanEvent The scan event to release.
751    */
752   void handleFreeWifiScanEvent(chreWifiScanEvent *scanEvent);
753 
754   /**
755    * Adds a wifi scan request log onto list possibly kicking earliest log out
756    * if full.
757    *
758    * @param nanoappInstanceId The instance Id of the requesting nanoapp
759    * @param params The chre wifi scan params
760    */
761   void addWifiScanRequestLog(uint16_t nanoappInstanceId,
762                              const chreWifiScanParams *params);
763 
764   /**
765    * Releases a wifi event (scan, ranging, NAN discovery) after nanoapps have
766    * consumed it.
767    *
768    * @param eventType the type of event being freed.
769    * @param eventData a pointer to the scan event to release.
770    */
771   static void freeWifiScanEventCallback(uint16_t eventType, void *eventData);
772   static void freeWifiRangingEventCallback(uint16_t eventType, void *eventData);
773   static void freeNanDiscoveryEventCallback(uint16_t eventType,
774                                             void *eventData);
775 
776   /**
777    * Copy a NAN subscription configuration to a pending NAN subscription
778    * request before dispatch.
779    *
780    * @param request The pending subscribe request being queued up for dispatch.
781    * @param config NAN service subscription configuration parameters.
782    * @return true if the copy was successful, false otherwise.
783    */
784   bool copyNanSubscribeConfigToRequest(
785       PendingNanSubscribeRequest &request,
786       const struct chreWifiNanSubscribeConfig *config);
787 
788   /**
789    * Rebuild a NAN subscription configuration from a dequed subscription
790    * request.
791    *
792    * @param request The pending NAN subscription request that was dequeued.
793    * @param config The subscription configuration that is to be built from
794    *        the pending request.
795    */
796   void buildNanSubscribeConfigFromRequest(
797       const PendingNanSubscribeRequest &request,
798       struct chreWifiNanSubscribeConfig *config);
799 
800   /**
801    * Scan through the nanoapp-subscription ID pair list to find the nanoapp
802    * that holds a subscription ID.
803    *
804    * @param subscriptionId The subscription ID that the nanoapp being searched
805    *        for owns.
806    * @return The instance ID of the nanoapp which owns the subscription ID if
807    *         it was found in the list, an invalid value otherwise.
808    */
809   bool getNappIdFromSubscriptionId(uint32_t subscriptionId,
810                                    uint16_t *nanoappInstanceId);
811 
812   /**
813    * Sends an AP (access point) or NAN ranging request to the platform.
814    *
815    * @param rangingType A value in WifiRequestManager::RangingType that denotes
816    *        the type of the ranging request.
817    * @param rangingParams The parameters of the ranging request.
818    */
819   bool requestRangingByType(RangingType rangingType, const void *rangingParams);
820 
821   /**
822    * Update a ranging request with the provided ranging parameters.
823    *
824    * @param rangingType A value in WifiRequestManager::RangingType that denotes
825    *        the type of the ranging request.
826    * @param request A pending ranging request which needs to be updated with the
827    *        provided ranging parameters.
828    * @param rangingParams The parameters of the ranging request.
829    */
830   bool updateRangingRequest(RangingType rangingType,
831                             PendingRangingRequest &request,
832                             const void *rangingParams);
833 
834   /**
835    * Send a pending AP or NAN ranging request to the platform.
836    *
837    * @param request A pending ranging request which needs to be updated with the
838    *        provided ranging parameters.
839    * @return true if the request was successfully sent, false otherwise.
840    */
841   bool sendRangingRequest(PendingRangingRequest &request);
842 
843   /**
844    * Helper function to determine if all the settings required for a ranging
845    * request (viz. Location, WiFi-available) are enabled.
846    *
847    * @return true if the necessary settings are enabled, false otherwise.
848    */
849   bool areRequiredSettingsEnabled();
850 
851   /**
852    * Helper function to cancel all existing nanoapp NAN subscriptions and
853    * inform the nanoapps owning the subscriptions of the cancelation with
854    * a NAN session terminated event.
855    */
856   void cancelNanSubscriptionsAndInformNanoapps();
857 
858   /**
859    * Helper function to cancel all pending NAN subscription requests and
860    * inform the nanoapps making the request of the cancelation with a WiFi
861    * async result event.
862    */
863   void cancelNanPendingRequestsAndInformNanoapps();
864 
865   /**
866    * Sends a config request to the host to enable or disable NAN functionality.
867    * The function checks if a request is already pending or if the pending
868    * request type opposes the current request and only then sends the request
869    * across to avoid duplicate requests.
870    *
871    * @param enable Indicates if a NAN enable or disable is being requested.
872    */
873   void sendNanConfiguration(bool enable);
874 
875   /**
876    * Invoked on no response for a configure scan monitor request in the expected
877    * window.
878    */
879   void handleConfigureScanMonitorTimeout();
880 
881   /**
882    * Sets up the system timer that invokes handleConfigureScanMonitorTimeout
883    * when the PAL does not respond to configure scan monitor request on time.
884    *
885    * @return TimerHandle that can be used later to cancel the timer if the PAL
886    * has responded in the expected time window.
887    */
888   TimerHandle setConfigureScanMonitorTimer();
889 
890   /**
891    * Invoked on no response for a ranging request in the expected window.
892    */
893   void handleRangingRequestTimeout();
894 
895   /**
896    * Sets up the system timer that invokes handleRangingRequestTimeout when the
897    * PAL does not respond on time.
898    *
899    * @return TimerHandle that can be used later to cancel the timer if the PAL
900    * has responded in the expected time window.
901    */
902   TimerHandle setRangingRequestTimer();
903 
904   /**
905    * Invoked on no response for a scan request in the expected window.
906    */
907   void handleScanRequestTimeout();
908 
909   /**
910    * Sets up the system timer that invokes handleScanRequestTimeout when the
911    * PAL does not respond on time.
912    *
913    * @return TimerHandle that can be used later to cancel the timer if the PAL
914    * has responded in the expected time window.
915    */
916   TimerHandle setScanRequestTimer();
917 
918   /**
919    * Clears the system timer tracking timeout of the scan request. Should be
920    * called after scan response and all pending data have been delivered.
921    */
922   void cancelScanRequestTimer();
923 };
924 
925 }  // namespace chre
926 
927 #endif  // CHRE_WIFI_SUPPORT_ENABLED
928 
929 #endif  // CHRE_CORE_WIFI_REQUEST_MANAGER_H_
930