wifi_world.cc 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. * Copyright (C) 2017 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. #include <chre.h>
  17. #include <cinttypes>
  18. #include "chre/util/macros.h"
  19. #include "chre/util/nanoapp/log.h"
  20. #include "chre/util/time.h"
  21. #include "chre/util/nanoapp/wifi.h"
  22. using chre::kOneMillisecondInNanoseconds;
  23. using chre::Nanoseconds;
  24. using chre::Seconds;
  25. #define LOG_TAG "[WifiWorld]"
  26. //#define WIFI_WORLD_VERBOSE_WIFI_RESULT_LOGS
  27. #ifdef CHRE_NANOAPP_INTERNAL
  28. namespace chre {
  29. namespace {
  30. #endif // CHRE_NANOAPP_INTERNAL
  31. namespace {
  32. //! A dummy cookie to pass into the configure scan monitoring async request.
  33. constexpr uint32_t kScanMonitoringCookie = 0x1337;
  34. //! A dummy cookie to pass into request scan async.
  35. constexpr uint32_t kOnDemandScanCookie = 0xcafe;
  36. //! The interval for on-demand wifi scans.
  37. constexpr Nanoseconds kWifiScanInterval = Nanoseconds(Seconds(10));
  38. //! A handle for the cyclic timer to request periodic on-demand wifi-scans.
  39. uint32_t gWifiScanTimerHandle;
  40. //! A global instance of wifi capabilities to use when reqeuesting wifi
  41. //! functionality. This is populated at startup.
  42. uint32_t gWifiCapabilities;
  43. //! The last time in nanoseconds a wifi scan request was sucessfully made.
  44. uint64_t gLastRequestTimeNs = 0;
  45. //! True if CHRE_WIFI_REQUEST_TYPE_REQUEST_SCAN mode is requested.
  46. bool gPendingOnDemandScan = false;
  47. //! Accumulating count of the scan request results so far.
  48. uint32_t gScanResultAcc = 0;
  49. //! The currently requested on-demand wifi scan parameters.
  50. chreWifiScanParams gWifiScanParams = {};
  51. //! The sequence of on-demand wifi scan types to request for.
  52. constexpr chreWifiScanType gWifiScanTypes[] = {
  53. CHRE_WIFI_SCAN_TYPE_ACTIVE,
  54. CHRE_WIFI_SCAN_TYPE_ACTIVE_PLUS_PASSIVE_DFS,
  55. CHRE_WIFI_SCAN_TYPE_PASSIVE
  56. };
  57. //! The index of the next wifi scan type to request for.
  58. uint8_t gScanTypeIndex = 0;
  59. /**
  60. * Logs a CHRE wifi scan result.
  61. *
  62. * @param result the scan result to log.
  63. */
  64. void logChreWifiResult(const chreWifiScanResult& result) {
  65. const char *ssidStr = "<non-printable>";
  66. char ssidBuffer[chre::kMaxSsidStrLen];
  67. if (result.ssidLen == 0) {
  68. ssidStr = "<empty>";
  69. } else if (chre::parseSsidToStr(ssidBuffer, sizeof(ssidBuffer),
  70. result.ssid, result.ssidLen)) {
  71. ssidStr = ssidBuffer;
  72. }
  73. LOGI("Found network with SSID: %s", ssidStr);
  74. #ifdef WIFI_WORLD_VERBOSE_WIFI_RESULT_LOGS
  75. const char *bssidStr = "<non-printable>";
  76. char bssidBuffer[chre::kBssidStrLen];
  77. if (chre::parseBssidToStr(result.bssid, bssidBuffer, sizeof(bssidBuffer))) {
  78. bssidStr = bssidBuffer;
  79. }
  80. LOGI(" age (ms): %" PRIu32, result.ageMs);
  81. LOGI(" capability info: %" PRIx16, result.capabilityInfo);
  82. LOGI(" bssid: %s", bssidStr);
  83. LOGI(" flags: %" PRIx8, result.flags);
  84. LOGI(" rssi: %" PRId8 "dBm", result.rssi);
  85. LOGI(" band: %s (%" PRIu8 ")",
  86. chre::parseChreWifiBand(result.band), result.band);
  87. LOGI(" primary channel: %" PRIu32, result.primaryChannel);
  88. LOGI(" center frequency primary: %" PRIu32, result.centerFreqPrimary);
  89. LOGI(" center frequency secondary: %" PRIu32, result.centerFreqSecondary);
  90. LOGI(" channel width: %" PRIu8, result.channelWidth);
  91. LOGI(" security mode: %" PRIx8, result.securityMode);
  92. #endif // WIFI_WORLD_VERBOSE_WIFI_RESULT_LOGS
  93. }
  94. /**
  95. * Requests a delayed wifi scan using a one-shot timer. The interval is
  96. * specified as a constant at the top of this file.
  97. */
  98. void requestDelayedWifiScan() {
  99. if (gWifiCapabilities & CHRE_WIFI_CAPABILITIES_ON_DEMAND_SCAN) {
  100. // Schedule a timer to send an active wifi scan.
  101. gWifiScanTimerHandle = chreTimerSet(kWifiScanInterval.toRawNanoseconds(),
  102. &gWifiScanTimerHandle /* data */,
  103. true /* oneShot */);
  104. if (gWifiScanTimerHandle == CHRE_TIMER_INVALID) {
  105. LOGE("Failed to set timer for delayed wifi scan");
  106. } else {
  107. LOGI("Set a timer to request a WiFi scan");
  108. }
  109. }
  110. }
  111. /**
  112. * Handles the result of an asynchronous request for a wifi resource.
  113. *
  114. * @param result a pointer to the event structure containing the result of the
  115. * request.
  116. */
  117. void handleWifiAsyncResult(const chreAsyncResult *result) {
  118. if (result->requestType == CHRE_WIFI_REQUEST_TYPE_CONFIGURE_SCAN_MONITOR) {
  119. if (result->success) {
  120. LOGI("Successfully requested wifi scan monitoring");
  121. } else {
  122. LOGE("Error requesting wifi scan monitoring with %" PRIu8,
  123. result->errorCode);
  124. }
  125. if (result->cookie != &kScanMonitoringCookie) {
  126. LOGE("Scan monitoring request cookie mismatch");
  127. }
  128. } else if (result->requestType == CHRE_WIFI_REQUEST_TYPE_REQUEST_SCAN) {
  129. uint64_t timeSinceRequest = chreGetTime() - gLastRequestTimeNs;
  130. if (result->success) {
  131. LOGI("Successfully requested an on-demand wifi scan (response time %"
  132. PRIu64 " ms)", timeSinceRequest / kOneMillisecondInNanoseconds);
  133. gPendingOnDemandScan = true;
  134. } else {
  135. LOGE("Error requesting an on-demand wifi scan with %" PRIu8,
  136. result->errorCode);
  137. }
  138. if (result->cookie != &kOnDemandScanCookie) {
  139. LOGE("On-demand scan cookie mismatch");
  140. }
  141. requestDelayedWifiScan();
  142. } else {
  143. LOGE("Received invalid async result");
  144. }
  145. }
  146. /**
  147. * Handles a wifi scan event.
  148. *
  149. * @param event a pointer to the details of the wifi scan event.
  150. */
  151. void handleWifiScanEvent(const chreWifiScanEvent *event) {
  152. LOGI("Received Wifi scan event of type %" PRIu8 " with %" PRIu8
  153. " results at %" PRIu64 "ns", event->scanType, event->resultCount,
  154. event->referenceTime);
  155. if (gPendingOnDemandScan) {
  156. uint64_t timeSinceRequest = chreGetTime() - gLastRequestTimeNs;
  157. LOGI("Time since scan request = %" PRIu64 " ms",
  158. timeSinceRequest / kOneMillisecondInNanoseconds);
  159. if (event->scanType != gWifiScanParams.scanType) {
  160. LOGE("Invalid scan event type (expected %" PRIu8 ", received %" PRIu8 ")",
  161. gWifiScanParams.scanType, event->scanType);
  162. }
  163. gScanResultAcc += event->resultCount;
  164. if (gScanResultAcc >= event->resultTotal) {
  165. gPendingOnDemandScan = false;
  166. gScanResultAcc = 0;
  167. }
  168. }
  169. for (uint8_t i = 0; i < event->resultCount; i++) {
  170. const chreWifiScanResult& result = event->results[i];
  171. logChreWifiResult(result);
  172. }
  173. }
  174. /**
  175. * Handles a timer event.
  176. *
  177. * @param eventData The cookie passed to the timer request.
  178. */
  179. void handleTimerEvent(const void *eventData) {
  180. const uint32_t *timerHandle = static_cast<const uint32_t *>(eventData);
  181. if (*timerHandle == gWifiScanTimerHandle) {
  182. gWifiScanParams.scanType = gWifiScanTypes[gScanTypeIndex];
  183. gWifiScanParams.maxScanAgeMs = 5000; // 5 seconds
  184. gWifiScanParams.frequencyListLen = 0;
  185. gWifiScanParams.ssidListLen = 0;
  186. gScanTypeIndex = (gScanTypeIndex + 1) % ARRAY_SIZE(gWifiScanTypes);
  187. if (chreWifiRequestScanAsync(&gWifiScanParams, &kOnDemandScanCookie)) {
  188. LOGI("Requested a wifi scan successfully");
  189. gLastRequestTimeNs = chreGetTime();
  190. } else {
  191. LOGE("Failed to request a wifi scan");
  192. }
  193. } else {
  194. LOGE("Received invalid timer handle");
  195. }
  196. }
  197. } // namespace
  198. bool nanoappStart() {
  199. LOGI("App started as instance %" PRIu32, chreGetInstanceId());
  200. gWifiCapabilities = chreWifiGetCapabilities();
  201. LOGI("Detected WiFi support as: 0x%" PRIx32, gWifiCapabilities);
  202. if (gWifiCapabilities & CHRE_WIFI_CAPABILITIES_SCAN_MONITORING) {
  203. if (chreWifiConfigureScanMonitorAsync(true, &kScanMonitoringCookie)) {
  204. LOGI("Scan monitor enable request successful");
  205. } else {
  206. LOGE("Error sending scan monitoring request");
  207. }
  208. }
  209. requestDelayedWifiScan();
  210. return true;
  211. }
  212. void nanoappHandleEvent(uint32_t senderInstanceId,
  213. uint16_t eventType,
  214. const void *eventData) {
  215. switch (eventType) {
  216. case CHRE_EVENT_WIFI_ASYNC_RESULT:
  217. handleWifiAsyncResult(static_cast<const chreAsyncResult *>(eventData));
  218. break;
  219. case CHRE_EVENT_WIFI_SCAN_RESULT:
  220. handleWifiScanEvent(static_cast<const chreWifiScanEvent *>(eventData));
  221. break;
  222. case CHRE_EVENT_TIMER:
  223. handleTimerEvent(eventData);
  224. break;
  225. default:
  226. LOGW("Unhandled event type %" PRIu16, eventType);
  227. }
  228. }
  229. void nanoappEnd() {
  230. LOGI("Wifi world app stopped");
  231. }
  232. #ifdef CHRE_NANOAPP_INTERNAL
  233. } // anonymous namespace
  234. } // namespace chre
  235. #include "chre/util/nanoapp/app_id.h"
  236. #include "chre/platform/static_nanoapp_init.h"
  237. CHRE_STATIC_NANOAPP_INIT(WifiWorld, chre::kWifiWorldAppId, 0);
  238. #endif // CHRE_NANOAPP_INTERNAL