- dont loose explicitely selected bit when autojoining same network
- use scorer only for untrusted networks
Bug:18490330
Bug:18368125

Change-Id: I13f21a2247d071d2e8edc48546c14e0a9e2bc5d6
diff --git a/service/java/com/android/server/wifi/WifiAutoJoinController.java b/service/java/com/android/server/wifi/WifiAutoJoinController.java
index cdef4bb..a971dcd 100644
--- a/service/java/com/android/server/wifi/WifiAutoJoinController.java
+++ b/service/java/com/android/server/wifi/WifiAutoJoinController.java
@@ -52,6 +52,7 @@
     private static final boolean mStaStaSupported = false;
 
     public static int mScanResultMaximumAge = 40000; /* milliseconds unit */
+    public static int mScanResultAutoJoinAge = 5000; /* milliseconds unit */
 
     private String mCurrentConfigurationKey = null; //used by autojoin
 
@@ -341,7 +342,7 @@
             logDbg("compareNetwork will compare " + candidate.configKey()
                     + " with current " + currentNetwork.configKey());
         }
-        int order = compareWifiConfigurationsTop(currentNetwork, candidate);
+        int order = compareWifiConfigurations(currentNetwork, candidate);
 
         // The lastSelectedConfiguration is the configuration the user has manually selected
         // thru WifiPicker, or that a 3rd party app asked us to connect to via the
@@ -680,7 +681,9 @@
         return order;
     }
 
-
+    /**
+     * b/18490330 only use scorer for untrusted networks
+     *
     int compareWifiConfigurationsWithScorer(WifiConfiguration a, WifiConfiguration b) {
 
         boolean aIsActive = false;
@@ -695,8 +698,8 @@
                 bIsActive = true;
             }
         }
-        int scoreA = getConfigNetworkScore(a, 3000, aIsActive);
-        int scoreB = getConfigNetworkScore(b, 3000, bIsActive);
+        int scoreA = getConfigNetworkScore(a, mScanResultAutoJoinAge, aIsActive);
+        int scoreB = getConfigNetworkScore(b, mScanResultAutoJoinAge, bIsActive);
 
         // Both configurations need to have a score for the scorer to be used
         // ...and the scores need to be different:-)
@@ -736,6 +739,7 @@
         // If scoreA > scoreB, the comparison is descending hence the return value is negative
         return scoreB - scoreA;
     }
+     */
 
     int compareWifiConfigurations(WifiConfiguration a, WifiConfiguration b) {
         int order = 0;
@@ -838,6 +842,7 @@
         return (rssi5 < -80 && rssi24 < -90);
     }
 
