WifiNative.java revision 03ba4a5b108ab2bbdb5d0e7be46ac45c00a6d9ff
1/*
2 * Copyright (C) 2008 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
17package com.android.server.wifi;
18
19import android.net.wifi.BatchedScanSettings;
20import android.net.wifi.RttManager;
21import android.net.wifi.ScanResult;
22import android.net.wifi.WifiConfiguration;
23import android.net.wifi.WifiLinkLayerStats;
24import android.net.wifi.WifiManager;
25import android.net.wifi.WifiScanner;
26import android.net.wifi.RttManager;
27import android.net.wifi.WifiSsid;
28import android.net.wifi.WpsInfo;
29import android.net.wifi.p2p.WifiP2pConfig;
30import android.net.wifi.p2p.WifiP2pGroup;
31import android.net.wifi.p2p.nsd.WifiP2pServiceInfo;
32import android.os.SystemClock;
33import android.text.TextUtils;
34import android.util.Base64;
35import android.util.LocalLog;
36import android.util.Log;
37
38import java.util.ArrayList;
39import java.util.List;
40import java.util.Locale;
41
42/**
43 * Native calls for bring up/shut down of the supplicant daemon and for
44 * sending requests to the supplicant daemon
45 *
46 * waitForEvent() is called on the monitor thread for events. All other methods
47 * must be serialized from the framework.
48 *
49 * {@hide}
50 */
51public class WifiNative {
52
53    private static boolean DBG = false;
54    private final String mTAG;
55    private static final int DEFAULT_GROUP_OWNER_INTENT     = 6;
56
57    static final int BLUETOOTH_COEXISTENCE_MODE_ENABLED     = 0;
58    static final int BLUETOOTH_COEXISTENCE_MODE_DISABLED    = 1;
59    static final int BLUETOOTH_COEXISTENCE_MODE_SENSE       = 2;
60
61    static final int SCAN_WITHOUT_CONNECTION_SETUP          = 1;
62    static final int SCAN_WITH_CONNECTION_SETUP             = 2;
63
64    // Hold this lock before calling supplicant - it is required to
65    // mutually exclude access from Wifi and P2p state machines
66    static final Object mLock = new Object();
67
68    public final String mInterfaceName;
69    public final String mInterfacePrefix;
70
71    private boolean mSuspendOptEnabled = false;
72
73    private static final int EID_HT_OPERATION = 61;
74    private static final int EID_VHT_OPERATION = 192;
75    private static final int EID_EXTENDED_CAPS = 127;
76    private static final int RTT_RESP_ENABLE_BIT = 70;
77    /* Register native functions */
78
79    static {
80        /* Native functions are defined in libwifi-service.so */
81        System.loadLibrary("wifi-service");
82        registerNatives();
83    }
84
85    private static native int registerNatives();
86
87    public native static boolean loadDriver();
88
89    public native static boolean isDriverLoaded();
90
91    public native static boolean unloadDriver();
92
93    public native static boolean startSupplicant(boolean p2pSupported);
94
95    /* Sends a kill signal to supplicant. To be used when we have lost connection
96       or when the supplicant is hung */
97    public native static boolean killSupplicant(boolean p2pSupported);
98
99    private native boolean connectToSupplicantNative();
100
101    private native void closeSupplicantConnectionNative();
102
103    /**
104     * Wait for the supplicant to send an event, returning the event string.
105     * @return the event string sent by the supplicant.
106     */
107    private native String waitForEventNative();
108
109    private native boolean doBooleanCommandNative(String command);
110
111    private native int doIntCommandNative(String command);
112
113    private native String doStringCommandNative(String command);
114
115    public WifiNative(String interfaceName) {
116        mInterfaceName = interfaceName;
117        mTAG = "WifiNative-" + interfaceName;
118        if (!interfaceName.equals("p2p0")) {
119            mInterfacePrefix = "IFNAME=" + interfaceName + " ";
120        } else {
121            // commands for p2p0 interface don't need prefix
122            mInterfacePrefix = "";
123        }
124    }
125
126    void enableVerboseLogging(int verbose) {
127        if (verbose > 0) {
128            DBG = true;
129        } else {
130            DBG = false;
131        }
132    }
133
134    private static final LocalLog mLocalLog = new LocalLog(1024);
135
136    // hold mLock before accessing mCmdIdLock
137    private static int sCmdId;
138
139    public LocalLog getLocalLog() {
140        return mLocalLog;
141    }
142
143    private static int getNewCmdIdLocked() {
144        return sCmdId++;
145    }
146
147    private void localLog(String s) {
148        if (mLocalLog != null)
149            mLocalLog.log(mInterfaceName + ": " + s);
150    }
151
152    public boolean connectToSupplicant() {
153        // No synchronization necessary .. it is implemented in WifiMonitor
154        localLog(mInterfacePrefix + "connectToSupplicant");
155        return connectToSupplicantNative();
156    }
157
158    public void closeSupplicantConnection() {
159        localLog(mInterfacePrefix + "closeSupplicantConnection");
160        closeSupplicantConnectionNative();
161    }
162
163    public String waitForEvent() {
164        // No synchronization necessary .. it is implemented in WifiMonitor
165        return waitForEventNative();
166    }
167
168    private boolean doBooleanCommand(String command) {
169        if (DBG) Log.d(mTAG, "doBoolean: " + command);
170        synchronized (mLock) {
171            int cmdId = getNewCmdIdLocked();
172            String toLog = Integer.toString(cmdId) + ":" + mInterfacePrefix + command;
173            boolean result = doBooleanCommandNative(mInterfacePrefix + command);
174            localLog(toLog + " -> " + result);
175            if (DBG) Log.d(mTAG, command + ": returned " + result);
176            return result;
177        }
178    }
179
180    private int doIntCommand(String command) {
181        if (DBG) Log.d(mTAG, "doInt: " + command);
182        synchronized (mLock) {
183            int cmdId = getNewCmdIdLocked();
184            String toLog = Integer.toString(cmdId) + ":" + mInterfacePrefix + command;
185            int result = doIntCommandNative(mInterfacePrefix + command);
186            localLog(toLog + " -> " + result);
187            if (DBG) Log.d(mTAG, "   returned " + result);
188            return result;
189        }
190    }
191
192    private String doStringCommand(String command) {
193        if (DBG) {
194            //GET_NETWORK commands flood the logs
195            if (!command.startsWith("GET_NETWORK")) {
196                Log.d(mTAG, "doString: [" + command + "]");
197            }
198        }
199        synchronized (mLock) {
200            int cmdId = getNewCmdIdLocked();
201            String toLog = Integer.toString(cmdId) + ":" + mInterfacePrefix + command;
202            String result = doStringCommandNative(mInterfacePrefix + command);
203            if (result == null) {
204                if (DBG) Log.d(mTAG, "doStringCommandNative no result");
205            } else {
206                if (!command.startsWith("STATUS-")) {
207                    localLog(toLog + " -> " + result);
208                }
209                if (DBG) Log.d(mTAG, "   returned " + result.replace("\n", " "));
210            }
211            return result;
212        }
213    }
214
215    private String doStringCommandWithoutLogging(String command) {
216        if (DBG) {
217            //GET_NETWORK commands flood the logs
218            if (!command.startsWith("GET_NETWORK")) {
219                Log.d(mTAG, "doString: [" + command + "]");
220            }
221        }
222        synchronized (mLock) {
223            return doStringCommandNative(mInterfacePrefix + command);
224        }
225    }
226
227    public boolean ping() {
228        String pong = doStringCommand("PING");
229        return (pong != null && pong.equals("PONG"));
230    }
231
232    public void setSupplicantLogLevel(String level) {
233        doStringCommand("LOG_LEVEL " + level);
234    }
235
236    public String getFreqCapability() {
237        return doStringCommand("GET_CAPABILITY freq");
238    }
239
240    public boolean scan(int type, String freqList) {
241        if (type == SCAN_WITHOUT_CONNECTION_SETUP) {
242            if (freqList == null) return doBooleanCommand("SCAN TYPE=ONLY");
243            else return doBooleanCommand("SCAN TYPE=ONLY freq=" + freqList);
244        } else if (type == SCAN_WITH_CONNECTION_SETUP) {
245            if (freqList == null) return doBooleanCommand("SCAN");
246            else return doBooleanCommand("SCAN freq=" + freqList);
247        } else {
248            throw new IllegalArgumentException("Invalid scan type");
249        }
250    }
251
252    /* Does a graceful shutdown of supplicant. Is a common stop function for both p2p and sta.
253     *
254     * Note that underneath we use a harsh-sounding "terminate" supplicant command
255     * for a graceful stop and a mild-sounding "stop" interface
256     * to kill the process
257     */
258    public boolean stopSupplicant() {
259        return doBooleanCommand("TERMINATE");
260    }
261
262    public String listNetworks() {
263        return doStringCommand("LIST_NETWORKS");
264    }
265
266    public String listNetworks(int last_id) {
267        return doStringCommand("LIST_NETWORKS LAST_ID=" + last_id);
268    }
269
270    public int addNetwork() {
271        return doIntCommand("ADD_NETWORK");
272    }
273
274    public boolean setNetworkVariable(int netId, String name, String value) {
275        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) return false;
276        return doBooleanCommand("SET_NETWORK " + netId + " " + name + " " + value);
277    }
278
279    public String getNetworkVariable(int netId, String name) {
280        if (TextUtils.isEmpty(name)) return null;
281
282        // GET_NETWORK will likely flood the logs ...
283        return doStringCommandWithoutLogging("GET_NETWORK " + netId + " " + name);
284    }
285
286    public boolean removeNetwork(int netId) {
287        return doBooleanCommand("REMOVE_NETWORK " + netId);
288    }
289
290
291    private void logDbg(String debug) {
292        long now = SystemClock.elapsedRealtimeNanos();
293        String ts = String.format("[%,d us] ", now/1000);
294        Log.e("WifiNative: ", ts+debug+ " stack:"
295                + Thread.currentThread().getStackTrace()[2].getMethodName() +" - "
296                + Thread.currentThread().getStackTrace()[3].getMethodName() +" - "
297                + Thread.currentThread().getStackTrace()[4].getMethodName() +" - "
298                + Thread.currentThread().getStackTrace()[5].getMethodName()+" - "
299                + Thread.currentThread().getStackTrace()[6].getMethodName());
300
301    }
302    public boolean enableNetwork(int netId, boolean disableOthers) {
303        if (DBG) logDbg("enableNetwork nid=" + Integer.toString(netId)
304                + " disableOthers=" + disableOthers);
305        if (disableOthers) {
306            return doBooleanCommand("SELECT_NETWORK " + netId);
307        } else {
308            return doBooleanCommand("ENABLE_NETWORK " + netId);
309        }
310    }
311
312    public boolean disableNetwork(int netId) {
313        if (DBG) logDbg("disableNetwork nid=" + Integer.toString(netId));
314        return doBooleanCommand("DISABLE_NETWORK " + netId);
315    }
316
317    public boolean selectNetwork(int netId) {
318        if (DBG) logDbg("selectNetwork nid=" + Integer.toString(netId));
319        return doBooleanCommand("SELECT_NETWORK " + netId);
320    }
321
322    public boolean reconnect() {
323        if (DBG) logDbg("RECONNECT ");
324        return doBooleanCommand("RECONNECT");
325    }
326
327    public boolean reassociate() {
328        if (DBG) logDbg("REASSOCIATE ");
329        return doBooleanCommand("REASSOCIATE");
330    }
331
332    public boolean disconnect() {
333        if (DBG) logDbg("DISCONNECT ");
334        return doBooleanCommand("DISCONNECT");
335    }
336
337    public String status() {
338        return status(false);
339    }
340
341    public String status(boolean noEvents) {
342        if (noEvents) {
343            return doStringCommand("STATUS-NO_EVENTS");
344        } else {
345            return doStringCommand("STATUS");
346        }
347    }
348
349    public String getMacAddress() {
350        //Macaddr = XX.XX.XX.XX.XX.XX
351        String ret = doStringCommand("DRIVER MACADDR");
352        if (!TextUtils.isEmpty(ret)) {
353            String[] tokens = ret.split(" = ");
354            if (tokens.length == 2) return tokens[1];
355        }
356        return null;
357    }
358
359
360
361    /**
362     * Format of results:
363     * =================
364     * id=1
365     * bssid=68:7f:74:d7:1b:6e
366     * freq=2412
367     * level=-43
368     * tsf=1344621975160944
369     * age=2623
370     * flags=[WPA2-PSK-CCMP][WPS][ESS]
371     * ssid=zubyb
372     * ====
373     *
374     * RANGE=ALL gets all scan results
375     * RANGE=ID- gets results from ID
376     * MASK=<N> see wpa_supplicant/src/common/wpa_ctrl.h for details
377     * 0                         0                        1                       0     2
378     *                           WPA_BSS_MASK_MESH_SCAN | WPA_BSS_MASK_DELIM    | WPA_BSS_MASK_WIFI_DISPLAY
379     * 0                         0                        0                       1     1   -> 9
380     * WPA_BSS_MASK_INTERNETW  | WPA_BSS_MASK_P2P_SCAN  | WPA_BSS_MASK_WPS_SCAN | WPA_BSS_MASK_SSID
381     * 1                         0                        0                       1     9   -> d
382     * WPA_BSS_MASK_FLAGS      | WPA_BSS_MASK_IE        | WPA_BSS_MASK_AGE      | WPA_BSS_MASK_TSF
383     * 1                         0                        0                       0     8
384     * WPA_BSS_MASK_LEVEL      | WPA_BSS_MASK_NOISE     | WPA_BSS_MASK_QUAL     | WPA_BSS_MASK_CAPABILITIES
385     * 0                         1                        1                       1     7
386     * WPA_BSS_MASK_BEACON_INT | WPA_BSS_MASK_FREQ      | WPA_BSS_MASK_BSSID    | WPA_BSS_MASK_ID
387     *
388     * WPA_BSS_MASK_INTERNETW adds ANQP info (ctrl_iface:4151-4176)
389     *
390     * ctrl_iface.c:wpa_supplicant_ctrl_iface_process:7884
391     *  wpa_supplicant_ctrl_iface_bss:4315
392     *  print_bss_info
393     */
394    public String scanResults(int sid) {
395        return doStringCommandWithoutLogging("BSS RANGE=" + sid + "- MASK=0x29d87");
396    }
397
398    public String doCustomCommand(String command) {
399        return doStringCommand(command);
400    }
401
402    /**
403     * Format of result:
404     * id=1016
405     * bssid=00:03:7f:40:84:10
406     * freq=2462
407     * beacon_int=200
408     * capabilities=0x0431
409     * qual=0
410     * noise=0
411     * level=-46
412     * tsf=0000002669008476
413     * age=5
414     * ie=00105143412d485332302d52322d54455354010882848b960c12182403010b0706555...
415     * flags=[WPA2-EAP-CCMP][ESS][P2P][HS20]
416     * ssid=QCA-HS20-R2-TEST
417     * p2p_device_name=
418     * p2p_config_methods=0x0SET_NE
419     * anqp_venue_name=02083d656e6757692d466920416c6c69616e63650a3239383920436f...
420     * anqp_network_auth_type=010000
421     * anqp_roaming_consortium=03506f9a05001bc504bd
422     * anqp_ip_addr_type_availability=0c
423     * anqp_nai_realm=0200300000246d61696c2e6578616d706c652e636f6d3b636973636f2...
424     * anqp_3gpp=000600040132f465
425     * anqp_domain_name=0b65786d61706c652e636f6d
426     * hs20_operator_friendly_name=11656e6757692d466920416c6c69616e63650e636869...
427     * hs20_wan_metrics=01c40900008001000000000a00
428     * hs20_connection_capability=0100000006140001061600000650000106bb010106bb0...
429     * hs20_osu_providers_list=0b5143412d4f53552d425353010901310015656e6757692d...
430     */
431    public String scanResult(String bssid) {
432        return doStringCommand("BSS " + bssid);
433    }
434
435    /**
436     * Format of command
437     * DRIVER WLS_BATCHING SET SCANFREQ=x MSCAN=r BESTN=y CHANNEL=<z, w, t> RTT=s
438     * where x is an ascii representation of an integer number of seconds between scans
439     *       r is an ascii representation of an integer number of scans per batch
440     *       y is an ascii representation of an integer number of the max AP to remember per scan
441     *       z, w, t represent a 1..n size list of channel numbers and/or 'A', 'B' values
442     *           indicating entire ranges of channels
443     *       s is an ascii representation of an integer number of highest-strength AP
444     *           for which we'd like approximate distance reported
445     *
446     * The return value is an ascii integer representing a guess of the number of scans
447     * the firmware can remember before it runs out of buffer space or -1 on error
448     */
449    public String setBatchedScanSettings(BatchedScanSettings settings) {
450        if (settings == null) {
451            return doStringCommand("DRIVER WLS_BATCHING STOP");
452        }
453        String cmd = "DRIVER WLS_BATCHING SET SCANFREQ=" + settings.scanIntervalSec;
454        cmd += " MSCAN=" + settings.maxScansPerBatch;
455        if (settings.maxApPerScan != BatchedScanSettings.UNSPECIFIED) {
456            cmd += " BESTN=" + settings.maxApPerScan;
457        }
458        if (settings.channelSet != null && !settings.channelSet.isEmpty()) {
459            cmd += " CHANNEL=<";
460            int i = 0;
461            for (String channel : settings.channelSet) {
462                cmd += (i > 0 ? "," : "") + channel;
463                ++i;
464            }
465            cmd += ">";
466        }
467        if (settings.maxApForDistance != BatchedScanSettings.UNSPECIFIED) {
468            cmd += " RTT=" + settings.maxApForDistance;
469        }
470        return doStringCommand(cmd);
471    }
472
473    public String getBatchedScanResults() {
474        return doStringCommand("DRIVER WLS_BATCHING GET");
475    }
476
477    public boolean startDriver() {
478        return doBooleanCommand("DRIVER START");
479    }
480
481    public boolean stopDriver() {
482        return doBooleanCommand("DRIVER STOP");
483    }
484
485
486    /**
487     * Start filtering out Multicast V4 packets
488     * @return {@code true} if the operation succeeded, {@code false} otherwise
489     *
490     * Multicast filtering rules work as follows:
491     *
492     * The driver can filter multicast (v4 and/or v6) and broadcast packets when in
493     * a power optimized mode (typically when screen goes off).
494     *
495     * In order to prevent the driver from filtering the multicast/broadcast packets, we have to
496     * add a DRIVER RXFILTER-ADD rule followed by DRIVER RXFILTER-START to make the rule effective
497     *
498     * DRIVER RXFILTER-ADD Num
499     *   where Num = 0 - Unicast, 1 - Broadcast, 2 - Mutil4 or 3 - Multi6
500     *
501     * and DRIVER RXFILTER-START
502     * In order to stop the usage of these rules, we do
503     *
504     * DRIVER RXFILTER-STOP
505     * DRIVER RXFILTER-REMOVE Num
506     *   where Num is as described for RXFILTER-ADD
507     *
508     * The  SETSUSPENDOPT driver command overrides the filtering rules
509     */
510    public boolean startFilteringMulticastV4Packets() {
511        return doBooleanCommand("DRIVER RXFILTER-STOP")
512            && doBooleanCommand("DRIVER RXFILTER-REMOVE 2")
513            && doBooleanCommand("DRIVER RXFILTER-START");
514    }
515
516    /**
517     * Stop filtering out Multicast V4 packets.
518     * @return {@code true} if the operation succeeded, {@code false} otherwise
519     */
520    public boolean stopFilteringMulticastV4Packets() {
521        return doBooleanCommand("DRIVER RXFILTER-STOP")
522            && doBooleanCommand("DRIVER RXFILTER-ADD 2")
523            && doBooleanCommand("DRIVER RXFILTER-START");
524    }
525
526    /**
527     * Start filtering out Multicast V6 packets
528     * @return {@code true} if the operation succeeded, {@code false} otherwise
529     */
530    public boolean startFilteringMulticastV6Packets() {
531        return doBooleanCommand("DRIVER RXFILTER-STOP")
532            && doBooleanCommand("DRIVER RXFILTER-REMOVE 3")
533            && doBooleanCommand("DRIVER RXFILTER-START");
534    }
535
536    /**
537     * Stop filtering out Multicast V6 packets.
538     * @return {@code true} if the operation succeeded, {@code false} otherwise
539     */
540    public boolean stopFilteringMulticastV6Packets() {
541        return doBooleanCommand("DRIVER RXFILTER-STOP")
542            && doBooleanCommand("DRIVER RXFILTER-ADD 3")
543            && doBooleanCommand("DRIVER RXFILTER-START");
544    }
545
546    /**
547     * Set the operational frequency band
548     * @param band One of
549     *     {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
550     *     {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
551     *     {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
552     * @return {@code true} if the operation succeeded, {@code false} otherwise
553     */
554    public boolean setBand(int band) {
555        String bandstr;
556
557        if (band == WifiManager.WIFI_FREQUENCY_BAND_5GHZ)
558            bandstr = "5G";
559        else if (band == WifiManager.WIFI_FREQUENCY_BAND_2GHZ)
560            bandstr = "2G";
561        else
562            bandstr = "AUTO";
563        return doBooleanCommand("SET SETBAND " + bandstr);
564    }
565
566    /**
567      * Sets the bluetooth coexistence mode.
568      *
569      * @param mode One of {@link #BLUETOOTH_COEXISTENCE_MODE_DISABLED},
570      *            {@link #BLUETOOTH_COEXISTENCE_MODE_ENABLED}, or
571      *            {@link #BLUETOOTH_COEXISTENCE_MODE_SENSE}.
572      * @return Whether the mode was successfully set.
573      */
574    public boolean setBluetoothCoexistenceMode(int mode) {
575        return doBooleanCommand("DRIVER BTCOEXMODE " + mode);
576    }
577
578    /**
579     * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
580     * some of the low-level scan parameters used by the driver are changed to
581     * reduce interference with A2DP streaming.
582     *
583     * @param isSet whether to enable or disable this mode
584     * @return {@code true} if the command succeeded, {@code false} otherwise.
585     */
586    public boolean setBluetoothCoexistenceScanMode(boolean setCoexScanMode) {
587        if (setCoexScanMode) {
588            return doBooleanCommand("DRIVER BTCOEXSCAN-START");
589        } else {
590            return doBooleanCommand("DRIVER BTCOEXSCAN-STOP");
591        }
592    }
593
594    public void enableSaveConfig() {
595        doBooleanCommand("SET update_config 1");
596    }
597
598    public boolean saveConfig() {
599        return doBooleanCommand("SAVE_CONFIG");
600    }
601
602    public boolean addToBlacklist(String bssid) {
603        if (TextUtils.isEmpty(bssid)) return false;
604        return doBooleanCommand("BLACKLIST " + bssid);
605    }
606
607    public boolean clearBlacklist() {
608        return doBooleanCommand("BLACKLIST clear");
609    }
610
611    public boolean setSuspendOptimizations(boolean enabled) {
612       // if (mSuspendOptEnabled == enabled) return true;
613        mSuspendOptEnabled = enabled;
614
615        Log.e("native", "do suspend " + enabled);
616        if (enabled) {
617            return doBooleanCommand("DRIVER SETSUSPENDMODE 1");
618        } else {
619            return doBooleanCommand("DRIVER SETSUSPENDMODE 0");
620        }
621    }
622
623    public boolean setCountryCode(String countryCode) {
624        if (countryCode != null)
625            return doBooleanCommand("DRIVER COUNTRY " + countryCode.toUpperCase(Locale.ROOT));
626        else
627            return doBooleanCommand("DRIVER COUNTRY");
628    }
629
630    public void enableBackgroundScan(boolean enable) {
631        if (enable) {
632            doBooleanCommand("SET pno 1");
633        } else {
634            doBooleanCommand("SET pno 0");
635        }
636    }
637
638    public void enableAutoConnect(boolean enable) {
639        if (enable) {
640            doBooleanCommand("STA_AUTOCONNECT 1");
641        } else {
642            doBooleanCommand("STA_AUTOCONNECT 0");
643        }
644    }
645
646    public void setScanInterval(int scanInterval) {
647        doBooleanCommand("SCAN_INTERVAL " + scanInterval);
648    }
649
650    public void startTdls(String macAddr, boolean enable) {
651        if (enable) {
652            doBooleanCommand("TDLS_DISCOVER " + macAddr);
653            doBooleanCommand("TDLS_SETUP " + macAddr);
654        } else {
655            doBooleanCommand("TDLS_TEARDOWN " + macAddr);
656        }
657    }
658
659    /** Example output:
660     * RSSI=-65
661     * LINKSPEED=48
662     * NOISE=9999
663     * FREQUENCY=0
664     */
665    public String signalPoll() {
666        return doStringCommandWithoutLogging("SIGNAL_POLL");
667    }
668
669    /** Example outout:
670     * TXGOOD=396
671     * TXBAD=1
672     */
673    public String pktcntPoll() {
674        return doStringCommand("PKTCNT_POLL");
675    }
676
677    public void bssFlush() {
678        doBooleanCommand("BSS_FLUSH 0");
679    }
680
681    public boolean startWpsPbc(String bssid) {
682        if (TextUtils.isEmpty(bssid)) {
683            return doBooleanCommand("WPS_PBC");
684        } else {
685            return doBooleanCommand("WPS_PBC " + bssid);
686        }
687    }
688
689    public boolean startWpsPbc(String iface, String bssid) {
690        synchronized (mLock) {
691            if (TextUtils.isEmpty(bssid)) {
692                return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC");
693            } else {
694                return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC " + bssid);
695            }
696        }
697    }
698
699    public boolean startWpsPinKeypad(String pin) {
700        if (TextUtils.isEmpty(pin)) return false;
701        return doBooleanCommand("WPS_PIN any " + pin);
702    }
703
704    public boolean startWpsPinKeypad(String iface, String pin) {
705        if (TextUtils.isEmpty(pin)) return false;
706        synchronized (mLock) {
707            return doBooleanCommandNative("IFNAME=" + iface + " WPS_PIN any " + pin);
708        }
709    }
710
711
712    public String startWpsPinDisplay(String bssid) {
713        if (TextUtils.isEmpty(bssid)) {
714            return doStringCommand("WPS_PIN any");
715        } else {
716            return doStringCommand("WPS_PIN " + bssid);
717        }
718    }
719
720    public String startWpsPinDisplay(String iface, String bssid) {
721        synchronized (mLock) {
722            if (TextUtils.isEmpty(bssid)) {
723                return doStringCommandNative("IFNAME=" + iface + " WPS_PIN any");
724            } else {
725                return doStringCommandNative("IFNAME=" + iface + " WPS_PIN " + bssid);
726            }
727        }
728    }
729
730    public boolean setExternalSim(boolean external) {
731        synchronized (mLock) {
732            String value = external ? "1" : "0";
733            Log.d(TAG, "Setting external_sim to " + value);
734            return doBooleanCommand("SET external_sim " + value);
735        }
736    }
737
738    public boolean simAuthResponse(int id, String type, String response) {
739        // with type = GSM-AUTH, UMTS-AUTH or UMTS-AUTS
740        synchronized (mLock) {
741            return doBooleanCommand("CTRL-RSP-SIM-" + id + ":" + type + response);
742        }
743    }
744
745    public boolean simIdentityResponse(int id, String response) {
746        synchronized (mLock) {
747            return doBooleanCommand("CTRL-RSP-IDENTITY-" + id + ":" + response);
748        }
749    }
750
751    /* Configures an access point connection */
752    public boolean startWpsRegistrar(String bssid, String pin) {
753        if (TextUtils.isEmpty(bssid) || TextUtils.isEmpty(pin)) return false;
754        return doBooleanCommand("WPS_REG " + bssid + " " + pin);
755    }
756
757    public boolean cancelWps() {
758        return doBooleanCommand("WPS_CANCEL");
759    }
760
761    public boolean setPersistentReconnect(boolean enabled) {
762        int value = (enabled == true) ? 1 : 0;
763        return doBooleanCommand("SET persistent_reconnect " + value);
764    }
765
766    public boolean setDeviceName(String name) {
767        return doBooleanCommand("SET device_name " + name);
768    }
769
770    public boolean setDeviceType(String type) {
771        return doBooleanCommand("SET device_type " + type);
772    }
773
774    public boolean setConfigMethods(String cfg) {
775        return doBooleanCommand("SET config_methods " + cfg);
776    }
777
778    public boolean setManufacturer(String value) {
779        return doBooleanCommand("SET manufacturer " + value);
780    }
781
782    public boolean setModelName(String value) {
783        return doBooleanCommand("SET model_name " + value);
784    }
785
786    public boolean setModelNumber(String value) {
787        return doBooleanCommand("SET model_number " + value);
788    }
789
790    public boolean setSerialNumber(String value) {
791        return doBooleanCommand("SET serial_number " + value);
792    }
793
794    public boolean setP2pSsidPostfix(String postfix) {
795        return doBooleanCommand("SET p2p_ssid_postfix " + postfix);
796    }
797
798    public boolean setP2pGroupIdle(String iface, int time) {
799        synchronized (mLock) {
800            return doBooleanCommandNative("IFNAME=" + iface + " SET p2p_group_idle " + time);
801        }
802    }
803
804    public void setPowerSave(boolean enabled) {
805        if (enabled) {
806            doBooleanCommand("SET ps 1");
807        } else {
808            doBooleanCommand("SET ps 0");
809        }
810    }
811
812    public boolean setP2pPowerSave(String iface, boolean enabled) {
813        synchronized (mLock) {
814            if (enabled) {
815                return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 1");
816            } else {
817                return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 0");
818            }
819        }
820    }
821
822    public boolean setWfdEnable(boolean enable) {
823        return doBooleanCommand("SET wifi_display " + (enable ? "1" : "0"));
824    }
825
826    public boolean setWfdDeviceInfo(String hex) {
827        return doBooleanCommand("WFD_SUBELEM_SET 0 " + hex);
828    }
829
830    /**
831     * "sta" prioritizes STA connection over P2P and "p2p" prioritizes
832     * P2P connection over STA
833     */
834    public boolean setConcurrencyPriority(String s) {
835        return doBooleanCommand("P2P_SET conc_pref " + s);
836    }
837
838    public boolean p2pFind() {
839        return doBooleanCommand("P2P_FIND");
840    }
841
842    public boolean p2pFind(int timeout) {
843        if (timeout <= 0) {
844            return p2pFind();
845        }
846        return doBooleanCommand("P2P_FIND " + timeout);
847    }
848
849    public boolean p2pStopFind() {
850       return doBooleanCommand("P2P_STOP_FIND");
851    }
852
853    public boolean p2pListen() {
854        return doBooleanCommand("P2P_LISTEN");
855    }
856
857    public boolean p2pListen(int timeout) {
858        if (timeout <= 0) {
859            return p2pListen();
860        }
861        return doBooleanCommand("P2P_LISTEN " + timeout);
862    }
863
864    public boolean p2pExtListen(boolean enable, int period, int interval) {
865        if (enable && interval < period) {
866            return false;
867        }
868        return doBooleanCommand("P2P_EXT_LISTEN"
869                    + (enable ? (" " + period + " " + interval) : ""));
870    }
871
872    public boolean p2pSetChannel(int lc, int oc) {
873        if (DBG) Log.d(mTAG, "p2pSetChannel: lc="+lc+", oc="+oc);
874
875        if (lc >=1 && lc <= 11) {
876            if (!doBooleanCommand("P2P_SET listen_channel " + lc)) {
877                return false;
878            }
879        } else if (lc != 0) {
880            return false;
881        }
882
883        if (oc >= 1 && oc <= 165 ) {
884            int freq = (oc <= 14 ? 2407 : 5000) + oc * 5;
885            return doBooleanCommand("P2P_SET disallow_freq 1000-"
886                    + (freq - 5) + "," + (freq + 5) + "-6000");
887        } else if (oc == 0) {
888            /* oc==0 disables "P2P_SET disallow_freq" (enables all freqs) */
889            return doBooleanCommand("P2P_SET disallow_freq \"\"");
890        }
891
892        return false;
893    }
894
895    public boolean p2pFlush() {
896        return doBooleanCommand("P2P_FLUSH");
897    }
898
899    /* p2p_connect <peer device address> <pbc|pin|PIN#> [label|display|keypad]
900        [persistent] [join|auth] [go_intent=<0..15>] [freq=<in MHz>] */
901    public String p2pConnect(WifiP2pConfig config, boolean joinExistingGroup) {
902        if (config == null) return null;
903        List<String> args = new ArrayList<String>();
904        WpsInfo wps = config.wps;
905        args.add(config.deviceAddress);
906
907        switch (wps.setup) {
908            case WpsInfo.PBC:
909                args.add("pbc");
910                break;
911            case WpsInfo.DISPLAY:
912                if (TextUtils.isEmpty(wps.pin)) {
913                    args.add("pin");
914                } else {
915                    args.add(wps.pin);
916                }
917                args.add("display");
918                break;
919            case WpsInfo.KEYPAD:
920                args.add(wps.pin);
921                args.add("keypad");
922                break;
923            case WpsInfo.LABEL:
924                args.add(wps.pin);
925                args.add("label");
926            default:
927                break;
928        }
929
930        if (config.netId == WifiP2pGroup.PERSISTENT_NET_ID) {
931            args.add("persistent");
932        }
933
934        if (joinExistingGroup) {
935            args.add("join");
936        } else {
937            //TODO: This can be adapted based on device plugged in state and
938            //device battery state
939            int groupOwnerIntent = config.groupOwnerIntent;
940            if (groupOwnerIntent < 0 || groupOwnerIntent > 15) {
941                groupOwnerIntent = DEFAULT_GROUP_OWNER_INTENT;
942            }
943            args.add("go_intent=" + groupOwnerIntent);
944        }
945
946        String command = "P2P_CONNECT ";
947        for (String s : args) command += s + " ";
948
949        return doStringCommand(command);
950    }
951
952    public boolean p2pCancelConnect() {
953        return doBooleanCommand("P2P_CANCEL");
954    }
955
956    public boolean p2pProvisionDiscovery(WifiP2pConfig config) {
957        if (config == null) return false;
958
959        switch (config.wps.setup) {
960            case WpsInfo.PBC:
961                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " pbc");
962            case WpsInfo.DISPLAY:
963                //We are doing display, so provision discovery is keypad
964                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " keypad");
965            case WpsInfo.KEYPAD:
966                //We are doing keypad, so provision discovery is display
967                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " display");
968            default:
969                break;
970        }
971        return false;
972    }
973
974    public boolean p2pGroupAdd(boolean persistent) {
975        if (persistent) {
976            return doBooleanCommand("P2P_GROUP_ADD persistent");
977        }
978        return doBooleanCommand("P2P_GROUP_ADD");
979    }
980
981    public boolean p2pGroupAdd(int netId) {
982        return doBooleanCommand("P2P_GROUP_ADD persistent=" + netId);
983    }
984
985    public boolean p2pGroupRemove(String iface) {
986        if (TextUtils.isEmpty(iface)) return false;
987        synchronized (mLock) {
988            return doBooleanCommandNative("IFNAME=" + iface + " P2P_GROUP_REMOVE " + iface);
989        }
990    }
991
992    public boolean p2pReject(String deviceAddress) {
993        return doBooleanCommand("P2P_REJECT " + deviceAddress);
994    }
995
996    /* Invite a peer to a group */
997    public boolean p2pInvite(WifiP2pGroup group, String deviceAddress) {
998        if (TextUtils.isEmpty(deviceAddress)) return false;
999
1000        if (group == null) {
1001            return doBooleanCommand("P2P_INVITE peer=" + deviceAddress);
1002        } else {
1003            return doBooleanCommand("P2P_INVITE group=" + group.getInterface()
1004                    + " peer=" + deviceAddress + " go_dev_addr=" + group.getOwner().deviceAddress);
1005        }
1006    }
1007
1008    /* Reinvoke a persistent connection */
1009    public boolean p2pReinvoke(int netId, String deviceAddress) {
1010        if (TextUtils.isEmpty(deviceAddress) || netId < 0) return false;
1011
1012        return doBooleanCommand("P2P_INVITE persistent=" + netId + " peer=" + deviceAddress);
1013    }
1014
1015    public String p2pGetSsid(String deviceAddress) {
1016        return p2pGetParam(deviceAddress, "oper_ssid");
1017    }
1018
1019    public String p2pGetDeviceAddress() {
1020
1021        Log.d(TAG, "p2pGetDeviceAddress");
1022
1023        String status = null;
1024
1025        /* Explicitly calling the API without IFNAME= prefix to take care of the devices that
1026        don't have p2p0 interface. Supplicant seems to be returning the correct address anyway. */
1027
1028        synchronized (mLock) {
1029            status = doStringCommandNative("STATUS");
1030        }
1031
1032        String result = "";
1033        if (status != null) {
1034            String[] tokens = status.split("\n");
1035            for (String token : tokens) {
1036                if (token.startsWith("p2p_device_address=")) {
1037                    String[] nameValue = token.split("=");
1038                    if (nameValue.length != 2)
1039                        break;
1040                    result = nameValue[1];
1041                }
1042            }
1043        }
1044
1045        Log.d(TAG, "p2pGetDeviceAddress returning " + result);
1046        return result;
1047    }
1048
1049    public int getGroupCapability(String deviceAddress) {
1050        int gc = 0;
1051        if (TextUtils.isEmpty(deviceAddress)) return gc;
1052        String peerInfo = p2pPeer(deviceAddress);
1053        if (TextUtils.isEmpty(peerInfo)) return gc;
1054
1055        String[] tokens = peerInfo.split("\n");
1056        for (String token : tokens) {
1057            if (token.startsWith("group_capab=")) {
1058                String[] nameValue = token.split("=");
1059                if (nameValue.length != 2) break;
1060                try {
1061                    return Integer.decode(nameValue[1]);
1062                } catch(NumberFormatException e) {
1063                    return gc;
1064                }
1065            }
1066        }
1067        return gc;
1068    }
1069
1070    public String p2pPeer(String deviceAddress) {
1071        return doStringCommand("P2P_PEER " + deviceAddress);
1072    }
1073
1074    private String p2pGetParam(String deviceAddress, String key) {
1075        if (deviceAddress == null) return null;
1076
1077        String peerInfo = p2pPeer(deviceAddress);
1078        if (peerInfo == null) return null;
1079        String[] tokens= peerInfo.split("\n");
1080
1081        key += "=";
1082        for (String token : tokens) {
1083            if (token.startsWith(key)) {
1084                String[] nameValue = token.split("=");
1085                if (nameValue.length != 2) break;
1086                return nameValue[1];
1087            }
1088        }
1089        return null;
1090    }
1091
1092    public boolean p2pServiceAdd(WifiP2pServiceInfo servInfo) {
1093        /*
1094         * P2P_SERVICE_ADD bonjour <query hexdump> <RDATA hexdump>
1095         * P2P_SERVICE_ADD upnp <version hex> <service>
1096         *
1097         * e.g)
1098         * [Bonjour]
1099         * # IP Printing over TCP (PTR) (RDATA=MyPrinter._ipp._tcp.local.)
1100         * P2P_SERVICE_ADD bonjour 045f697070c00c000c01 094d795072696e746572c027
1101         * # IP Printing over TCP (TXT) (RDATA=txtvers=1,pdl=application/postscript)
1102         * P2P_SERVICE_ADD bonjour 096d797072696e746572045f697070c00c001001
1103         *  09747874766572733d311a70646c3d6170706c69636174696f6e2f706f7374736372797074
1104         *
1105         * [UPnP]
1106         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012
1107         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice
1108         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp
1109         * -org:device:InternetGatewayDevice:1
1110         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9322-123456789012::urn:schemas-upnp
1111         * -org:service:ContentDirectory:2
1112         */
1113        for (String s : servInfo.getSupplicantQueryList()) {
1114            String command = "P2P_SERVICE_ADD";
1115            command += (" " + s);
1116            if (!doBooleanCommand(command)) {
1117                return false;
1118            }
1119        }
1120        return true;
1121    }
1122
1123    public boolean p2pServiceDel(WifiP2pServiceInfo servInfo) {
1124        /*
1125         * P2P_SERVICE_DEL bonjour <query hexdump>
1126         * P2P_SERVICE_DEL upnp <version hex> <service>
1127         */
1128        for (String s : servInfo.getSupplicantQueryList()) {
1129            String command = "P2P_SERVICE_DEL ";
1130
1131            String[] data = s.split(" ");
1132            if (data.length < 2) {
1133                return false;
1134            }
1135            if ("upnp".equals(data[0])) {
1136                command += s;
1137            } else if ("bonjour".equals(data[0])) {
1138                command += data[0];
1139                command += (" " + data[1]);
1140            } else {
1141                return false;
1142            }
1143            if (!doBooleanCommand(command)) {
1144                return false;
1145            }
1146        }
1147        return true;
1148    }
1149
1150    public boolean p2pServiceFlush() {
1151        return doBooleanCommand("P2P_SERVICE_FLUSH");
1152    }
1153
1154    public String p2pServDiscReq(String addr, String query) {
1155        String command = "P2P_SERV_DISC_REQ";
1156        command += (" " + addr);
1157        command += (" " + query);
1158
1159        return doStringCommand(command);
1160    }
1161
1162    public boolean p2pServDiscCancelReq(String id) {
1163        return doBooleanCommand("P2P_SERV_DISC_CANCEL_REQ " + id);
1164    }
1165
1166    /* Set the current mode of miracast operation.
1167     *  0 = disabled
1168     *  1 = operating as source
1169     *  2 = operating as sink
1170     */
1171    public void setMiracastMode(int mode) {
1172        // Note: optional feature on the driver. It is ok for this to fail.
1173        doBooleanCommand("DRIVER MIRACAST " + mode);
1174    }
1175
1176    public boolean fetchAnqp(String bssid, String subtypes) {
1177        return doBooleanCommand("ANQP_GET " + bssid + " " + subtypes);
1178    }
1179
1180    /* WIFI HAL support */
1181
1182    private static final String TAG = "WifiNative-HAL";
1183    private static long sWifiHalHandle = 0;  /* used by JNI to save wifi_handle */
1184    private static long[] sWifiIfaceHandles = null;  /* used by JNI to save interface handles */
1185    private static int sWlan0Index = -1;
1186    private static int sP2p0Index = -1;
1187
1188    private static boolean sHalIsStarted = false;
1189    private static boolean sHalFailed = false;
1190
1191    private static native boolean startHalNative();
1192    private static native void stopHalNative();
1193    private static native void waitForHalEventNative();
1194
1195    private static class MonitorThread extends Thread {
1196        public void run() {
1197            Log.i(TAG, "Waiting for HAL events mWifiHalHandle=" + Long.toString(sWifiHalHandle));
1198            waitForHalEventNative();
1199        }
1200    }
1201
1202    synchronized public static boolean startHal() {
1203
1204        String debugLog = "startHal stack: ";
1205        java.lang.StackTraceElement[] elements = Thread.currentThread().getStackTrace();
1206        for (int i = 2; i < elements.length && i <= 7; i++ ) {
1207            debugLog = debugLog + " - " + elements[i].getMethodName();
1208        }
1209
1210        Log.i(TAG,debugLog);
1211
1212        synchronized (mLock) {
1213            if (sHalFailed)
1214                return false;
1215            if (startHalNative() && (getInterfaces() != 0) && (sWlan0Index != -1)) {
1216                new MonitorThread().start();
1217                sHalIsStarted = true;
1218                return true;
1219            } else {
1220                Log.i(TAG, "Could not start hal");
1221                sHalIsStarted = false;
1222                sHalFailed = true;
1223                return false;
1224            }
1225        }
1226    }
1227
1228    synchronized public static void stopHal() {
1229        stopHalNative();
1230    }
1231
1232    private static native int getInterfacesNative();
1233
1234    synchronized public static int getInterfaces() {
1235        synchronized (mLock) {
1236            if (sWifiIfaceHandles == null) {
1237                int num = getInterfacesNative();
1238                int wifi_num = 0;
1239                for (int i = 0; i < num; i++) {
1240                    String name = getInterfaceNameNative(i);
1241                    Log.i(TAG, "interface[" + i + "] = " + name);
1242                    if (name.equals("wlan0")) {
1243                        sWlan0Index = i;
1244                        wifi_num++;
1245                    } else if (name.equals("p2p0")) {
1246                        sP2p0Index = i;
1247                        wifi_num++;
1248                    }
1249                }
1250                return wifi_num;
1251            } else {
1252                return sWifiIfaceHandles.length;
1253            }
1254        }
1255    }
1256
1257    private static native String getInterfaceNameNative(int index);
1258    synchronized public static String getInterfaceName(int index) {
1259        return getInterfaceNameNative(index);
1260    }
1261
1262    public static class ScanCapabilities {
1263        public int  max_scan_cache_size;                 // in number of scan results??
1264        public int  max_scan_buckets;
1265        public int  max_ap_cache_per_scan;
1266        public int  max_rssi_sample_size;
1267        public int  max_scan_reporting_threshold;        // in number of scan results??
1268        public int  max_hotlist_bssids;
1269        public int  max_significant_wifi_change_aps;
1270    }
1271
1272    public static boolean getScanCapabilities(ScanCapabilities capabilities) {
1273        return getScanCapabilitiesNative(sWlan0Index, capabilities);
1274    }
1275
1276    private static native boolean getScanCapabilitiesNative(
1277            int iface, ScanCapabilities capabilities);
1278
1279    private static native boolean startScanNative(int iface, int id, ScanSettings settings);
1280    private static native boolean stopScanNative(int iface, int id);
1281    private static native WifiScanner.ScanData[] getScanResultsNative(int iface, boolean flush);
1282    private static native WifiLinkLayerStats getWifiLinkLayerStatsNative(int iface);
1283
1284    public static class ChannelSettings {
1285        int frequency;
1286        int dwell_time_ms;
1287        boolean passive;
1288    }
1289
1290    public static class BucketSettings {
1291        int bucket;
1292        int band;
1293        int period_ms;
1294        int report_events;
1295        int num_channels;
1296        ChannelSettings channels[];
1297    }
1298
1299    public static class ScanSettings {
1300        int base_period_ms;
1301        int max_ap_per_scan;
1302        int report_threshold_percent;
1303        int report_threshold_num_scans;
1304        int num_buckets;
1305        BucketSettings buckets[];
1306    }
1307
1308    public static interface ScanEventHandler {
1309        void onScanResultsAvailable();
1310        void onFullScanResult(ScanResult fullScanResult);
1311        void onScanStatus();
1312        void onScanPaused(WifiScanner.ScanData[] data);
1313        void onScanRestarted();
1314    }
1315
1316    synchronized static void onScanResultsAvailable(int id) {
1317        if (sScanEventHandler  != null) {
1318            sScanEventHandler.onScanResultsAvailable();
1319        }
1320    }
1321
1322    /* scan status, keep these values in sync with gscan.h */
1323    private static int WIFI_SCAN_BUFFER_FULL = 0;
1324    private static int WIFI_SCAN_COMPLETE = 1;
1325
1326    synchronized static void onScanStatus(int status) {
1327        Log.i(TAG, "Got a scan status changed event, status = " + status);
1328
1329        if (status == WIFI_SCAN_BUFFER_FULL) {
1330            /* we have a separate event to take care of this */
1331        } else if (status == WIFI_SCAN_COMPLETE) {
1332            if (sScanEventHandler  != null) {
1333                sScanEventHandler.onScanStatus();
1334            }
1335        }
1336    }
1337
1338    static void populateScanResult(ScanResult result, byte bytes[], String dbg) {
1339        int num = 0;
1340        if (bytes == null) return;
1341        if (dbg == null) dbg = "";
1342        for (int i = 0; i < bytes.length; ) {
1343            int type  = bytes[i] & 0xFF;
1344            int len = bytes[i + 1] & 0xFF;
1345
1346            if (i + len + 2 > bytes.length) {
1347                Log.w(TAG, dbg + "bad length " + len + " of IE " + type + " from " + result.BSSID);
1348                Log.w(TAG, dbg + "ignoring the rest of the IEs");
1349                break;
1350            }
1351            num++;
1352            i += len + 2;
1353            if (DBG) Log.i(TAG, dbg + "bytes[" + i + "] = [" + type + ", " + len + "]" + ", " +
1354                    "next = " + i);
1355        }
1356
1357        int secondChanelOffset = 0;
1358        byte channelMode = 0;
1359        byte centerFreqIndex1 = 0;
1360        byte centerFreqIndex2 = 0;
1361        result.is80211McRTTResponder = false;
1362
1363        ScanResult.InformationElement elements[] = new ScanResult.InformationElement[num];
1364        for (int i = 0, index = 0; i < num; i++) {
1365            int type  = bytes[index] & 0xFF;
1366            int len = bytes[index + 1] & 0xFF;
1367            if (DBG) Log.i(TAG, dbg + "index = " + index + ", type = " + type + ", len = " + len);
1368            ScanResult.InformationElement elem = new ScanResult.InformationElement();
1369            elem.id = type;
1370            elem.bytes = new byte[len];
1371            for (int j = 0; j < len; j++) {
1372                elem.bytes[j] = bytes[index + j + 2];
1373            }
1374            elements[i] = elem;
1375            int inforStart = index + 2;
1376            index += (len + 2);
1377
1378            if(type == EID_HT_OPERATION) {
1379                secondChanelOffset = bytes[inforStart + 1] & 0x3;
1380            } else if(type == EID_VHT_OPERATION) {
1381                channelMode = bytes[inforStart];
1382                centerFreqIndex1 = bytes[inforStart + 1];
1383                centerFreqIndex2 = bytes[inforStart + 2];
1384            } else if (type == EID_EXTENDED_CAPS) {
1385                int tempIndex = RTT_RESP_ENABLE_BIT / 8;
1386                byte offset = RTT_RESP_ENABLE_BIT % 8;
1387
1388                if(len < tempIndex + 1) {
1389                    result.is80211McRTTResponder = false;
1390                } else {
1391                    if ((bytes[inforStart + tempIndex] & ((byte)0x1 << offset)) != 0) {
1392                        result.is80211McRTTResponder = true;
1393                    } else {
1394                        result.is80211McRTTResponder = false;
1395                    }
1396                }
1397            }
1398        }
1399        //handle RTT related information
1400        if (channelMode != 0) {
1401            // 80 or 160 MHz
1402            result.channelWidth = channelMode + 1;
1403
1404            //convert channel index to frequency in MHz, channel 36 is 5180MHz
1405            result.centerFreq0 = (centerFreqIndex1 - 36) * 5 + 5180;
1406
1407            if(channelMode > 1) { //160MHz
1408                result.centerFreq1 = (centerFreqIndex2 - 36) * 5 + 5180;
1409            } else {
1410                result.centerFreq1 = 0;
1411            }
1412        } else {
1413            //20 or 40 MHz
1414            if (secondChanelOffset != 0) {//40MHz
1415                result.channelWidth = 1;
1416                if (secondChanelOffset == 1) {
1417                    result.centerFreq0 = result.frequency + 20;
1418                } else if (secondChanelOffset == 3) {
1419                    result.centerFreq0 = result.frequency - 20;
1420                } else {
1421                    result.centerFreq0 = 0;
1422                    Log.e(TAG, dbg + ": Error on secondChanelOffset");
1423                }
1424            } else {
1425                result.centerFreq0  = 0;
1426                result.centerFreq1  = 0;
1427            }
1428            result.centerFreq1  = 0;
1429        }
1430        if(DBG) {
1431            Log.d(TAG, dbg + "SSID: " + result.SSID + " ChannelWidth is: " + result.channelWidth +
1432                    " PrimaryFreq: " + result.frequency +" mCenterfreq0: " + result.centerFreq0 +
1433                    " mCenterfreq1: " + result.centerFreq1 + (result.is80211McRTTResponder ?
1434                    "Support RTT reponder: " : "Do not support RTT responder"));
1435        }
1436
1437        result.informationElements = elements;
1438    }
1439
1440    synchronized static void onFullScanResult(int id, ScanResult result, byte bytes[]) {
1441        if (DBG) Log.i(TAG, "Got a full scan results event, ssid = " + result.SSID + ", " +
1442                "num = " + bytes.length);
1443
1444        if (sScanEventHandler == null) {
1445            return;
1446        }
1447        populateScanResult(result, bytes, " onFullScanResult ");
1448
1449        sScanEventHandler.onFullScanResult(result);
1450    }
1451
1452    private static int sScanCmdId = 0;
1453    private static ScanEventHandler sScanEventHandler;
1454    private static ScanSettings sScanSettings;
1455
1456    synchronized public static boolean startScan(
1457            ScanSettings settings, ScanEventHandler eventHandler) {
1458        synchronized (mLock) {
1459
1460            if (sScanCmdId != 0) {
1461                stopScan();
1462            } else if (sScanSettings != null || sScanEventHandler != null) {
1463                /* current scan is paused; no need to stop it */
1464            }
1465
1466            sScanCmdId = getNewCmdIdLocked();
1467
1468            sScanSettings = settings;
1469            sScanEventHandler = eventHandler;
1470
1471            if (startScanNative(sWlan0Index, sScanCmdId, settings) == false) {
1472                sScanEventHandler = null;
1473                sScanSettings = null;
1474                sScanCmdId = 0;
1475                return false;
1476            }
1477
1478            return true;
1479        }
1480    }
1481
1482    synchronized public static void stopScan() {
1483        synchronized (mLock) {
1484            stopScanNative(sWlan0Index, sScanCmdId);
1485            sScanSettings = null;
1486            sScanEventHandler = null;
1487            sScanCmdId = 0;
1488        }
1489    }
1490
1491    synchronized public static void pauseScan() {
1492        synchronized (mLock) {
1493            if (sScanCmdId != 0 && sScanSettings != null && sScanEventHandler != null) {
1494                Log.d(TAG, "Pausing scan");
1495                WifiScanner.ScanData scanData[] = getScanResultsNative(sWlan0Index, true);
1496                stopScanNative(sWlan0Index, sScanCmdId);
1497                sScanCmdId = 0;
1498                sScanEventHandler.onScanPaused(scanData);
1499            }
1500        }
1501    }
1502
1503    synchronized public static void restartScan() {
1504        synchronized (mLock) {
1505            if (sScanCmdId == 0 && sScanSettings != null && sScanEventHandler != null) {
1506                Log.d(TAG, "Restarting scan");
1507                ScanEventHandler handler = sScanEventHandler;
1508                ScanSettings settings = sScanSettings;
1509                if (startScan(sScanSettings, sScanEventHandler)) {
1510                    sScanEventHandler.onScanRestarted();
1511                } else {
1512                    /* we are still paused; don't change state */
1513                    sScanEventHandler = handler;
1514                    sScanSettings = settings;
1515                }
1516            }
1517        }
1518    }
1519
1520    synchronized public static WifiScanner.ScanData[] getScanResults(boolean flush) {
1521        synchronized (mLock) {
1522            return getScanResultsNative(sWlan0Index, flush);
1523        }
1524    }
1525
1526    public static interface HotlistEventHandler {
1527        void onHotlistApFound (ScanResult[] result);
1528        void onHotlistApLost  (ScanResult[] result);
1529    }
1530
1531    private static int sHotlistCmdId = 0;
1532    private static HotlistEventHandler sHotlistEventHandler;
1533
1534    private native static boolean setHotlistNative(int iface, int id,
1535            WifiScanner.HotlistSettings settings);
1536    private native static boolean resetHotlistNative(int iface, int id);
1537
1538    synchronized public static boolean setHotlist(WifiScanner.HotlistSettings settings,
1539                                    HotlistEventHandler eventHandler) {
1540        synchronized (mLock) {
1541            if (sHotlistCmdId != 0) {
1542                return false;
1543            } else {
1544                sHotlistCmdId = getNewCmdIdLocked();
1545            }
1546
1547            sHotlistEventHandler = eventHandler;
1548            if (setHotlistNative(sWlan0Index, sScanCmdId, settings) == false) {
1549                sHotlistEventHandler = null;
1550                return false;
1551            }
1552
1553            return true;
1554        }
1555    }
1556
1557    synchronized public static void resetHotlist() {
1558        synchronized (mLock) {
1559            if (sHotlistCmdId != 0) {
1560                resetHotlistNative(sWlan0Index, sHotlistCmdId);
1561                sHotlistCmdId = 0;
1562                sHotlistEventHandler = null;
1563            }
1564        }
1565    }
1566
1567    synchronized public static void onHotlistApFound(int id, ScanResult[] results) {
1568        synchronized (mLock) {
1569            if (sHotlistCmdId != 0) {
1570                sHotlistEventHandler.onHotlistApFound(results);
1571            } else {
1572                /* this can happen because of race conditions */
1573                Log.d(TAG, "Ignoring hotlist AP found event");
1574            }
1575        }
1576    }
1577
1578    synchronized public static void onHotlistApLost(int id, ScanResult[] results) {
1579        synchronized (mLock) {
1580            if (sHotlistCmdId != 0) {
1581                sHotlistEventHandler.onHotlistApLost(results);
1582            } else {
1583                /* this can happen because of race conditions */
1584                Log.d(TAG, "Ignoring hotlist AP lost event");
1585            }
1586        }
1587    }
1588
1589    public static interface SignificantWifiChangeEventHandler {
1590        void onChangesFound(ScanResult[] result);
1591    }
1592
1593    private static SignificantWifiChangeEventHandler sSignificantWifiChangeHandler;
1594    private static int sSignificantWifiChangeCmdId;
1595
1596    private static native boolean trackSignificantWifiChangeNative(
1597            int iface, int id, WifiScanner.WifiChangeSettings settings);
1598    private static native boolean untrackSignificantWifiChangeNative(int iface, int id);
1599
1600    synchronized public static boolean trackSignificantWifiChange(
1601            WifiScanner.WifiChangeSettings settings, SignificantWifiChangeEventHandler handler) {
1602        synchronized (mLock) {
1603            if (sSignificantWifiChangeCmdId != 0) {
1604                return false;
1605            } else {
1606                sSignificantWifiChangeCmdId = getNewCmdIdLocked();
1607            }
1608
1609            sSignificantWifiChangeHandler = handler;
1610            if (trackSignificantWifiChangeNative(sWlan0Index, sScanCmdId, settings) == false) {
1611                sSignificantWifiChangeHandler = null;
1612                return false;
1613            }
1614
1615            return true;
1616        }
1617    }
1618
1619    synchronized static void untrackSignificantWifiChange() {
1620        synchronized (mLock) {
1621            if (sSignificantWifiChangeCmdId != 0) {
1622                untrackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId);
1623                sSignificantWifiChangeCmdId = 0;
1624                sSignificantWifiChangeHandler = null;
1625            }
1626        }
1627    }
1628
1629    synchronized static void onSignificantWifiChange(int id, ScanResult[] results) {
1630        synchronized (mLock) {
1631            if (sSignificantWifiChangeCmdId != 0) {
1632                sSignificantWifiChangeHandler.onChangesFound(results);
1633            } else {
1634                /* this can happen because of race conditions */
1635                Log.d(TAG, "Ignoring significant wifi change");
1636            }
1637        }
1638    }
1639
1640    synchronized public static WifiLinkLayerStats getWifiLinkLayerStats(String iface) {
1641        // TODO: use correct iface name to Index translation
1642        if (iface == null) return null;
1643        synchronized (mLock) {
1644            if (!sHalIsStarted)
1645                startHal();
1646            if (sHalIsStarted)
1647                return getWifiLinkLayerStatsNative(sWlan0Index);
1648        }
1649        return null;
1650    }
1651
1652    /*
1653     * NFC-related calls
1654     */
1655    public String getNfcWpsConfigurationToken(int netId) {
1656        return doStringCommand("WPS_NFC_CONFIG_TOKEN WPS " + netId);
1657    }
1658
1659    public String getNfcHandoverRequest() {
1660        return doStringCommand("NFC_GET_HANDOVER_REQ NDEF P2P-CR");
1661    }
1662
1663    public String getNfcHandoverSelect() {
1664        return doStringCommand("NFC_GET_HANDOVER_SEL NDEF P2P-CR");
1665    }
1666
1667    public boolean initiatorReportNfcHandover(String selectMessage) {
1668        return doBooleanCommand("NFC_REPORT_HANDOVER INIT P2P 00 " + selectMessage);
1669    }
1670
1671    public boolean responderReportNfcHandover(String requestMessage) {
1672        return doBooleanCommand("NFC_REPORT_HANDOVER RESP P2P " + requestMessage + " 00");
1673    }
1674
1675    public static native int getSupportedFeatureSetNative(int iface);
1676    synchronized public static int getSupportedFeatureSet() {
1677        return getSupportedFeatureSetNative(sWlan0Index);
1678    }
1679
1680    /* Rtt related commands/events */
1681    public static interface RttEventHandler {
1682        void onRttResults(RttManager.RttResult[] result);
1683    }
1684
1685    private static RttEventHandler sRttEventHandler;
1686    private static int sRttCmdId;
1687
1688    synchronized private static void onRttResults(int id, RttManager.RttResult[] results) {
1689        if (id == sRttCmdId) {
1690            Log.d(TAG, "Received " + results.length + " rtt results");
1691            sRttEventHandler.onRttResults(results);
1692            sRttCmdId = 0;
1693        } else {
1694            Log.d(TAG, "RTT Received event for unknown cmd = " + id + ", current id = " + sRttCmdId);
1695        }
1696    }
1697
1698    private static native boolean requestRangeNative(
1699            int iface, int id, RttManager.RttParams[] params);
1700    private static native boolean cancelRangeRequestNative(
1701            int iface, int id, RttManager.RttParams[] params);
1702
1703    synchronized public static boolean requestRtt(
1704            RttManager.RttParams[] params, RttEventHandler handler) {
1705        synchronized (mLock) {
1706            if (sRttCmdId != 0) {
1707                Log.v("TAG", "Last one is still under measurement!");
1708                return false;
1709            } else {
1710                sRttCmdId = getNewCmdIdLocked();
1711            }
1712            sRttEventHandler = handler;
1713            Log.v(TAG, "native issue RTT request");
1714            return requestRangeNative(sWlan0Index, sRttCmdId, params);
1715        }
1716    }
1717
1718    synchronized public static boolean cancelRtt(RttManager.RttParams[] params) {
1719        synchronized(mLock) {
1720            if (sRttCmdId == 0) {
1721                return false;
1722            }
1723
1724            sRttCmdId = 0;
1725
1726            if (cancelRangeRequestNative(sWlan0Index, sRttCmdId, params)) {
1727                sRttEventHandler = null;
1728                Log.v(TAG, "Xin: RTT cancel Request Successfully");
1729                return true;
1730            } else {
1731                Log.e(TAG, "Xin:RTT cancel Request failed");
1732                return false;
1733            }
1734        }
1735    }
1736
1737    private static native boolean setScanningMacOuiNative(int iface, byte[] oui);
1738
1739    synchronized public static boolean setScanningMacOui(byte[] oui) {
1740        synchronized (mLock) {
1741            if (startHal()) {
1742                return setScanningMacOuiNative(sWlan0Index, oui);
1743            } else {
1744                return false;
1745            }
1746        }
1747    }
1748
1749    private static native int[] getChannelsForBandNative(
1750            int iface, int band);
1751
1752    synchronized public static int [] getChannelsForBand(int band) {
1753        synchronized (mLock) {
1754            if (startHal()) {
1755                return getChannelsForBandNative(sWlan0Index, band);
1756            } else {
1757                return null;
1758            }
1759        }
1760    }
1761
1762
1763    private static native boolean setDfsFlagNative(int iface, boolean dfsOn);
1764    synchronized public static boolean setDfsFlag(boolean dfsOn) {
1765        synchronized (mLock) {
1766            if (startHal()) {
1767                return setDfsFlagNative(sWlan0Index, dfsOn);
1768            } else {
1769                return false;
1770            }
1771        }
1772    }
1773
1774    private static native boolean toggleInterfaceNative(int on);
1775    synchronized public static boolean toggleInterface(int on) {
1776        synchronized (mLock) {
1777            if (startHal()) {
1778                return toggleInterfaceNative(0);
1779            } else {
1780
1781                return false;
1782            }
1783        }
1784    }
1785
1786    private static native RttManager.RttCapabilities getRttCapabilitiesNative(int iface);
1787    synchronized public static RttManager.RttCapabilities getRttCapabilities() {
1788        synchronized (mLock) {
1789            if (startHal()) {
1790                return getRttCapabilitiesNative(sWlan0Index);
1791            } else {
1792                return null;
1793            }
1794        }
1795    }
1796
1797    private static native boolean setCountryCodeHalNative(int iface, String CountryCode);
1798    synchronized public static boolean setCountryCodeHal( String CountryCode) {
1799        synchronized (mLock) {
1800            if (startHal()) {
1801                return setCountryCodeHalNative(sWlan0Index, CountryCode);
1802            } else {
1803                return false;
1804            }
1805        }
1806    }
1807
1808    /* Rtt related commands/events */
1809    public abstract class TdlsEventHandler {
1810        abstract public void onTdlsStatus(String macAddr, int status, int reason);
1811    }
1812
1813    private static TdlsEventHandler sTdlsEventHandler;
1814
1815
1816    private static native boolean enableDisableTdlsNative(int iface, boolean enable,
1817            String macAddr);
1818    synchronized public static boolean enableDisableTdls(boolean enable, String macAdd,
1819            TdlsEventHandler tdlsCallBack) {
1820        synchronized (mLock) {
1821            if (startHal()) {
1822                sTdlsEventHandler = tdlsCallBack;
1823                return enableDisableTdlsNative(sWlan0Index, enable, macAdd);
1824            } else {
1825                return false;
1826            }
1827        }
1828    }
1829
1830    // Once TDLS per mac and event feature is implemented, this class definition should be
1831    // moved to the right place, like WifiManager etc
1832    public static class TdlsStatus {
1833        int channel;
1834        int global_operating_class;
1835        int state;
1836        int reason;
1837    }
1838    private static native TdlsStatus getTdlsStatusNative(int iface, String macAddr);
1839    synchronized public static TdlsStatus getTdlsStatus (String macAdd) {
1840        synchronized (mLock) {
1841            if (startHal()) {
1842                return getTdlsStatusNative(sWlan0Index, macAdd);
1843            } else {
1844                return null;
1845            }
1846        }
1847    }
1848
1849    //ToFix: Once TDLS per mac and event feature is implemented, this class definition should be
1850    // moved to the right place, like WifiStateMachine etc
1851    public static class TdlsCapabilities {
1852        /* Maximum TDLS session number can be supported by the Firmware and hardware */
1853        int maxConcurrentTdlsSessionNumber;
1854        boolean isGlobalTdlsSupported;
1855        boolean isPerMacTdlsSupported;
1856        boolean isOffChannelTdlsSupported;
1857    }
1858
1859
1860
1861    private static native TdlsCapabilities getTdlsCapabilitiesNative(int iface);
1862    synchronized public static TdlsCapabilities getTdlsCapabilities () {
1863        synchronized (mLock) {
1864            if (startHal()) {
1865                return getTdlsCapabilitiesNative(sWlan0Index);
1866            } else {
1867                return null;
1868            }
1869        }
1870    }
1871
1872    synchronized private static boolean onTdlsStatus(String macAddr, int status, int reason) {
1873         if (sTdlsEventHandler == null) {
1874             return false;
1875         } else {
1876             sTdlsEventHandler.onTdlsStatus(macAddr, status, reason);
1877             return true;
1878         }
1879    }
1880
1881    //---------------------------------------------------------------------------------
1882
1883    /* Wifi Logger commands/events */
1884
1885    public static native boolean startLogging(int iface);
1886
1887    public static interface WifiLoggerEventHandler {
1888        void onDataAvailable(char data[], int len);
1889    }
1890
1891    private static WifiLoggerEventHandler sWifiLoggerEventHandler = null;
1892
1893    public static class WifiLoggerEvent {
1894        WifiLogger.RingBufferStatus status;
1895        int entrySize;
1896        int flags;
1897        int type;
1898        long timestamp;
1899        byte[] entry;
1900
1901        public String toString() {
1902            StringBuilder str =  new StringBuilder();
1903            str.append(status + "\n entry size: " + entrySize + " flags: " + flags);
1904            str.append(" type: " + type + " timestamp: " + timestamp +"\n");
1905            if (entry != null) {
1906                str.append(android.util.Base64.encodeToString(entry, Base64.DEFAULT));
1907            } else {
1908                str.append(" empty bytes[]");
1909            }
1910            str.append("\n\n");
1911            return str.toString();
1912        }
1913    }
1914
1915    private static void onWifiLoggerEvent(WifiLoggerEvent event) {
1916        if (event != null) {
1917            Log.d(TAG, "Logger Event:" + event);
1918        }
1919    }
1920
1921    private static void onWifiAlert(byte[] buffer, int errorCode) {
1922        Log.d(TAG, "Logger Alert error code:" + errorCode);
1923        if (buffer != null) {
1924            StringBuilder str =  new StringBuilder();
1925            str.append(android.util.Base64.encodeToString(buffer, android.util.Base64.NO_WRAP));
1926            Log.e(TAG,"Logger Alert event:");
1927            Log.e(TAG, str.toString());
1928        } else {
1929            Log.e(TAG," empty Alert");
1930        }
1931    }
1932
1933    private static native boolean startLoggingRingBufferNative(int iface, int verboseLevel,
1934            int flags, int maxInterval,int minDataSize, String ringName);
1935    synchronized public static boolean startLoggingRingBuffer(int verboseLevel, int flags, int maxInterval,
1936            int minDataSize, String ringName){
1937        synchronized (mLock) {
1938            if (startHal()) {
1939                return startLoggingRingBufferNative(sWlan0Index, verboseLevel, flags, maxInterval,
1940                        minDataSize, ringName);
1941            } else {
1942                return false;
1943            }
1944        }
1945    }
1946
1947    private static native int getSupportedLoggerFeatureSetNative(int iface);
1948    synchronized public static int getSupportedLoggerFeatureSet() {
1949        synchronized (mLock) {
1950            if (startHal()) {
1951                return getSupportedLoggerFeatureSetNative(sWlan0Index);
1952            } else {
1953                return -1;
1954            }
1955        }
1956    }
1957
1958    private static native String getDriverVersionNative(int iface);
1959    synchronized public static String getDriverVersion() {
1960        synchronized (mLock) {
1961            if (startHal()) {
1962                return getDriverVersionNative(sWlan0Index);
1963            } else {
1964                return null;
1965            }
1966        }
1967    }
1968
1969
1970    private static native String getFirmwareVersionNative(int iface);
1971    synchronized public static String getFirmwareVersion() {
1972        synchronized (mLock) {
1973            if (startHal()) {
1974                return getFirmwareVersionNative(sWlan0Index);
1975            } else {
1976                return null;
1977            }
1978        }
1979    }
1980
1981    private static native WifiLogger.RingBufferStatus[] getRingBufferStatusNative(int iface);
1982    synchronized public static WifiLogger.RingBufferStatus[] getRingBufferStatus() {
1983        synchronized (mLock) {
1984            if (startHal()) {
1985                return getRingBufferStatusNative(sWlan0Index);
1986            } else {
1987                return null;
1988            }
1989        }
1990    }
1991
1992    private static native boolean getRingBufferDataNative(int iface, String ringName);
1993    synchronized public static boolean getRingBufferData(String ringName) {
1994        synchronized (mLock) {
1995            if (startHal()) {
1996                return getRingBufferDataNative(sWlan0Index, ringName);
1997            } else {
1998                return false;
1999            }
2000        }
2001    }
2002
2003    public static String mFwMemoryDump;
2004    private static void onWifiFwMemoryAvailable(byte[] buffer) {
2005        Log.d(TAG, "onWifiFwMemoryAvailable is called");
2006        mFwMemoryDump =  android.util.Base64.encodeToString(buffer, Base64.DEFAULT);
2007    }
2008    private static native boolean getFwMemoryDumpNative(int iface);
2009    synchronized public static String getFwMemoryDump() {
2010        synchronized (mLock) {
2011            if (startHal()) {
2012                if(getFwMemoryDumpNative(sWlan0Index)) {
2013                    String tmp = mFwMemoryDump;
2014                    mFwMemoryDump = null;
2015                    return tmp;
2016                } else {
2017                    return null;
2018                }
2019            } else {
2020                return null;
2021            }
2022        }
2023    }
2024
2025    //---------------------------------------------------------------------------------
2026    /* Configure ePNO */
2027
2028    public class WifiPnoNetwork {
2029        String SSID;
2030        int rssi_threshold;
2031        int flags;
2032        int auth;
2033        String configKey; // kept for reference
2034
2035        WifiPnoNetwork(WifiConfiguration config, int threshold) {
2036            if (config.SSID == null) {
2037                this.SSID = "";
2038                this.flags = 1;
2039            } else {
2040                this.SSID = config.SSID;
2041            }
2042            this.rssi_threshold = threshold;
2043            if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
2044                auth |= 2;
2045            } else if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) ||
2046                    config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
2047                auth |= 4;
2048            } else if (config.wepKeys[0] != null) {
2049                auth |= 1;
2050            } else {
2051                auth |= 1;
2052            }
2053//            auth = 0;
2054            flags |= 6; //A and G
2055            configKey = config.configKey();
2056        }
2057
2058        @Override
2059        public String toString() {
2060            StringBuilder sbuf = new StringBuilder();
2061            sbuf.append(this.SSID);
2062            sbuf.append(" flags=").append(this.flags);
2063            sbuf.append(" rssi=").append(this.rssi_threshold);
2064            sbuf.append(" auth=").append(this.auth);
2065            return sbuf.toString();
2066        }
2067    }
2068
2069    public static interface WifiPnoEventHandler {
2070        void onPnoNetworkFound(ScanResult results[]);
2071    }
2072
2073    private static WifiPnoEventHandler sWifiPnoEventHandler;
2074
2075    private static int sPnoCmdId = 0;
2076
2077    private native static boolean setPnoListNative(int iface, int id, WifiPnoNetwork list[]);
2078
2079    synchronized public static boolean setPnoList(WifiPnoNetwork list[],
2080                                                  WifiPnoEventHandler eventHandler) {
2081        Log.e(TAG, "setPnoList cmd " + sPnoCmdId);
2082
2083        synchronized (mLock) {
2084
2085            sPnoCmdId = getNewCmdIdLocked();
2086
2087            sWifiPnoEventHandler = eventHandler;
2088            if (setPnoListNative(sWlan0Index, sPnoCmdId, list) == false) {
2089                sWifiPnoEventHandler = null;
2090                return false;
2091            }
2092
2093            return true;
2094        }
2095    }
2096
2097    synchronized public static void onPnoNetworkFound(int id, ScanResult[] results) {
2098
2099        if (results == null) {
2100            Log.e(TAG, "onPnoNetworkFound null results");
2101            return;
2102
2103        }
2104        Log.d(TAG, "WifiNative.onPnoNetworkFound result " + results.length);
2105
2106        //Log.e(TAG, "onPnoNetworkFound length " + results.length);
2107        //return;
2108        for (int i=0; i<results.length; i++) {
2109            Log.e(TAG, "onPnoNetworkFound SSID " + results[i].SSID
2110                    + " " + results[i].level + " " + results[i].frequency);
2111
2112            populateScanResult(results[i], results[i].bytes, "onPnoNetworkFound ");
2113            results[i].wifiSsid = WifiSsid.createFromAsciiEncoded(results[i].SSID);
2114        }
2115        synchronized (mLock) {
2116            if (sPnoCmdId != 0 && sWifiPnoEventHandler != null) {
2117                sWifiPnoEventHandler.onPnoNetworkFound(results);
2118            } else {
2119                /* this can happen because of race conditions */
2120                Log.d(TAG, "Ignoring Pno Network found event");
2121            }
2122        }
2123}
2124
2125}
2126