1 /* 2 * Copyright (C) 2011 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 package com.android.server.wifi; 18 19 import android.content.BroadcastReceiver; 20 import android.content.ContentResolver; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.content.IntentFilter; 24 import android.database.ContentObserver; 25 import android.net.ConnectivityManager; 26 import android.net.LinkProperties; 27 import android.net.NetworkInfo; 28 import android.net.wifi.RssiPacketCountInfo; 29 import android.net.wifi.SupplicantState; 30 import android.net.wifi.WifiInfo; 31 import android.net.wifi.WifiManager; 32 import android.os.Message; 33 import android.os.Messenger; 34 import android.os.SystemClock; 35 import android.provider.Settings; 36 import android.util.LruCache; 37 38 import com.android.internal.util.AsyncChannel; 39 import com.android.internal.util.Protocol; 40 import com.android.internal.util.State; 41 import com.android.internal.util.StateMachine; 42 43 import java.io.FileDescriptor; 44 import java.io.PrintWriter; 45 import java.text.DecimalFormat; 46 47 /** 48 * WifiWatchdogStateMachine monitors the connection to a WiFi network. When WiFi 49 * connects at L2 layer, the beacons from access point reach the device and it 50 * can maintain a connection, but the application connectivity can be flaky (due 51 * to bigger packet size exchange). 52 * <p> 53 * We now monitor the quality of the last hop on WiFi using packet loss ratio as 54 * an indicator to decide if the link is good enough to switch to Wi-Fi as the 55 * uplink. 56 * <p> 57 * When WiFi is connected, the WiFi watchdog keeps sampling the RSSI and the 58 * instant packet loss, and record it as per-AP loss-to-rssi statistics. When 59 * the instant packet loss is higher than a threshold, the WiFi watchdog sends a 60 * poor link notification to avoid WiFi connection temporarily. 61 * <p> 62 * While WiFi is being avoided, the WiFi watchdog keep watching the RSSI to 63 * bring the WiFi connection back. Once the RSSI is high enough to achieve a 64 * lower packet loss, a good link detection is sent such that the WiFi 65 * connection become available again. 66 * <p> 67 * BSSID roaming has been taken into account. When user is moving across 68 * multiple APs, the WiFi watchdog will detect that and keep watching the 69 * currently connected AP. 70 * <p> 71 * Power impact should be minimal since much of the measurement relies on 72 * passive statistics already being tracked at the driver and the polling is 73 * done when screen is turned on and the RSSI is in a certain range. 74 * 75 * @hide 76 */ 77 public class WifiWatchdogStateMachine extends StateMachine { 78 79 private static final boolean DBG = false; 80 81 private static final int BASE = Protocol.BASE_WIFI_WATCHDOG; 82 83 /* Internal events */ 84 private static final int EVENT_WATCHDOG_TOGGLED = BASE + 1; 85 private static final int EVENT_NETWORK_STATE_CHANGE = BASE + 2; 86 private static final int EVENT_RSSI_CHANGE = BASE + 3; 87 private static final int EVENT_SUPPLICANT_STATE_CHANGE = BASE + 4; 88 private static final int EVENT_WIFI_RADIO_STATE_CHANGE = BASE + 5; 89 private static final int EVENT_WATCHDOG_SETTINGS_CHANGE = BASE + 6; 90 private static final int EVENT_BSSID_CHANGE = BASE + 7; 91 private static final int EVENT_SCREEN_ON = BASE + 8; 92 private static final int EVENT_SCREEN_OFF = BASE + 9; 93 94 /* Internal messages */ 95 private static final int CMD_RSSI_FETCH = BASE + 11; 96 97 /* Notifications from/to WifiStateMachine */ 98 static final int POOR_LINK_DETECTED = BASE + 21; 99 static final int GOOD_LINK_DETECTED = BASE + 22; 100 101 /* 102 * RSSI levels as used by notification icon 103 * Level 4 -55 <= RSSI 104 * Level 3 -66 <= RSSI < -55 105 * Level 2 -77 <= RSSI < -67 106 * Level 1 -88 <= RSSI < -78 107 * Level 0 RSSI < -88 108 */ 109 110 /** 111 * WiFi link statistics is monitored and recorded actively below this threshold. 112 * <p> 113 * Larger threshold is more adaptive but increases sampling cost. 114 */ 115 private static final int LINK_MONITOR_LEVEL_THRESHOLD = WifiManager.RSSI_LEVELS - 1; 116 117 /** 118 * Remember packet loss statistics of how many BSSIDs. 119 * <p> 120 * Larger size is usually better but requires more space. 121 */ 122 private static final int BSSID_STAT_CACHE_SIZE = 20; 123 124 /** 125 * RSSI range of a BSSID statistics. 126 * Within the range, (RSSI -> packet loss %) mappings are stored. 127 * <p> 128 * Larger range is usually better but requires more space. 129 */ 130 private static final int BSSID_STAT_RANGE_LOW_DBM = -105; 131 132 /** 133 * See {@link #BSSID_STAT_RANGE_LOW_DBM}. 134 */ 135 private static final int BSSID_STAT_RANGE_HIGH_DBM = -45; 136 137 /** 138 * How many consecutive empty data point to trigger a empty-cache detection. 139 * In this case, a preset/default loss value (function on RSSI) is used. 140 * <p> 141 * In normal uses, some RSSI values may never be seen due to channel randomness. 142 * However, the size of such empty RSSI chunk in normal use is generally 1~2. 143 */ 144 private static final int BSSID_STAT_EMPTY_COUNT = 3; 145 146 /** 147 * Sample interval for packet loss statistics, in msec. 148 * <p> 149 * Smaller interval is more accurate but increases sampling cost (battery consumption). 150 */ 151 private static final long LINK_SAMPLING_INTERVAL_MS = 1 * 1000; 152 153 /** 154 * Coefficients (alpha) for moving average for packet loss tracking. 155 * Must be within (0.0, 1.0). 156 * <p> 157 * Equivalent number of samples: N = 2 / alpha - 1 . 158 * We want the historic loss to base on more data points to be statistically reliable. 159 * We want the current instant loss to base on less data points to be responsive. 160 */ 161 private static final double EXP_COEFFICIENT_RECORD = 0.1; 162 163 /** 164 * See {@link #EXP_COEFFICIENT_RECORD}. 165 */ 166 private static final double EXP_COEFFICIENT_MONITOR = 0.5; 167 168 /** 169 * Thresholds for sending good/poor link notifications, in packet loss %. 170 * Good threshold must be smaller than poor threshold. 171 * Use smaller poor threshold to avoid WiFi more aggressively. 172 * Use smaller good threshold to bring back WiFi more conservatively. 173 * <p> 174 * When approaching the boundary, loss ratio jumps significantly within a few dBs. 175 * 50% loss threshold is a good balance between accuracy and reponsiveness. 176 * <=10% good threshold is a safe value to avoid jumping back to WiFi too easily. 177 */ 178 private static final double POOR_LINK_LOSS_THRESHOLD = 0.5; 179 180 /** 181 * See {@link #POOR_LINK_LOSS_THRESHOLD}. 182 */ 183 private static final double GOOD_LINK_LOSS_THRESHOLD = 0.1; 184 185 /** 186 * Number of samples to confirm before sending a poor link notification. 187 * Response time = confirm_count * sample_interval . 188 * <p> 189 * A smaller threshold improves response speed but may suffer from randomness. 190 * According to experiments, 3~5 are good values to achieve a balance. 191 * These parameters should be tuned along with {@link #LINK_SAMPLING_INTERVAL_MS}. 192 */ 193 private static final int POOR_LINK_SAMPLE_COUNT = 3; 194 195 /** 196 * Minimum volume (converted from pkt/sec) to detect a poor link, to avoid randomness. 197 * <p> 198 * According to experiments, 1pkt/sec is too sensitive but 3pkt/sec is slightly unresponsive. 199 */ 200 private static final double POOR_LINK_MIN_VOLUME = 2.0 * LINK_SAMPLING_INTERVAL_MS / 1000.0; 201 202 /** 203 * When a poor link is detected, we scan over this range (based on current 204 * poor link RSSI) for a target RSSI that satisfies a target packet loss. 205 * Refer to {@link #GOOD_LINK_TARGET}. 206 * <p> 207 * We want range_min not too small to avoid jumping back to WiFi too easily. 208 */ 209 private static final int GOOD_LINK_RSSI_RANGE_MIN = 3; 210 211 /** 212 * See {@link #GOOD_LINK_RSSI_RANGE_MIN}. 213 */ 214 private static final int GOOD_LINK_RSSI_RANGE_MAX = 20; 215 216 /** 217 * Adaptive good link target to avoid flapping. 218 * When a poor link is detected, a good link target is calculated as follows: 219 * <p> 220 * targetRSSI = min { rssi | loss(rssi) < GOOD_LINK_LOSS_THRESHOLD } + rssi_adj[i], 221 * where rssi is within the above GOOD_LINK_RSSI_RANGE. 222 * targetCount = sample_count[i] . 223 * <p> 224 * While WiFi is being avoided, we keep monitoring its signal strength. 225 * Good link notification is sent when we see current RSSI >= targetRSSI 226 * for targetCount consecutive times. 227 * <p> 228 * Index i is incremented each time after a poor link detection. 229 * Index i is decreased to at most k if the last poor link was at lease reduce_time[k] ago. 230 * <p> 231 * Intuitively, larger index i makes it more difficult to get back to WiFi, avoiding flapping. 232 * In experiments, (+9 dB / 30 counts) makes it quite difficult to achieve. 233 * Avoid using it unless flapping is really bad (say, last poor link is < 1 min ago). 234 */ 235 private static final GoodLinkTarget[] GOOD_LINK_TARGET = { 236 /* rssi_adj, sample_count, reduce_time */ 237 new GoodLinkTarget( 0, 3, 30 * 60000 ), 238 new GoodLinkTarget( 3, 5, 5 * 60000 ), 239 new GoodLinkTarget( 6, 10, 1 * 60000 ), 240 new GoodLinkTarget( 9, 30, 0 * 60000 ), 241 }; 242 243 /** 244 * The max time to avoid a BSSID, to prevent avoiding forever. 245 * If current RSSI is at least min_rssi[i], the max avoidance time is at most max_time[i] 246 * <p> 247 * It is unusual to experience high packet loss at high RSSI. Something unusual must be 248 * happening (e.g. strong interference). For higher signal strengths, we set the avoidance 249 * time to be low to allow for quick turn around from temporary interference. 250 * <p> 251 * See {@link BssidStatistics#poorLinkDetected}. 252 */ 253 private static final MaxAvoidTime[] MAX_AVOID_TIME = { 254 /* max_time, min_rssi */ 255 new MaxAvoidTime( 30 * 60000, -200 ), 256 new MaxAvoidTime( 5 * 60000, -70 ), 257 new MaxAvoidTime( 0 * 60000, -55 ), 258 }; 259 260 /* Framework related */ 261 private Context mContext; 262 private ContentResolver mContentResolver; 263 private WifiManager mWifiManager; 264 private IntentFilter mIntentFilter; 265 private BroadcastReceiver mBroadcastReceiver; 266 private AsyncChannel mWsmChannel = new AsyncChannel(); 267 private WifiInfo mWifiInfo; 268 private LinkProperties mLinkProperties; 269 270 /* System settingss related */ 271 private static boolean sWifiOnly = false; 272 private boolean mPoorNetworkDetectionEnabled; 273 274 /* Poor link detection related */ 275 private LruCache<String, BssidStatistics> mBssidCache = 276 new LruCache<String, BssidStatistics>(BSSID_STAT_CACHE_SIZE); 277 private int mRssiFetchToken = 0; 278 private int mCurrentSignalLevel; 279 private BssidStatistics mCurrentBssid; 280 private VolumeWeightedEMA mCurrentLoss; 281 private boolean mIsScreenOn = true; 282 private static double sPresetLoss[]; 283 284 /* WiFi watchdog state machine related */ 285 private DefaultState mDefaultState = new DefaultState(); 286 private WatchdogDisabledState mWatchdogDisabledState = new WatchdogDisabledState(); 287 private WatchdogEnabledState mWatchdogEnabledState = new WatchdogEnabledState(); 288 private NotConnectedState mNotConnectedState = new NotConnectedState(); 289 private VerifyingLinkState mVerifyingLinkState = new VerifyingLinkState(); 290 private ConnectedState mConnectedState = new ConnectedState(); 291 private OnlineWatchState mOnlineWatchState = new OnlineWatchState(); 292 private LinkMonitoringState mLinkMonitoringState = new LinkMonitoringState(); 293 private OnlineState mOnlineState = new OnlineState(); 294 295 /** 296 * STATE MAP 297 * Default 298 * / \ 299 * Disabled Enabled 300 * / \ \ 301 * NotConnected Verifying Connected 302 * /---------\ 303 * (all other states) 304 */ 305 private WifiWatchdogStateMachine(Context context, Messenger dstMessenger) { 306 super("WifiWatchdogStateMachine"); 307 mContext = context; 308 mContentResolver = context.getContentResolver(); 309 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 310 311 mWsmChannel.connectSync(mContext, getHandler(), dstMessenger); 312 313 setupNetworkReceiver(); 314 315 // the content observer to listen needs a handler 316 registerForSettingsChanges(); 317 registerForWatchdogToggle(); 318 addState(mDefaultState); 319 addState(mWatchdogDisabledState, mDefaultState); 320 addState(mWatchdogEnabledState, mDefaultState); 321 addState(mNotConnectedState, mWatchdogEnabledState); 322 addState(mVerifyingLinkState, mWatchdogEnabledState); 323 addState(mConnectedState, mWatchdogEnabledState); 324 addState(mOnlineWatchState, mConnectedState); 325 addState(mLinkMonitoringState, mConnectedState); 326 addState(mOnlineState, mConnectedState); 327 328 if (isWatchdogEnabled()) { 329 setInitialState(mNotConnectedState); 330 } else { 331 setInitialState(mWatchdogDisabledState); 332 } 333 setLogRecSize(25); 334 setLogOnlyTransitions(true); 335 updateSettings(); 336 } 337 338 public static WifiWatchdogStateMachine makeWifiWatchdogStateMachine(Context context, Messenger dstMessenger) { 339 ContentResolver contentResolver = context.getContentResolver(); 340 341 ConnectivityManager cm = (ConnectivityManager) context.getSystemService( 342 Context.CONNECTIVITY_SERVICE); 343 sWifiOnly = (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false); 344 345 // Watchdog is always enabled. Poor network detection can be seperately turned on/off 346 // TODO: Remove this setting & clean up state machine since we always have 347 // watchdog in an enabled state 348 putSettingsGlobalBoolean(contentResolver, Settings.Global.WIFI_WATCHDOG_ON, true); 349 350 WifiWatchdogStateMachine wwsm = new WifiWatchdogStateMachine(context, dstMessenger); 351 wwsm.start(); 352 return wwsm; 353 } 354 355 private void setupNetworkReceiver() { 356 mBroadcastReceiver = new BroadcastReceiver() { 357 @Override 358 public void onReceive(Context context, Intent intent) { 359 String action = intent.getAction(); 360 if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) { 361 obtainMessage(EVENT_RSSI_CHANGE, 362 intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, -200), 0).sendToTarget(); 363 } else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { 364 sendMessage(EVENT_SUPPLICANT_STATE_CHANGE, intent); 365 } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { 366 sendMessage(EVENT_NETWORK_STATE_CHANGE, intent); 367 } else if (action.equals(Intent.ACTION_SCREEN_ON)) { 368 sendMessage(EVENT_SCREEN_ON); 369 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 370 sendMessage(EVENT_SCREEN_OFF); 371 } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { 372 sendMessage(EVENT_WIFI_RADIO_STATE_CHANGE,intent.getIntExtra( 373 WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)); 374 } 375 } 376 }; 377 378 mIntentFilter = new IntentFilter(); 379 mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 380 mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 381 mIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); 382 mIntentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); 383 mIntentFilter.addAction(Intent.ACTION_SCREEN_ON); 384 mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); 385 mContext.registerReceiver(mBroadcastReceiver, mIntentFilter); 386 } 387 388 /** 389 * Observes the watchdog on/off setting, and takes action when changed. 390 */ 391 private void registerForWatchdogToggle() { 392 ContentObserver contentObserver = new ContentObserver(this.getHandler()) { 393 @Override 394 public void onChange(boolean selfChange) { 395 sendMessage(EVENT_WATCHDOG_TOGGLED); 396 } 397 }; 398 399 mContext.getContentResolver().registerContentObserver( 400 Settings.Global.getUriFor(Settings.Global.WIFI_WATCHDOG_ON), 401 false, contentObserver); 402 } 403 404 /** 405 * Observes watchdogs secure setting changes. 406 */ 407 private void registerForSettingsChanges() { 408 ContentObserver contentObserver = new ContentObserver(this.getHandler()) { 409 @Override 410 public void onChange(boolean selfChange) { 411 sendMessage(EVENT_WATCHDOG_SETTINGS_CHANGE); 412 } 413 }; 414 415 mContext.getContentResolver().registerContentObserver( 416 Settings.Global.getUriFor(Settings.Global.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED), 417 false, contentObserver); 418 } 419 420 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 421 super.dump(fd, pw, args); 422 pw.println("mWifiInfo: [" + mWifiInfo + "]"); 423 pw.println("mLinkProperties: [" + mLinkProperties + "]"); 424 pw.println("mCurrentSignalLevel: [" + mCurrentSignalLevel + "]"); 425 pw.println("mPoorNetworkDetectionEnabled: [" + mPoorNetworkDetectionEnabled + "]"); 426 } 427 428 private boolean isWatchdogEnabled() { 429 boolean ret = getSettingsGlobalBoolean( 430 mContentResolver, Settings.Global.WIFI_WATCHDOG_ON, true); 431 if (DBG) logd("Watchdog enabled " + ret); 432 return ret; 433 } 434 435 private void updateSettings() { 436 if (DBG) logd("Updating secure settings"); 437 438 // disable poor network avoidance 439 if (sWifiOnly) { 440 logd("Disabling poor network avoidance for wi-fi only device"); 441 mPoorNetworkDetectionEnabled = false; 442 } else { 443 mPoorNetworkDetectionEnabled = getSettingsGlobalBoolean(mContentResolver, 444 Settings.Global.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED, 445 WifiManager.DEFAULT_POOR_NETWORK_AVOIDANCE_ENABLED); 446 } 447 } 448 449 /** 450 * Default state, guard for unhandled messages. 451 */ 452 class DefaultState extends State { 453 @Override 454 public void enter() { 455 if (DBG) logd(getName()); 456 } 457 458 @Override 459 public boolean processMessage(Message msg) { 460 switch (msg.what) { 461 case EVENT_WATCHDOG_SETTINGS_CHANGE: 462 updateSettings(); 463 if (DBG) logd("Updating wifi-watchdog secure settings"); 464 break; 465 case EVENT_RSSI_CHANGE: 466 mCurrentSignalLevel = calculateSignalLevel(msg.arg1); 467 break; 468 case EVENT_WIFI_RADIO_STATE_CHANGE: 469 case EVENT_NETWORK_STATE_CHANGE: 470 case EVENT_SUPPLICANT_STATE_CHANGE: 471 case EVENT_BSSID_CHANGE: 472 case CMD_RSSI_FETCH: 473 case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED: 474 case WifiManager.RSSI_PKTCNT_FETCH_FAILED: 475 // ignore 476 break; 477 case EVENT_SCREEN_ON: 478 mIsScreenOn = true; 479 break; 480 case EVENT_SCREEN_OFF: 481 mIsScreenOn = false; 482 break; 483 default: 484 loge("Unhandled message " + msg + " in state " + getCurrentState().getName()); 485 break; 486 } 487 return HANDLED; 488 } 489 } 490 491 /** 492 * WiFi watchdog is disabled by the setting. 493 */ 494 class WatchdogDisabledState extends State { 495 @Override 496 public void enter() { 497 if (DBG) logd(getName()); 498 } 499 500 @Override 501 public boolean processMessage(Message msg) { 502 switch (msg.what) { 503 case EVENT_WATCHDOG_TOGGLED: 504 if (isWatchdogEnabled()) 505 transitionTo(mNotConnectedState); 506 return HANDLED; 507 case EVENT_NETWORK_STATE_CHANGE: 508 Intent intent = (Intent) msg.obj; 509 NetworkInfo networkInfo = (NetworkInfo) 510 intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 511 512 switch (networkInfo.getDetailedState()) { 513 case VERIFYING_POOR_LINK: 514 if (DBG) logd("Watchdog disabled, verify link"); 515 sendLinkStatusNotification(true); 516 break; 517 default: 518 break; 519 } 520 break; 521 } 522 return NOT_HANDLED; 523 } 524 } 525 526 /** 527 * WiFi watchdog is enabled by the setting. 528 */ 529 class WatchdogEnabledState extends State { 530 @Override 531 public void enter() { 532 if (DBG) logd(getName()); 533 } 534 535 @Override 536 public boolean processMessage(Message msg) { 537 Intent intent; 538 switch (msg.what) { 539 case EVENT_WATCHDOG_TOGGLED: 540 if (!isWatchdogEnabled()) 541 transitionTo(mWatchdogDisabledState); 542 break; 543 544 case EVENT_NETWORK_STATE_CHANGE: 545 intent = (Intent) msg.obj; 546 NetworkInfo networkInfo = 547 (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 548 if (DBG) logd("Network state change " + networkInfo.getDetailedState()); 549 550 mWifiInfo = (WifiInfo) intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); 551 updateCurrentBssid(mWifiInfo != null ? mWifiInfo.getBSSID() : null); 552 553 switch (networkInfo.getDetailedState()) { 554 case VERIFYING_POOR_LINK: 555 mLinkProperties = (LinkProperties) intent.getParcelableExtra( 556 WifiManager.EXTRA_LINK_PROPERTIES); 557 if (mPoorNetworkDetectionEnabled) { 558 if (mWifiInfo == null || mCurrentBssid == null) { 559 loge("Ignore, wifiinfo " + mWifiInfo +" bssid " + mCurrentBssid); 560 sendLinkStatusNotification(true); 561 } else { 562 transitionTo(mVerifyingLinkState); 563 } 564 } else { 565 sendLinkStatusNotification(true); 566 } 567 break; 568 case CONNECTED: 569 transitionTo(mOnlineWatchState); 570 break; 571 default: 572 transitionTo(mNotConnectedState); 573 break; 574 } 575 break; 576 577 case EVENT_SUPPLICANT_STATE_CHANGE: 578 intent = (Intent) msg.obj; 579 SupplicantState supplicantState = (SupplicantState) intent.getParcelableExtra( 580 WifiManager.EXTRA_NEW_STATE); 581 if (supplicantState == SupplicantState.COMPLETED) { 582 mWifiInfo = mWifiManager.getConnectionInfo(); 583 updateCurrentBssid(mWifiInfo.getBSSID()); 584 } 585 break; 586 587 case EVENT_WIFI_RADIO_STATE_CHANGE: 588 if (msg.arg1 == WifiManager.WIFI_STATE_DISABLING) { 589 transitionTo(mNotConnectedState); 590 } 591 break; 592 593 default: 594 return NOT_HANDLED; 595 } 596 597 return HANDLED; 598 } 599 } 600 601 /** 602 * WiFi is disconnected. 603 */ 604 class NotConnectedState extends State { 605 @Override 606 public void enter() { 607 if (DBG) logd(getName()); 608 } 609 } 610 611 /** 612 * WiFi is connected, but waiting for good link detection message. 613 */ 614 class VerifyingLinkState extends State { 615 616 private int mSampleCount; 617 618 @Override 619 public void enter() { 620 if (DBG) logd(getName()); 621 mSampleCount = 0; 622 if (mCurrentBssid != null) mCurrentBssid.newLinkDetected(); 623 sendMessage(obtainMessage(CMD_RSSI_FETCH, ++mRssiFetchToken, 0)); 624 } 625 626 @Override 627 public boolean processMessage(Message msg) { 628 switch (msg.what) { 629 case EVENT_WATCHDOG_SETTINGS_CHANGE: 630 updateSettings(); 631 if (!mPoorNetworkDetectionEnabled) { 632 sendLinkStatusNotification(true); 633 } 634 break; 635 636 case EVENT_BSSID_CHANGE: 637 transitionTo(mVerifyingLinkState); 638 break; 639 640 case CMD_RSSI_FETCH: 641 if (msg.arg1 == mRssiFetchToken) { 642 mWsmChannel.sendMessage(WifiManager.RSSI_PKTCNT_FETCH); 643 sendMessageDelayed(obtainMessage(CMD_RSSI_FETCH, ++mRssiFetchToken, 0), 644 LINK_SAMPLING_INTERVAL_MS); 645 } 646 break; 647 648 case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED: 649 if (mCurrentBssid == null || msg.obj == null) { 650 break; 651 } 652 RssiPacketCountInfo info = (RssiPacketCountInfo) msg.obj; 653 int rssi = info.rssi; 654 if (DBG) logd("Fetch RSSI succeed, rssi=" + rssi); 655 656 long time = mCurrentBssid.mBssidAvoidTimeMax - SystemClock.elapsedRealtime(); 657 if (time <= 0) { 658 // max avoidance time is met 659 if (DBG) logd("Max avoid time elapsed"); 660 sendLinkStatusNotification(true); 661 } else { 662 if (rssi >= mCurrentBssid.mGoodLinkTargetRssi) { 663 if (++mSampleCount >= mCurrentBssid.mGoodLinkTargetCount) { 664 // link is good again 665 if (DBG) logd("Good link detected, rssi=" + rssi); 666 mCurrentBssid.mBssidAvoidTimeMax = 0; 667 sendLinkStatusNotification(true); 668 } 669 } else { 670 mSampleCount = 0; 671 if (DBG) logd("Link is still poor, time left=" + time); 672 } 673 } 674 break; 675 676 case WifiManager.RSSI_PKTCNT_FETCH_FAILED: 677 if (DBG) logd("RSSI_FETCH_FAILED"); 678 break; 679 680 default: 681 return NOT_HANDLED; 682 } 683 return HANDLED; 684 } 685 } 686 687 /** 688 * WiFi is connected and link is verified. 689 */ 690 class ConnectedState extends State { 691 @Override 692 public void enter() { 693 if (DBG) logd(getName()); 694 } 695 696 @Override 697 public boolean processMessage(Message msg) { 698 switch (msg.what) { 699 case EVENT_WATCHDOG_SETTINGS_CHANGE: 700 updateSettings(); 701 if (mPoorNetworkDetectionEnabled) { 702 transitionTo(mOnlineWatchState); 703 } else { 704 transitionTo(mOnlineState); 705 } 706 return HANDLED; 707 } 708 return NOT_HANDLED; 709 } 710 } 711 712 /** 713 * RSSI is high enough and don't need link monitoring. 714 */ 715 class OnlineWatchState extends State { 716 @Override 717 public void enter() { 718 if (DBG) logd(getName()); 719 if (mPoorNetworkDetectionEnabled) { 720 // treat entry as an rssi change 721 handleRssiChange(); 722 } else { 723 transitionTo(mOnlineState); 724 } 725 } 726 727 private void handleRssiChange() { 728 if (mCurrentSignalLevel <= LINK_MONITOR_LEVEL_THRESHOLD && mCurrentBssid != null) { 729 transitionTo(mLinkMonitoringState); 730 } else { 731 // stay here 732 } 733 } 734 735 @Override 736 public boolean processMessage(Message msg) { 737 switch (msg.what) { 738 case EVENT_RSSI_CHANGE: 739 mCurrentSignalLevel = calculateSignalLevel(msg.arg1); 740 handleRssiChange(); 741 break; 742 default: 743 return NOT_HANDLED; 744 } 745 return HANDLED; 746 } 747 } 748 749 /** 750 * Keep sampling the link and monitor any poor link situation. 751 */ 752 class LinkMonitoringState extends State { 753 754 private int mSampleCount; 755 756 private int mLastRssi; 757 private int mLastTxGood; 758 private int mLastTxBad; 759 760 @Override 761 public void enter() { 762 if (DBG) logd(getName()); 763 mSampleCount = 0; 764 mCurrentLoss = new VolumeWeightedEMA(EXP_COEFFICIENT_MONITOR); 765 sendMessage(obtainMessage(CMD_RSSI_FETCH, ++mRssiFetchToken, 0)); 766 } 767 768 @Override 769 public boolean processMessage(Message msg) { 770 switch (msg.what) { 771 case EVENT_RSSI_CHANGE: 772 mCurrentSignalLevel = calculateSignalLevel(msg.arg1); 773 if (mCurrentSignalLevel <= LINK_MONITOR_LEVEL_THRESHOLD) { 774 // stay here; 775 } else { 776 // we don't need frequent RSSI monitoring any more 777 transitionTo(mOnlineWatchState); 778 } 779 break; 780 781 case EVENT_BSSID_CHANGE: 782 transitionTo(mLinkMonitoringState); 783 break; 784 785 case CMD_RSSI_FETCH: 786 if (!mIsScreenOn) { 787 transitionTo(mOnlineState); 788 } else if (msg.arg1 == mRssiFetchToken) { 789 mWsmChannel.sendMessage(WifiManager.RSSI_PKTCNT_FETCH); 790 sendMessageDelayed(obtainMessage(CMD_RSSI_FETCH, ++mRssiFetchToken, 0), 791 LINK_SAMPLING_INTERVAL_MS); 792 } 793 break; 794 795 case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED: 796 if (mCurrentBssid == null) { 797 break; 798 } 799 RssiPacketCountInfo info = (RssiPacketCountInfo) msg.obj; 800 int rssi = info.rssi; 801 int mrssi = (mLastRssi + rssi) / 2; 802 int txbad = info.txbad; 803 int txgood = info.txgood; 804 if (DBG) logd("Fetch RSSI succeed, rssi=" + rssi + " mrssi=" + mrssi + " txbad=" 805 + txbad + " txgood=" + txgood); 806 807 // skip the first data point as we want incremental values 808 long now = SystemClock.elapsedRealtime(); 809 if (now - mCurrentBssid.mLastTimeSample < LINK_SAMPLING_INTERVAL_MS * 2) { 810 811 // update packet loss statistics 812 int dbad = txbad - mLastTxBad; 813 int dgood = txgood - mLastTxGood; 814 int dtotal = dbad + dgood; 815 816 if (dtotal > 0) { 817 // calculate packet loss in the last sampling interval 818 double loss = ((double) dbad) / ((double) dtotal); 819 820 mCurrentLoss.update(loss, dtotal); 821 822 if (DBG) { 823 DecimalFormat df = new DecimalFormat("#.##"); 824 logd("Incremental loss=" + dbad + "/" + dtotal + " Current loss=" 825 + df.format(mCurrentLoss.mValue * 100) + "% volume=" 826 + df.format(mCurrentLoss.mVolume)); 827 } 828 829 mCurrentBssid.updateLoss(mrssi, loss, dtotal); 830 831 // check for high packet loss and send poor link notification 832 if (mCurrentLoss.mValue > POOR_LINK_LOSS_THRESHOLD 833 && mCurrentLoss.mVolume > POOR_LINK_MIN_VOLUME) { 834 if (++mSampleCount >= POOR_LINK_SAMPLE_COUNT) 835 if (mCurrentBssid.poorLinkDetected(rssi)) { 836 sendLinkStatusNotification(false); 837 ++mRssiFetchToken; 838 } 839 } else { 840 mSampleCount = 0; 841 } 842 } 843 } 844 845 mCurrentBssid.mLastTimeSample = now; 846 mLastTxBad = txbad; 847 mLastTxGood = txgood; 848 mLastRssi = rssi; 849 break; 850 851 case WifiManager.RSSI_PKTCNT_FETCH_FAILED: 852 // can happen if we are waiting to get a disconnect notification 853 if (DBG) logd("RSSI_FETCH_FAILED"); 854 break; 855 856 default: 857 return NOT_HANDLED; 858 } 859 return HANDLED; 860 } 861 } 862 863 /** 864 * Child state of ConnectedState indicating that we are online and there is nothing to do. 865 */ 866 class OnlineState extends State { 867 @Override 868 public void enter() { 869 if (DBG) logd(getName()); 870 } 871 872 @Override 873 public boolean processMessage(Message msg) { 874 switch (msg.what) { 875 case EVENT_SCREEN_ON: 876 mIsScreenOn = true; 877 if (mPoorNetworkDetectionEnabled) 878 transitionTo(mOnlineWatchState); 879 break; 880 default: 881 return NOT_HANDLED; 882 } 883 return HANDLED; 884 } 885 } 886 887 private void updateCurrentBssid(String bssid) { 888 if (DBG) logd("Update current BSSID to " + (bssid != null ? bssid : "null")); 889 890 // if currently not connected, then set current BSSID to null 891 if (bssid == null) { 892 if (mCurrentBssid == null) return; 893 mCurrentBssid = null; 894 if (DBG) logd("BSSID changed"); 895 sendMessage(EVENT_BSSID_CHANGE); 896 return; 897 } 898 899 // if it is already the current BSSID, then done 900 if (mCurrentBssid != null && bssid.equals(mCurrentBssid.mBssid)) return; 901 902 // search for the new BSSID in the cache, add to cache if not found 903 mCurrentBssid = mBssidCache.get(bssid); 904 if (mCurrentBssid == null) { 905 mCurrentBssid = new BssidStatistics(bssid); 906 mBssidCache.put(bssid, mCurrentBssid); 907 } 908 909 // send BSSID change notification 910 if (DBG) logd("BSSID changed"); 911 sendMessage(EVENT_BSSID_CHANGE); 912 } 913 914 private int calculateSignalLevel(int rssi) { 915 int signalLevel = WifiManager.calculateSignalLevel(rssi, WifiManager.RSSI_LEVELS); 916 if (DBG) 917 logd("RSSI current: " + mCurrentSignalLevel + " new: " + rssi + ", " + signalLevel); 918 return signalLevel; 919 } 920 921 private void sendLinkStatusNotification(boolean isGood) { 922 if (DBG) logd("########################################"); 923 if (isGood) { 924 mWsmChannel.sendMessage(GOOD_LINK_DETECTED); 925 if (mCurrentBssid != null) { 926 mCurrentBssid.mLastTimeGood = SystemClock.elapsedRealtime(); 927 } 928 if (DBG) logd("Good link notification is sent"); 929 } else { 930 mWsmChannel.sendMessage(POOR_LINK_DETECTED); 931 if (mCurrentBssid != null) { 932 mCurrentBssid.mLastTimePoor = SystemClock.elapsedRealtime(); 933 } 934 logd("Poor link notification is sent"); 935 } 936 } 937 938 /** 939 * Convenience function for retrieving a single secure settings value as a 940 * boolean. Note that internally setting values are always stored as 941 * strings; this function converts the string to a boolean for you. The 942 * default value will be returned if the setting is not defined or not a 943 * valid boolean. 944 * 945 * @param cr The ContentResolver to access. 946 * @param name The name of the setting to retrieve. 947 * @param def Value to return if the setting is not defined. 948 * @return The setting's current value, or 'def' if it is not defined or not 949 * a valid boolean. 950 */ 951 private static boolean getSettingsGlobalBoolean(ContentResolver cr, String name, boolean def) { 952 return Settings.Global.getInt(cr, name, def ? 1 : 0) == 1; 953 } 954 955 /** 956 * Convenience function for updating a single settings value as an integer. 957 * This will either create a new entry in the table if the given name does 958 * not exist, or modify the value of the existing row with that name. Note 959 * that internally setting values are always stored as strings, so this 960 * function converts the given value to a string before storing it. 961 * 962 * @param cr The ContentResolver to access. 963 * @param name The name of the setting to modify. 964 * @param value The new value for the setting. 965 * @return true if the value was set, false on database errors 966 */ 967 private static boolean putSettingsGlobalBoolean(ContentResolver cr, String name, boolean value) { 968 return Settings.Global.putInt(cr, name, value ? 1 : 0); 969 } 970 971 /** 972 * Bundle of good link count parameters 973 */ 974 private static class GoodLinkTarget { 975 public final int RSSI_ADJ_DBM; 976 public final int SAMPLE_COUNT; 977 public final int REDUCE_TIME_MS; 978 public GoodLinkTarget(int adj, int count, int time) { 979 RSSI_ADJ_DBM = adj; 980 SAMPLE_COUNT = count; 981 REDUCE_TIME_MS = time; 982 } 983 } 984 985 /** 986 * Bundle of max avoidance time parameters 987 */ 988 private static class MaxAvoidTime { 989 public final int TIME_MS; 990 public final int MIN_RSSI_DBM; 991 public MaxAvoidTime(int time, int rssi) { 992 TIME_MS = time; 993 MIN_RSSI_DBM = rssi; 994 } 995 } 996 997 /** 998 * Volume-weighted Exponential Moving Average (V-EMA) 999 * - volume-weighted: each update has its own weight (number of packets) 1000 * - exponential: O(1) time and O(1) space for both update and query 1001 * - moving average: reflect most recent results and expire old ones 1002 */ 1003 private class VolumeWeightedEMA { 1004 private double mValue; 1005 private double mVolume; 1006 private double mProduct; 1007 private final double mAlpha; 1008 1009 public VolumeWeightedEMA(double coefficient) { 1010 mValue = 0.0; 1011 mVolume = 0.0; 1012 mProduct = 0.0; 1013 mAlpha = coefficient; 1014 } 1015 1016 public void update(double newValue, int newVolume) { 1017 if (newVolume <= 0) return; 1018 // core update formulas 1019 double newProduct = newValue * newVolume; 1020 mProduct = mAlpha * newProduct + (1 - mAlpha) * mProduct; 1021 mVolume = mAlpha * newVolume + (1 - mAlpha) * mVolume; 1022 mValue = mProduct / mVolume; 1023 } 1024 } 1025 1026 /** 1027 * Record (RSSI -> pakce loss %) mappings of one BSSID 1028 */ 1029 private class BssidStatistics { 1030 1031 /* MAC address of this BSSID */ 1032 private final String mBssid; 1033 1034 /* RSSI -> packet loss % mappings */ 1035 private VolumeWeightedEMA[] mEntries; 1036 private int mRssiBase; 1037 private int mEntriesSize; 1038 1039 /* Target to send good link notification, set when poor link is detected */ 1040 private int mGoodLinkTargetRssi; 1041 private int mGoodLinkTargetCount; 1042 1043 /* Index of GOOD_LINK_TARGET array */ 1044 private int mGoodLinkTargetIndex; 1045 1046 /* Timestamps of some last events */ 1047 private long mLastTimeSample; 1048 private long mLastTimeGood; 1049 private long mLastTimePoor; 1050 1051 /* Max time to avoid this BSSID */ 1052 private long mBssidAvoidTimeMax; 1053 1054 /** 1055 * Constructor 1056 * 1057 * @param bssid is the address of this BSSID 1058 */ 1059 public BssidStatistics(String bssid) { 1060 this.mBssid = bssid; 1061 mRssiBase = BSSID_STAT_RANGE_LOW_DBM; 1062 mEntriesSize = BSSID_STAT_RANGE_HIGH_DBM - BSSID_STAT_RANGE_LOW_DBM + 1; 1063 mEntries = new VolumeWeightedEMA[mEntriesSize]; 1064 for (int i = 0; i < mEntriesSize; i++) 1065 mEntries[i] = new VolumeWeightedEMA(EXP_COEFFICIENT_RECORD); 1066 } 1067 1068 /** 1069 * Update this BSSID cache 1070 * 1071 * @param rssi is the RSSI 1072 * @param value is the new instant loss value at this RSSI 1073 * @param volume is the volume for this single update 1074 */ 1075 public void updateLoss(int rssi, double value, int volume) { 1076 if (volume <= 0) return; 1077 int index = rssi - mRssiBase; 1078 if (index < 0 || index >= mEntriesSize) return; 1079 mEntries[index].update(value, volume); 1080 if (DBG) { 1081 DecimalFormat df = new DecimalFormat("#.##"); 1082 logd("Cache updated: loss[" + rssi + "]=" + df.format(mEntries[index].mValue * 100) 1083 + "% volume=" + df.format(mEntries[index].mVolume)); 1084 } 1085 } 1086 1087 /** 1088 * Get preset loss if the cache has insufficient data, observed from experiments. 1089 * 1090 * @param rssi is the input RSSI 1091 * @return preset loss of the given RSSI 1092 */ 1093 public double presetLoss(int rssi) { 1094 if (rssi <= -90) return 1.0; 1095 if (rssi > 0) return 0.0; 1096 1097 if (sPresetLoss == null) { 1098 // pre-calculate all preset losses only once, then reuse them 1099 final int size = 90; 1100 sPresetLoss = new double[size]; 1101 for (int i = 0; i < size; i++) sPresetLoss[i] = 1.0 / Math.pow(90 - i, 1.5); 1102 } 1103 return sPresetLoss[-rssi]; 1104 } 1105 1106 /** 1107 * A poor link is detected, calculate a target RSSI to bring WiFi back. 1108 * 1109 * @param rssi is the current RSSI 1110 * @return true iff the current BSSID should be avoided 1111 */ 1112 public boolean poorLinkDetected(int rssi) { 1113 if (DBG) logd("Poor link detected, rssi=" + rssi); 1114 1115 long now = SystemClock.elapsedRealtime(); 1116 long lastGood = now - mLastTimeGood; 1117 long lastPoor = now - mLastTimePoor; 1118 1119 // reduce the difficulty of good link target if last avoidance was long time ago 1120 while (mGoodLinkTargetIndex > 0 1121 && lastPoor >= GOOD_LINK_TARGET[mGoodLinkTargetIndex - 1].REDUCE_TIME_MS) 1122 mGoodLinkTargetIndex--; 1123 mGoodLinkTargetCount = GOOD_LINK_TARGET[mGoodLinkTargetIndex].SAMPLE_COUNT; 1124 1125 // scan for a target RSSI at which the link is good 1126 int from = rssi + GOOD_LINK_RSSI_RANGE_MIN; 1127 int to = rssi + GOOD_LINK_RSSI_RANGE_MAX; 1128 mGoodLinkTargetRssi = findRssiTarget(from, to, GOOD_LINK_LOSS_THRESHOLD); 1129 mGoodLinkTargetRssi += GOOD_LINK_TARGET[mGoodLinkTargetIndex].RSSI_ADJ_DBM; 1130 if (mGoodLinkTargetIndex < GOOD_LINK_TARGET.length - 1) mGoodLinkTargetIndex++; 1131 1132 // calculate max avoidance time to prevent avoiding forever 1133 int p = 0, pmax = MAX_AVOID_TIME.length - 1; 1134 while (p < pmax && rssi >= MAX_AVOID_TIME[p + 1].MIN_RSSI_DBM) p++; 1135 long avoidMax = MAX_AVOID_TIME[p].TIME_MS; 1136 1137 // don't avoid if max avoidance time is 0 (RSSI is super high) 1138 if (avoidMax <= 0) return false; 1139 1140 // set max avoidance time, send poor link notification 1141 mBssidAvoidTimeMax = now + avoidMax; 1142 1143 if (DBG) logd("goodRssi=" + mGoodLinkTargetRssi + " goodCount=" + mGoodLinkTargetCount 1144 + " lastGood=" + lastGood + " lastPoor=" + lastPoor + " avoidMax=" + avoidMax); 1145 1146 return true; 1147 } 1148 1149 /** 1150 * A new BSSID is connected, recalculate target RSSI threshold 1151 */ 1152 public void newLinkDetected() { 1153 // if this BSSID is currently being avoided, the reuse those values 1154 if (mBssidAvoidTimeMax > 0) { 1155 if (DBG) logd("Previous avoidance still in effect, rssi=" + mGoodLinkTargetRssi 1156 + " count=" + mGoodLinkTargetCount); 1157 return; 1158 } 1159 1160 // calculate a new RSSI threshold for new link verifying 1161 int from = BSSID_STAT_RANGE_LOW_DBM; 1162 int to = BSSID_STAT_RANGE_HIGH_DBM; 1163 mGoodLinkTargetRssi = findRssiTarget(from, to, GOOD_LINK_LOSS_THRESHOLD); 1164 mGoodLinkTargetCount = 1; 1165 mBssidAvoidTimeMax = SystemClock.elapsedRealtime() + MAX_AVOID_TIME[0].TIME_MS; 1166 if (DBG) logd("New link verifying target set, rssi=" + mGoodLinkTargetRssi + " count=" 1167 + mGoodLinkTargetCount); 1168 } 1169 1170 /** 1171 * Return the first RSSI within the range where loss[rssi] < threshold 1172 * 1173 * @param from start scanning from this RSSI 1174 * @param to stop scanning at this RSSI 1175 * @param threshold target threshold for scanning 1176 * @return target RSSI 1177 */ 1178 public int findRssiTarget(int from, int to, double threshold) { 1179 from -= mRssiBase; 1180 to -= mRssiBase; 1181 int emptyCount = 0; 1182 int d = from < to ? 1 : -1; 1183 for (int i = from; i != to; i += d) 1184 // don't use a data point if it volume is too small (statistically unreliable) 1185 if (i >= 0 && i < mEntriesSize && mEntries[i].mVolume > 1.0) { 1186 emptyCount = 0; 1187 if (mEntries[i].mValue < threshold) { 1188 // scan target found 1189 int rssi = mRssiBase + i; 1190 if (DBG) { 1191 DecimalFormat df = new DecimalFormat("#.##"); 1192 logd("Scan target found: rssi=" + rssi + " threshold=" 1193 + df.format(threshold * 100) + "% value=" 1194 + df.format(mEntries[i].mValue * 100) + "% volume=" 1195 + df.format(mEntries[i].mVolume)); 1196 } 1197 return rssi; 1198 } 1199 } else if (++emptyCount >= BSSID_STAT_EMPTY_COUNT) { 1200 // cache has insufficient data around this RSSI, use preset loss instead 1201 int rssi = mRssiBase + i; 1202 double lossPreset = presetLoss(rssi); 1203 if (lossPreset < threshold) { 1204 if (DBG) { 1205 DecimalFormat df = new DecimalFormat("#.##"); 1206 logd("Scan target found: rssi=" + rssi + " threshold=" 1207 + df.format(threshold * 100) + "% value=" 1208 + df.format(lossPreset * 100) + "% volume=preset"); 1209 } 1210 return rssi; 1211 } 1212 } 1213 1214 return mRssiBase + to; 1215 } 1216 } 1217 } 1218