+    /*
     int compareWifiConfigurationsTop(WifiConfiguration a, WifiConfiguration b) {
         int scorerOrder = compareWifiConfigurationsWithScorer(a, b);
         int order = compareWifiConfigurations(a, b);
@@ -861,6 +866,7 @@
         }
         return order;
     }
+    */
 
     public int rssiBoostFrom5GHzRssi(int rssi, String dbg) {
         if (!mWifiConfigStore.enable5GHzPreference) {
@@ -1133,7 +1139,8 @@
         WifiConfiguration candidate = null;
 
         // Obtain the subset of recently seen networks
-        List<WifiConfiguration> list = mWifiConfigStore.getRecentConfiguredNetworks(3000, false);
+        List<WifiConfiguration> list =
+                mWifiConfigStore.getRecentConfiguredNetworks(mScanResultAutoJoinAge, false);
         if (list == null) {
             if (VDBG)  logDbg("attemptAutoJoin nothing known=" +
                     mWifiConfigStore.getconfiguredNetworkSize());
@@ -1417,7 +1424,7 @@
                     logDbg("attemptAutoJoin will compare candidate  " + candidate.configKey()
                             + " with " + config.configKey());
                 }
-                int order = compareWifiConfigurationsTop(candidate, config);
+                int order = compareWifiConfigurations(candidate, config);
 
                 // The lastSelectedConfiguration is the configuration the user has manually selected
                 // thru WifiPicker, or that a 3rd party app asked us to connect to via the
@@ -1460,9 +1467,7 @@
         }
 
         // Now, go thru scan result to try finding a better untrusted network
-        // TODO: Consider only running this when we can actually connect to these networks. For now,
-        // this is useful for debugging.
-        if (mNetworkScoreCache != null) {
+        if (mNetworkScoreCache != null && mAllowUntrustedConnections) {
             int rssi5 = WifiConfiguration.INVALID_RSSI;
             int rssi24 = WifiConfiguration.INVALID_RSSI;
             if (candidate != null) {
@@ -1484,7 +1489,7 @@
                             !isOpenNetwork(result)) {
                         continue;
                     }
-                    if ((nowMs - result.seen) < 3000) {
+                    if ((nowMs - result.seen) < mScanResultAutoJoinAge) {
                         // Increment usage count for the network
                         mWifiConnectionStatistics.incrementOrAddUntrusted(result.SSID, 0, 1);
 
@@ -1520,12 +1525,10 @@
 
                 // At this point, we have an untrusted network candidate.
                 // Create the new ephemeral configuration and see if we should switch over
-                if (mAllowUntrustedConnections) {
-                    candidate =
-                            mWifiConfigStore.wifiConfigurationFromScanResult(untrustedCandidate);
-                    candidate.allowedKeyManagement.set(KeyMgmt.NONE);
-                    candidate.ephemeral = true;
-                }
+                candidate =
+                        mWifiConfigStore.wifiConfigurationFromScanResult(untrustedCandidate);
+                candidate.allowedKeyManagement.set(KeyMgmt.NONE);
+                candidate.ephemeral = true;
             }
         }
 
@@ -1608,7 +1611,8 @@
                     // Second step: Look for the best Scan result for this configuration
                     // TODO this algorithm should really be done in one step
                     String currentBSSID = mWifiStateMachine.getCurrentBSSID();
-                    ScanResult roamCandidate = attemptRoam(null, candidate, 3000, null);
+                    ScanResult roamCandidate =
+                            attemptRoam(null, candidate, mScanResultAutoJoinAge, null);
                     if (roamCandidate != null && currentBSSID != null
                             && currentBSSID.equals(roamCandidate.BSSID)) {
                         // Sanity, we were already asociated to that candidate
@@ -1639,8 +1643,8 @@
         if (networkSwitchType == AUTO_JOIN_IDLE) {
             String currentBSSID = mWifiStateMachine.getCurrentBSSID();
             // Attempt same WifiConfiguration roaming
-            ScanResult roamCandidate = attemptRoam(null, currentConfiguration, 3000,
-                    currentBSSID);
+            ScanResult roamCandidate =
+                    attemptRoam(null, currentConfiguration, mScanResultAutoJoinAge, currentBSSID);
             /**
              *  TODO: (post L initial release)
              *  consider handling linked configurations roaming (i.e. extended Roaming)
@@ -1659,7 +1663,7 @@
                 for (String key : currentConfiguration.linkedConfigurations.keySet()) {
                     WifiConfiguration link = mWifiConfigStore.getWifiConfiguration(key);
                     if (link != null) {
-                        roamCandidate = attemptRoam(roamCandidate, link, 3000,
+                        roamCandidate = attemptRoam(roamCandidate, link, mScanResultAutoJoinAge,
                                 currentBSSID);
                     }
                 }
diff --git a/service/java/com/android/server/wifi/WifiStateMachine.java b/service/java/com/android/server/wifi/WifiStateMachine.java
index 593d808..e1c9a57 100644
--- a/service/java/com/android/server/wifi/WifiStateMachine.java
+++ b/service/java/com/android/server/wifi/WifiStateMachine.java
@@ -3374,7 +3374,8 @@
         if (DBG) {
             loge("wifi setScanResults state" + getCurrentState()
                     + " sup_state=" + state
-                    + " debouncing=" + linkDebouncing);
+                    + " debouncing=" + linkDebouncing
+                    + " mConnectionRequests=" + mConnectionRequests);
         }
         if (attemptAutoJoin) {
             messageHandlingStatus = MESSAGE_HANDLING_STATUS_PROCESSED;
@@ -6362,13 +6363,24 @@
                             mWifiNative.reconnect()) {
                         lastConnectAttempt = System.currentTimeMillis();
                         targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId);
-                        // We selected a better config,
-                        // maybe because we could not see the last user
-                        // selection, then forget it. We will remember the selection
-                        // only if it was persisted.
-                        mWifiConfigStore.
-                                setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
-
+                        config = mWifiConfigStore.getWifiConfiguration(netId);
+                        if (config != null
+                                && !mWifiConfigStore.isLastSelectedConfiguration(config)) {
+                            // If we autojoined a different config than the user selected one,
+                            // it means we could not see the last user selection,
+                            // or that the last user selection was faulty and ended up blacklisted
+                            // for some reason (in which case the user is notified with an error
+                            // message in the Wifi picker), and thus we managed to auto-join away
+                            // from the selected  config. -> in that case we need to forget
+                            // the selection because we don't want to abruptly switch back to it.
+                            //
+                            // Note that the user selection is also forgotten after a period of time
+                            // during which the device has been disconnected.
+                            // The default value is 30 minutes : see the code path at bottom of
+                            // setScanResults() function.
+                            mWifiConfigStore.
+                                 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
+                        }
                         mAutoRoaming = roam;
                         if (isRoaming() || linkDebouncing) {
                             transitionTo(mRoamingState);
@@ -7691,7 +7703,8 @@
             if (PDBG) {
                 loge(" Enter disconnected State scan interval " + mFrameworkScanIntervalMs
                         + " mEnableBackgroundScan= " + mEnableBackgroundScan
-                        + " screenOn=" + mScreenOn);
+                        + " screenOn=" + mScreenOn
+                        + " mFrameworkScanIntervalMs=" + mFrameworkScanIntervalMs);
             }
 
             /** clear the roaming state, if we were roaming, we failed */