WifiNative.java revision 3ff269ca67e73f66ac22049fc318b2f86eafb253
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.RttManager;
20import android.net.wifi.ScanResult;
21import android.net.wifi.WifiConfiguration;
22import android.net.wifi.WifiEnterpriseConfig;
23import android.net.wifi.WifiLinkLayerStats;
24import android.net.wifi.WifiWakeReasonAndCounts;
25import android.net.wifi.WifiManager;
26import android.net.wifi.WifiScanner;
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.os.SystemProperties;
34import android.text.TextUtils;
35import android.util.LocalLog;
36import android.util.Log;
37import android.content.Context;
38import android.content.Intent;
39import android.app.AlarmManager;
40import android.app.PendingIntent;
41import android.content.IntentFilter;
42import android.content.BroadcastReceiver;
43import com.android.server.connectivity.KeepalivePacketData;
44import com.android.server.wifi.hotspot2.NetworkDetail;
45import com.android.server.wifi.hotspot2.SupplicantBridge;
46import com.android.server.wifi.hotspot2.Utils;
47import com.android.server.wifi.util.InformationElementUtil;
48
49import libcore.util.HexEncoding;
50
51import java.nio.ByteBuffer;
52import java.nio.CharBuffer;
53import java.nio.charset.CharacterCodingException;
54import java.nio.charset.CharsetDecoder;
55import java.nio.charset.StandardCharsets;
56import java.util.ArrayList;
57import java.util.List;
58import java.util.Locale;
59import java.util.Set;
60
61/**
62 * Native calls for bring up/shut down of the supplicant daemon and for
63 * sending requests to the supplicant daemon
64 *
65 * waitForEvent() is called on the monitor thread for events. All other methods
66 * must be serialized from the framework.
67 *
68 * {@hide}
69 */
70public class WifiNative {
71    private static boolean DBG = false;
72
73    /**
74     * Hold this lock before calling supplicant or HAL methods
75     * it is required to mutually exclude access to the driver
76     */
77    public static final Object sLock = new Object();
78
79    private static final LocalLog sLocalLog = new LocalLog(16384);
80
81    public static LocalLog getLocalLog() {
82        return sLocalLog;
83    }
84
85    /* Register native functions */
86    static {
87        /* Native functions are defined in libwifi-service.so */
88        System.loadLibrary("wifi-service");
89        registerNatives();
90    }
91
92    private static native int registerNatives();
93
94    /*
95     * Singleton WifiNative instances
96     */
97    private static WifiNative wlanNativeInterface =
98            new WifiNative(SystemProperties.get("wifi.interface", "wlan0"));
99    public static WifiNative getWlanNativeInterface() {
100        return wlanNativeInterface;
101    }
102
103    //STOPSHIP: get interface name from native side
104    private static WifiNative p2pNativeInterface = new WifiNative("p2p0");
105    public static WifiNative getP2pNativeInterface() {
106        return p2pNativeInterface;
107    }
108
109
110    private final String mTAG;
111    private final String mInterfaceName;
112    private final String mInterfacePrefix;
113
114    private Context mContext = null;
115    private PnoMonitor mPnoMonitor = null;
116    public void initContext(Context context) {
117        if (mContext == null && context != null) {
118            mContext = context;
119            mPnoMonitor = new PnoMonitor();
120        }
121    }
122
123    private WifiNative(String interfaceName) {
124        mInterfaceName = interfaceName;
125        mTAG = "WifiNative-" + interfaceName;
126
127        if (!interfaceName.equals("p2p0")) {
128            mInterfacePrefix = "IFNAME=" + interfaceName + " ";
129        } else {
130            // commands for p2p0 interface don't need prefix
131            mInterfacePrefix = "";
132        }
133    }
134
135    public String getInterfaceName() {
136        return mInterfaceName;
137    }
138
139    // Note this affects logging on for all interfaces
140    void enableVerboseLogging(int verbose) {
141        if (verbose > 0) {
142            DBG = true;
143        } else {
144            DBG = false;
145        }
146    }
147
148    private void localLog(String s) {
149        if (sLocalLog != null) sLocalLog.log(mInterfaceName + ": " + s);
150    }
151
152
153
154    /*
155     * Driver and Supplicant management
156     */
157    private native static boolean loadDriverNative();
158    public boolean loadDriver() {
159        synchronized (sLock) {
160            return loadDriverNative();
161        }
162    }
163
164    private native static boolean isDriverLoadedNative();
165    public boolean isDriverLoaded() {
166        synchronized (sLock) {
167            return isDriverLoadedNative();
168        }
169    }
170
171    private native static boolean unloadDriverNative();
172    public boolean unloadDriver() {
173        synchronized (sLock) {
174            return unloadDriverNative();
175        }
176    }
177
178    private native static boolean startSupplicantNative(boolean p2pSupported);
179    public boolean startSupplicant(boolean p2pSupported) {
180        synchronized (sLock) {
181            return startSupplicantNative(p2pSupported);
182        }
183    }
184
185    /* Sends a kill signal to supplicant. To be used when we have lost connection
186       or when the supplicant is hung */
187    private native static boolean killSupplicantNative(boolean p2pSupported);
188    public boolean killSupplicant(boolean p2pSupported) {
189        synchronized (sLock) {
190            return killSupplicantNative(p2pSupported);
191        }
192    }
193
194    private native static boolean connectToSupplicantNative();
195    public boolean connectToSupplicant() {
196        synchronized (sLock) {
197            localLog(mInterfacePrefix + "connectToSupplicant");
198            return connectToSupplicantNative();
199        }
200    }
201
202    private native static void closeSupplicantConnectionNative();
203    public void closeSupplicantConnection() {
204        synchronized (sLock) {
205            localLog(mInterfacePrefix + "closeSupplicantConnection");
206            closeSupplicantConnectionNative();
207        }
208    }
209
210    /**
211     * Wait for the supplicant to send an event, returning the event string.
212     * @return the event string sent by the supplicant.
213     */
214    private native static String waitForEventNative();
215    public String waitForEvent() {
216        // No synchronization necessary .. it is implemented in WifiMonitor
217        return waitForEventNative();
218    }
219
220
221    /*
222     * Supplicant Command Primitives
223     */
224    private native boolean doBooleanCommandNative(String command);
225
226    private native int doIntCommandNative(String command);
227
228    private native String doStringCommandNative(String command);
229
230    private boolean doBooleanCommand(String command) {
231        if (DBG) Log.d(mTAG, "doBoolean: " + command);
232        synchronized (sLock) {
233            String toLog = mInterfacePrefix + command;
234            boolean result = doBooleanCommandNative(mInterfacePrefix + command);
235            localLog(toLog + " -> " + result);
236            if (DBG) Log.d(mTAG, command + ": returned " + result);
237            return result;
238        }
239    }
240
241    private boolean doBooleanCommandWithoutLogging(String command) {
242        if (DBG) Log.d(mTAG, "doBooleanCommandWithoutLogging: " + command);
243        synchronized (sLock) {
244            boolean result = doBooleanCommandNative(mInterfacePrefix + command);
245            if (DBG) Log.d(mTAG, command + ": returned " + result);
246            return result;
247        }
248    }
249
250    private int doIntCommand(String command) {
251        if (DBG) Log.d(mTAG, "doInt: " + command);
252        synchronized (sLock) {
253            String toLog = mInterfacePrefix + command;
254            int result = doIntCommandNative(mInterfacePrefix + command);
255            localLog(toLog + " -> " + result);
256            if (DBG) Log.d(mTAG, "   returned " + result);
257            return result;
258        }
259    }
260
261    private String doStringCommand(String command) {
262        if (DBG) {
263            //GET_NETWORK commands flood the logs
264            if (!command.startsWith("GET_NETWORK")) {
265                Log.d(mTAG, "doString: [" + command + "]");
266            }
267        }
268        synchronized (sLock) {
269            String toLog = mInterfacePrefix + command;
270            String result = doStringCommandNative(mInterfacePrefix + command);
271            if (result == null) {
272                if (DBG) Log.d(mTAG, "doStringCommandNative no result");
273            } else {
274                if (!command.startsWith("STATUS-")) {
275                    localLog(toLog + " -> " + result);
276                }
277                if (DBG) Log.d(mTAG, "   returned " + result.replace("\n", " "));
278            }
279            return result;
280        }
281    }
282
283    private String doStringCommandWithoutLogging(String command) {
284        if (DBG) {
285            //GET_NETWORK commands flood the logs
286            if (!command.startsWith("GET_NETWORK")) {
287                Log.d(mTAG, "doString: [" + command + "]");
288            }
289        }
290        synchronized (sLock) {
291            return doStringCommandNative(mInterfacePrefix + command);
292        }
293    }
294
295    public String doCustomSupplicantCommand(String command) {
296        return doStringCommand(command);
297    }
298
299    /*
300     * Wrappers for supplicant commands
301     */
302    public boolean ping() {
303        String pong = doStringCommand("PING");
304        return (pong != null && pong.equals("PONG"));
305    }
306
307    public void setSupplicantLogLevel(String level) {
308        doStringCommand("LOG_LEVEL " + level);
309    }
310
311    public String getFreqCapability() {
312        return doStringCommand("GET_CAPABILITY freq");
313    }
314
315
316    public static final int SCAN_WITHOUT_CONNECTION_SETUP          = 1;
317    public static final int SCAN_WITH_CONNECTION_SETUP             = 2;
318
319    public boolean scan(int type, Set<Integer> freqs) {
320        if(freqs == null) {
321            return scan(type, (String)null);
322        }
323        else if (freqs.size() != 0) {
324            StringBuilder freqList = new StringBuilder();
325            boolean first = true;
326            for (Integer freq : freqs) {
327                if (!first)
328                    freqList.append(",");
329                freqList.append(freq.toString());
330                first = false;
331            }
332            return scan(type, freqList.toString());
333        }
334        else {
335            return false;
336        }
337    }
338
339    private boolean scan(int type, String freqList) {
340        if (type == SCAN_WITHOUT_CONNECTION_SETUP) {
341            if (freqList == null) return doBooleanCommand("SCAN TYPE=ONLY");
342            else return doBooleanCommand("SCAN TYPE=ONLY freq=" + freqList);
343        } else if (type == SCAN_WITH_CONNECTION_SETUP) {
344            if (freqList == null) return doBooleanCommand("SCAN");
345            else return doBooleanCommand("SCAN freq=" + freqList);
346        } else {
347            throw new IllegalArgumentException("Invalid scan type");
348        }
349    }
350
351    /* Does a graceful shutdown of supplicant. Is a common stop function for both p2p and sta.
352     *
353     * Note that underneath we use a harsh-sounding "terminate" supplicant command
354     * for a graceful stop and a mild-sounding "stop" interface
355     * to kill the process
356     */
357    public boolean stopSupplicant() {
358        return doBooleanCommand("TERMINATE");
359    }
360
361    public String listNetworks() {
362        return doStringCommand("LIST_NETWORKS");
363    }
364
365    public String listNetworks(int last_id) {
366        return doStringCommand("LIST_NETWORKS LAST_ID=" + last_id);
367    }
368
369    public int addNetwork() {
370        return doIntCommand("ADD_NETWORK");
371    }
372
373    public boolean setNetworkVariable(int netId, String name, String value) {
374        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) return false;
375        if (name.equals(WifiConfiguration.pskVarName)
376                || name.equals(WifiEnterpriseConfig.PASSWORD_KEY)) {
377            return doBooleanCommandWithoutLogging("SET_NETWORK " + netId + " " + name + " " + value);
378        } else {
379            return doBooleanCommand("SET_NETWORK " + netId + " " + name + " " + value);
380        }
381    }
382
383    public String getNetworkVariable(int netId, String name) {
384        if (TextUtils.isEmpty(name)) return null;
385
386        // GET_NETWORK will likely flood the logs ...
387        return doStringCommandWithoutLogging("GET_NETWORK " + netId + " " + name);
388    }
389
390    public boolean removeNetwork(int netId) {
391        return doBooleanCommand("REMOVE_NETWORK " + netId);
392    }
393
394
395    private void logDbg(String debug) {
396        long now = SystemClock.elapsedRealtimeNanos();
397        String ts = String.format("[%,d us] ", now/1000);
398        Log.e("WifiNative: ", ts+debug+ " stack:"
399                + Thread.currentThread().getStackTrace()[2].getMethodName() +" - "
400                + Thread.currentThread().getStackTrace()[3].getMethodName() +" - "
401                + Thread.currentThread().getStackTrace()[4].getMethodName() +" - "
402                + Thread.currentThread().getStackTrace()[5].getMethodName()+" - "
403                + Thread.currentThread().getStackTrace()[6].getMethodName());
404
405    }
406    public boolean enableNetwork(int netId, boolean disableOthers) {
407        if (DBG) logDbg("enableNetwork nid=" + Integer.toString(netId)
408                + " disableOthers=" + disableOthers);
409        if (disableOthers) {
410            return doBooleanCommand("SELECT_NETWORK " + netId);
411        } else {
412            return doBooleanCommand("ENABLE_NETWORK " + netId);
413        }
414    }
415
416    public boolean disableNetwork(int netId) {
417        if (DBG) logDbg("disableNetwork nid=" + Integer.toString(netId));
418        return doBooleanCommand("DISABLE_NETWORK " + netId);
419    }
420
421    public boolean selectNetwork(int netId) {
422        if (DBG) logDbg("selectNetwork nid=" + Integer.toString(netId));
423        return doBooleanCommand("SELECT_NETWORK " + netId);
424    }
425
426    public boolean reconnect() {
427        if (DBG) logDbg("RECONNECT ");
428        return doBooleanCommand("RECONNECT");
429    }
430
431    public boolean reassociate() {
432        if (DBG) logDbg("REASSOCIATE ");
433        return doBooleanCommand("REASSOCIATE");
434    }
435
436    public boolean disconnect() {
437        if (DBG) logDbg("DISCONNECT ");
438        return doBooleanCommand("DISCONNECT");
439    }
440
441    public String status() {
442        return status(false);
443    }
444
445    public String status(boolean noEvents) {
446        if (noEvents) {
447            return doStringCommand("STATUS-NO_EVENTS");
448        } else {
449            return doStringCommand("STATUS");
450        }
451    }
452
453    public String getMacAddress() {
454        //Macaddr = XX.XX.XX.XX.XX.XX
455        String ret = doStringCommand("DRIVER MACADDR");
456        if (!TextUtils.isEmpty(ret)) {
457            String[] tokens = ret.split(" = ");
458            if (tokens.length == 2) return tokens[1];
459        }
460        return null;
461    }
462
463
464
465    /**
466     * Format of results:
467     * =================
468     * id=1
469     * bssid=68:7f:76:d7:1a:6e
470     * freq=2412
471     * level=-44
472     * tsf=1344626243700342
473     * flags=[WPA2-PSK-CCMP][WPS][ESS]
474     * ssid=zfdy
475     * ====
476     * id=2
477     * bssid=68:5f:74:d7:1a:6f
478     * freq=5180
479     * level=-73
480     * tsf=1344626243700373
481     * flags=[WPA2-PSK-CCMP][WPS][ESS]
482     * ssid=zuby
483     * ====
484     *
485     * RANGE=ALL gets all scan results
486     * RANGE=ID- gets results from ID
487     * MASK=<N> see wpa_supplicant/src/common/wpa_ctrl.h for details
488     * 0                         0                        1                       0     2
489     *                           WPA_BSS_MASK_MESH_SCAN | WPA_BSS_MASK_DELIM    | WPA_BSS_MASK_WIFI_DISPLAY
490     * 0                         0                        0                       1     1   -> 9
491     * WPA_BSS_MASK_INTERNETW  | WPA_BSS_MASK_P2P_SCAN  | WPA_BSS_MASK_WPS_SCAN | WPA_BSS_MASK_SSID
492     * 1                         0                        0                       1     9   -> d
493     * WPA_BSS_MASK_FLAGS      | WPA_BSS_MASK_IE        | WPA_BSS_MASK_AGE      | WPA_BSS_MASK_TSF
494     * 1                         0                        0                       0     8
495     * WPA_BSS_MASK_LEVEL      | WPA_BSS_MASK_NOISE     | WPA_BSS_MASK_QUAL     | WPA_BSS_MASK_CAPABILITIES
496     * 0                         1                        1                       1     7
497     * WPA_BSS_MASK_BEACON_INT | WPA_BSS_MASK_FREQ      | WPA_BSS_MASK_BSSID    | WPA_BSS_MASK_ID
498     *
499     * WPA_BSS_MASK_INTERNETW adds ANQP info (ctrl_iface:4151-4176)
500     *
501     * ctrl_iface.c:wpa_supplicant_ctrl_iface_process:7884
502     *  wpa_supplicant_ctrl_iface_bss:4315
503     *  print_bss_info
504     */
505    private String getRawScanResults(String range) {
506        return doStringCommandWithoutLogging("BSS RANGE=" + range + " MASK=0x29d87");
507    }
508
509    private static final String BSS_IE_STR = "ie=";
510    private static final String BSS_ID_STR = "id=";
511    private static final String BSS_BSSID_STR = "bssid=";
512    private static final String BSS_FREQ_STR = "freq=";
513    private static final String BSS_LEVEL_STR = "level=";
514    private static final String BSS_TSF_STR = "tsf=";
515    private static final String BSS_FLAGS_STR = "flags=";
516    private static final String BSS_SSID_STR = "ssid=";
517    private static final String BSS_DELIMITER_STR = "====";
518    private static final String BSS_END_STR = "####";
519
520    public ArrayList<ScanDetail> getScanResults() {
521        int next_sid = 0;
522        ArrayList<ScanDetail> results = new ArrayList<>();
523        while(next_sid >= 0) {
524            String rawResult = getRawScanResults(next_sid+"-");
525            next_sid = -1;
526
527            if (TextUtils.isEmpty(rawResult))
528                break;
529
530            String[] lines = rawResult.split("\n");
531
532
533            // note that all these splits and substrings keep references to the original
534            // huge string buffer while the amount we really want is generally pretty small
535            // so make copies instead (one example b/11087956 wasted 400k of heap here).
536            final int bssidStrLen = BSS_BSSID_STR.length();
537            final int flagLen = BSS_FLAGS_STR.length();
538
539            String bssid = "";
540            int level = 0;
541            int freq = 0;
542            long tsf = 0;
543            String flags = "";
544            WifiSsid wifiSsid = null;
545            String infoElementsStr = null;
546            List<String> anqpLines = null;
547
548            for (String line : lines) {
549                if (line.startsWith(BSS_ID_STR)) { // Will find the last id line
550                    try {
551                        next_sid = Integer.parseInt(line.substring(BSS_ID_STR.length())) + 1;
552                    } catch (NumberFormatException e) {
553                        // Nothing to do
554                    }
555                } else if (line.startsWith(BSS_BSSID_STR)) {
556                    bssid = new String(line.getBytes(), bssidStrLen, line.length() - bssidStrLen);
557                } else if (line.startsWith(BSS_FREQ_STR)) {
558                    try {
559                        freq = Integer.parseInt(line.substring(BSS_FREQ_STR.length()));
560                    } catch (NumberFormatException e) {
561                        freq = 0;
562                    }
563                } else if (line.startsWith(BSS_LEVEL_STR)) {
564                    try {
565                        level = Integer.parseInt(line.substring(BSS_LEVEL_STR.length()));
566                        /* some implementations avoid negative values by adding 256
567                         * so we need to adjust for that here.
568                         */
569                        if (level > 0) level -= 256;
570                    } catch (NumberFormatException e) {
571                        level = 0;
572                    }
573                } else if (line.startsWith(BSS_TSF_STR)) {
574                    try {
575                        tsf = Long.parseLong(line.substring(BSS_TSF_STR.length()));
576                    } catch (NumberFormatException e) {
577                        tsf = 0;
578                    }
579                } else if (line.startsWith(BSS_FLAGS_STR)) {
580                    flags = new String(line.getBytes(), flagLen, line.length() - flagLen);
581                } else if (line.startsWith(BSS_SSID_STR)) {
582                    wifiSsid = WifiSsid.createFromAsciiEncoded(
583                            line.substring(BSS_SSID_STR.length()));
584                } else if (line.startsWith(BSS_IE_STR)) {
585                    infoElementsStr = line;
586                } else if (SupplicantBridge.isAnqpAttribute(line)) {
587                    if (anqpLines == null) {
588                        anqpLines = new ArrayList<>();
589                    }
590                    anqpLines.add(line);
591                } else if (line.startsWith(BSS_DELIMITER_STR) || line.startsWith(BSS_END_STR)) {
592                    if (bssid != null) {
593                        try {
594                            if (infoElementsStr == null) {
595                                throw new IllegalArgumentException("Null information element data");
596                            }
597                            int seperator = infoElementsStr.indexOf('=');
598                            if (seperator < 0) {
599                                throw new IllegalArgumentException("No element separator");
600                            }
601
602                            ScanResult.InformationElement[] infoElements =
603                                        InformationElementUtil.parseInformationElements(
604                                        Utils.hexToBytes(infoElementsStr.substring(seperator + 1)));
605
606                            NetworkDetail networkDetail = new NetworkDetail(bssid,
607                                    infoElements, anqpLines, freq);
608
609                            String xssid = (wifiSsid != null) ? wifiSsid.toString() : WifiSsid.NONE;
610                            if (!xssid.equals(networkDetail.getTrimmedSSID())) {
611                                Log.d(TAG, String.format(
612                                        "Inconsistent SSID on BSSID '%s': '%s' vs '%s': %s",
613                                        bssid, xssid, networkDetail.getSSID(), infoElementsStr));
614                            }
615
616                            if (networkDetail.hasInterworking()) {
617                                Log.d(TAG, "HSNwk: '" + networkDetail);
618                            }
619                            ScanDetail scan = new ScanDetail(networkDetail, wifiSsid, bssid, flags,
620                                    level, freq, tsf);
621                            scan.getScanResult().informationElements = infoElements;
622                            results.add(scan);
623                        } catch (IllegalArgumentException iae) {
624                            Log.d(TAG, "Failed to parse information elements: " + iae);
625                        }
626                    }
627                    bssid = null;
628                    level = 0;
629                    freq = 0;
630                    tsf = 0;
631                    flags = "";
632                    wifiSsid = null;
633                    infoElementsStr = null;
634                    anqpLines = null;
635                }
636            }
637        }
638        return results;
639    }
640
641    /**
642     * Format of result:
643     * id=1016
644     * bssid=00:03:7f:40:84:10
645     * freq=2462
646     * beacon_int=200
647     * capabilities=0x0431
648     * qual=0
649     * noise=0
650     * level=-46
651     * tsf=0000002669008476
652     * age=5
653     * ie=00105143412d485332302d52322d54455354010882848b960c12182403010b0706555...
654     * flags=[WPA2-EAP-CCMP][ESS][P2P][HS20]
655     * ssid=QCA-HS20-R2-TEST
656     * p2p_device_name=
657     * p2p_config_methods=0x0SET_NE
658     * anqp_venue_name=02083d656e6757692d466920416c6c69616e63650a3239383920436f...
659     * anqp_network_auth_type=010000
660     * anqp_roaming_consortium=03506f9a05001bc504bd
661     * anqp_ip_addr_type_availability=0c
662     * anqp_nai_realm=0200300000246d61696c2e6578616d706c652e636f6d3b636973636f2...
663     * anqp_3gpp=000600040132f465
664     * anqp_domain_name=0b65786d61706c652e636f6d
665     * hs20_operator_friendly_name=11656e6757692d466920416c6c69616e63650e636869...
666     * hs20_wan_metrics=01c40900008001000000000a00
667     * hs20_connection_capability=0100000006140001061600000650000106bb010106bb0...
668     * hs20_osu_providers_list=0b5143412d4f53552d425353010901310015656e6757692d...
669     */
670    public String scanResult(String bssid) {
671        return doStringCommand("BSS " + bssid);
672    }
673
674    public boolean startDriver() {
675        return doBooleanCommand("DRIVER START");
676    }
677
678    public boolean stopDriver() {
679        return doBooleanCommand("DRIVER STOP");
680    }
681
682
683    /**
684     * Start filtering out Multicast V4 packets
685     * @return {@code true} if the operation succeeded, {@code false} otherwise
686     *
687     * Multicast filtering rules work as follows:
688     *
689     * The driver can filter multicast (v4 and/or v6) and broadcast packets when in
690     * a power optimized mode (typically when screen goes off).
691     *
692     * In order to prevent the driver from filtering the multicast/broadcast packets, we have to
693     * add a DRIVER RXFILTER-ADD rule followed by DRIVER RXFILTER-START to make the rule effective
694     *
695     * DRIVER RXFILTER-ADD Num
696     *   where Num = 0 - Unicast, 1 - Broadcast, 2 - Mutil4 or 3 - Multi6
697     *
698     * and DRIVER RXFILTER-START
699     * In order to stop the usage of these rules, we do
700     *
701     * DRIVER RXFILTER-STOP
702     * DRIVER RXFILTER-REMOVE Num
703     *   where Num is as described for RXFILTER-ADD
704     *
705     * The  SETSUSPENDOPT driver command overrides the filtering rules
706     */
707    public boolean startFilteringMulticastV4Packets() {
708        return doBooleanCommand("DRIVER RXFILTER-STOP")
709            && doBooleanCommand("DRIVER RXFILTER-REMOVE 2")
710            && doBooleanCommand("DRIVER RXFILTER-START");
711    }
712
713    /**
714     * Stop filtering out Multicast V4 packets.
715     * @return {@code true} if the operation succeeded, {@code false} otherwise
716     */
717    public boolean stopFilteringMulticastV4Packets() {
718        return doBooleanCommand("DRIVER RXFILTER-STOP")
719            && doBooleanCommand("DRIVER RXFILTER-ADD 2")
720            && doBooleanCommand("DRIVER RXFILTER-START");
721    }
722
723    /**
724     * Start filtering out Multicast V6 packets
725     * @return {@code true} if the operation succeeded, {@code false} otherwise
726     */
727    public boolean startFilteringMulticastV6Packets() {
728        return doBooleanCommand("DRIVER RXFILTER-STOP")
729            && doBooleanCommand("DRIVER RXFILTER-REMOVE 3")
730            && doBooleanCommand("DRIVER RXFILTER-START");
731    }
732
733    /**
734     * Stop filtering out Multicast V6 packets.
735     * @return {@code true} if the operation succeeded, {@code false} otherwise
736     */
737    public boolean stopFilteringMulticastV6Packets() {
738        return doBooleanCommand("DRIVER RXFILTER-STOP")
739            && doBooleanCommand("DRIVER RXFILTER-ADD 3")
740            && doBooleanCommand("DRIVER RXFILTER-START");
741    }
742
743    /**
744     * Set the operational frequency band
745     * @param band One of
746     *     {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
747     *     {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
748     *     {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
749     * @return {@code true} if the operation succeeded, {@code false} otherwise
750     */
751    public boolean setBand(int band) {
752        String bandstr;
753
754        if (band == WifiManager.WIFI_FREQUENCY_BAND_5GHZ)
755            bandstr = "5G";
756        else if (band == WifiManager.WIFI_FREQUENCY_BAND_2GHZ)
757            bandstr = "2G";
758        else
759            bandstr = "AUTO";
760        return doBooleanCommand("SET SETBAND " + bandstr);
761    }
762
763    public static final int BLUETOOTH_COEXISTENCE_MODE_ENABLED     = 0;
764    public static final int BLUETOOTH_COEXISTENCE_MODE_DISABLED    = 1;
765    public static final int BLUETOOTH_COEXISTENCE_MODE_SENSE       = 2;
766    /**
767      * Sets the bluetooth coexistence mode.
768      *
769      * @param mode One of {@link #BLUETOOTH_COEXISTENCE_MODE_DISABLED},
770      *            {@link #BLUETOOTH_COEXISTENCE_MODE_ENABLED}, or
771      *            {@link #BLUETOOTH_COEXISTENCE_MODE_SENSE}.
772      * @return Whether the mode was successfully set.
773      */
774    public boolean setBluetoothCoexistenceMode(int mode) {
775        return doBooleanCommand("DRIVER BTCOEXMODE " + mode);
776    }
777
778    /**
779     * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
780     * some of the low-level scan parameters used by the driver are changed to
781     * reduce interference with A2DP streaming.
782     *
783     * @param isSet whether to enable or disable this mode
784     * @return {@code true} if the command succeeded, {@code false} otherwise.
785     */
786    public boolean setBluetoothCoexistenceScanMode(boolean setCoexScanMode) {
787        if (setCoexScanMode) {
788            return doBooleanCommand("DRIVER BTCOEXSCAN-START");
789        } else {
790            return doBooleanCommand("DRIVER BTCOEXSCAN-STOP");
791        }
792    }
793
794    public void enableSaveConfig() {
795        doBooleanCommand("SET update_config 1");
796    }
797
798    public boolean saveConfig() {
799        return doBooleanCommand("SAVE_CONFIG");
800    }
801
802    public boolean addToBlacklist(String bssid) {
803        if (TextUtils.isEmpty(bssid)) return false;
804        return doBooleanCommand("BLACKLIST " + bssid);
805    }
806
807    public boolean clearBlacklist() {
808        return doBooleanCommand("BLACKLIST clear");
809    }
810
811    public boolean setSuspendOptimizations(boolean enabled) {
812        if (enabled) {
813            return doBooleanCommand("DRIVER SETSUSPENDMODE 1");
814        } else {
815            return doBooleanCommand("DRIVER SETSUSPENDMODE 0");
816        }
817    }
818
819    public boolean setCountryCode(String countryCode) {
820        if (countryCode != null)
821            return doBooleanCommand("DRIVER COUNTRY " + countryCode.toUpperCase(Locale.ROOT));
822        else
823            return doBooleanCommand("DRIVER COUNTRY");
824    }
825
826    //PNO Monitor
827    private class PnoMonitor {
828        private static final int MINIMUM_PNO_GAP = 5 * 1000;
829        private static final String ACTION_TOGGLE_PNO =
830            "com.android.server.Wifi.action.TOGGLE_PNO";
831        long mLastPnoChangeTimeStamp = -1L;
832        boolean mExpectedPnoState = false;
833        boolean mCurrentPnoState = false;;
834        boolean mWaitForTimer = false;
835        final Object mPnoLock = new Object();
836        private final AlarmManager mAlarmManager =
837                (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
838        private final PendingIntent mPnoIntent;
839
840        public PnoMonitor() {
841            Intent intent = new Intent(ACTION_TOGGLE_PNO, null);
842            intent.setPackage("android");
843            mPnoIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
844
845            mContext.registerReceiver(
846                new BroadcastReceiver() {
847                    @Override
848                    public void onReceive(Context context, Intent intent) {
849                        synchronized(mPnoLock) {
850                            if (DBG) Log.d(mTAG, "PNO timer expire, PNO should change to " +
851                                    mExpectedPnoState);
852                            if (mCurrentPnoState != mExpectedPnoState) {
853                                if (DBG) Log.d(mTAG, "change PNO from " + mCurrentPnoState + " to "
854                                        + mExpectedPnoState);
855                                boolean ret = setPno(mExpectedPnoState);
856                                if (!ret) {
857                                    Log.e(mTAG, "set PNO failure");
858                                }
859                            } else {
860                                if (DBG) Log.d(mTAG, "Do not change PNO since current is expected");
861                            }
862                            mWaitForTimer = false;
863                        }
864                    }
865                },
866                new IntentFilter(ACTION_TOGGLE_PNO));
867        }
868
869        private boolean setPno(boolean enable) {
870            String cmd = enable ? "SET pno 1" : "SET pno 0";
871            boolean ret = doBooleanCommand(cmd);
872            mLastPnoChangeTimeStamp = System.currentTimeMillis();
873            if (ret) {
874                mCurrentPnoState = enable;
875            }
876            return ret;
877        }
878
879        public boolean enableBackgroundScan(boolean enable) {
880            synchronized(mPnoLock) {
881                if (mWaitForTimer) {
882                    //already has a timer
883                    mExpectedPnoState = enable;
884                    if (DBG) Log.d(mTAG, "update expected PNO to " +  mExpectedPnoState);
885                } else {
886                    if (mCurrentPnoState == enable) {
887                        return true;
888                    }
889                    long timeDifference = System.currentTimeMillis() - mLastPnoChangeTimeStamp;
890                    if (timeDifference >= MINIMUM_PNO_GAP) {
891                        return setPno(enable);
892                    } else {
893                        mExpectedPnoState = enable;
894                        mWaitForTimer = true;
895                        if (DBG) Log.d(mTAG, "start PNO timer with delay:" + timeDifference);
896                        mAlarmManager.set(AlarmManager.RTC_WAKEUP,
897                                System.currentTimeMillis() + timeDifference, mPnoIntent);
898                    }
899                }
900                return true;
901            }
902        }
903    }
904
905    public boolean enableBackgroundScan(boolean enable) {
906        if (mPnoMonitor != null) {
907            return mPnoMonitor.enableBackgroundScan(enable);
908        } else {
909            return false;
910        }
911    }
912
913    public void enableAutoConnect(boolean enable) {
914        if (enable) {
915            doBooleanCommand("STA_AUTOCONNECT 1");
916        } else {
917            doBooleanCommand("STA_AUTOCONNECT 0");
918        }
919    }
920
921    public void setScanInterval(int scanInterval) {
922        doBooleanCommand("SCAN_INTERVAL " + scanInterval);
923    }
924
925    public void setHs20(boolean hs20) {
926        if (hs20) {
927            doBooleanCommand("SET HS20 1");
928        } else {
929            doBooleanCommand("SET HS20 0");
930        }
931    }
932
933    public void startTdls(String macAddr, boolean enable) {
934        if (enable) {
935            synchronized (sLock) {
936                doBooleanCommand("TDLS_DISCOVER " + macAddr);
937                doBooleanCommand("TDLS_SETUP " + macAddr);
938            }
939        } else {
940            doBooleanCommand("TDLS_TEARDOWN " + macAddr);
941        }
942    }
943
944    /** Example output:
945     * RSSI=-65
946     * LINKSPEED=48
947     * NOISE=9999
948     * FREQUENCY=0
949     */
950    public String signalPoll() {
951        return doStringCommandWithoutLogging("SIGNAL_POLL");
952    }
953
954    /** Example outout:
955     * TXGOOD=396
956     * TXBAD=1
957     */
958    public String pktcntPoll() {
959        return doStringCommand("PKTCNT_POLL");
960    }
961
962    public void bssFlush() {
963        doBooleanCommand("BSS_FLUSH 0");
964    }
965
966    public boolean startWpsPbc(String bssid) {
967        if (TextUtils.isEmpty(bssid)) {
968            return doBooleanCommand("WPS_PBC");
969        } else {
970            return doBooleanCommand("WPS_PBC " + bssid);
971        }
972    }
973
974    public boolean startWpsPbc(String iface, String bssid) {
975        synchronized (sLock) {
976            if (TextUtils.isEmpty(bssid)) {
977                return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC");
978            } else {
979                return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC " + bssid);
980            }
981        }
982    }
983
984    public boolean startWpsPinKeypad(String pin) {
985        if (TextUtils.isEmpty(pin)) return false;
986        return doBooleanCommand("WPS_PIN any " + pin);
987    }
988
989    public boolean startWpsPinKeypad(String iface, String pin) {
990        if (TextUtils.isEmpty(pin)) return false;
991        synchronized (sLock) {
992            return doBooleanCommandNative("IFNAME=" + iface + " WPS_PIN any " + pin);
993        }
994    }
995
996
997    public String startWpsPinDisplay(String bssid) {
998        if (TextUtils.isEmpty(bssid)) {
999            return doStringCommand("WPS_PIN any");
1000        } else {
1001            return doStringCommand("WPS_PIN " + bssid);
1002        }
1003    }
1004
1005    public String startWpsPinDisplay(String iface, String bssid) {
1006        synchronized (sLock) {
1007            if (TextUtils.isEmpty(bssid)) {
1008                return doStringCommandNative("IFNAME=" + iface + " WPS_PIN any");
1009            } else {
1010                return doStringCommandNative("IFNAME=" + iface + " WPS_PIN " + bssid);
1011            }
1012        }
1013    }
1014
1015    public boolean setExternalSim(boolean external) {
1016        String value = external ? "1" : "0";
1017        Log.d(TAG, "Setting external_sim to " + value);
1018        return doBooleanCommand("SET external_sim " + value);
1019    }
1020
1021    public boolean simAuthResponse(int id, String type, String response) {
1022        // with type = GSM-AUTH, UMTS-AUTH or UMTS-AUTS
1023        return doBooleanCommand("CTRL-RSP-SIM-" + id + ":" + type + response);
1024    }
1025
1026    public boolean simAuthFailedResponse(int id) {
1027        // should be used with type GSM-AUTH
1028        return doBooleanCommand("CTRL-RSP-SIM-" + id + ":GSM-FAIL");
1029    }
1030
1031    public boolean umtsAuthFailedResponse(int id) {
1032        // should be used with type UMTS-AUTH
1033        return doBooleanCommand("CTRL-RSP-SIM-" + id + ":UMTS-FAIL");
1034    }
1035
1036    public boolean simIdentityResponse(int id, String response) {
1037        return doBooleanCommand("CTRL-RSP-IDENTITY-" + id + ":" + response);
1038    }
1039
1040    /* Configures an access point connection */
1041    public boolean startWpsRegistrar(String bssid, String pin) {
1042        if (TextUtils.isEmpty(bssid) || TextUtils.isEmpty(pin)) return false;
1043        return doBooleanCommand("WPS_REG " + bssid + " " + pin);
1044    }
1045
1046    public boolean cancelWps() {
1047        return doBooleanCommand("WPS_CANCEL");
1048    }
1049
1050    public boolean setPersistentReconnect(boolean enabled) {
1051        int value = (enabled == true) ? 1 : 0;
1052        return doBooleanCommand("SET persistent_reconnect " + value);
1053    }
1054
1055    public boolean setDeviceName(String name) {
1056        return doBooleanCommand("SET device_name " + name);
1057    }
1058
1059    public boolean setDeviceType(String type) {
1060        return doBooleanCommand("SET device_type " + type);
1061    }
1062
1063    public boolean setConfigMethods(String cfg) {
1064        return doBooleanCommand("SET config_methods " + cfg);
1065    }
1066
1067    public boolean setManufacturer(String value) {
1068        return doBooleanCommand("SET manufacturer " + value);
1069    }
1070
1071    public boolean setModelName(String value) {
1072        return doBooleanCommand("SET model_name " + value);
1073    }
1074
1075    public boolean setModelNumber(String value) {
1076        return doBooleanCommand("SET model_number " + value);
1077    }
1078
1079    public boolean setSerialNumber(String value) {
1080        return doBooleanCommand("SET serial_number " + value);
1081    }
1082
1083    public boolean setP2pSsidPostfix(String postfix) {
1084        return doBooleanCommand("SET p2p_ssid_postfix " + postfix);
1085    }
1086
1087    public boolean setP2pGroupIdle(String iface, int time) {
1088        synchronized (sLock) {
1089            return doBooleanCommandNative("IFNAME=" + iface + " SET p2p_group_idle " + time);
1090        }
1091    }
1092
1093    public void setPowerSave(boolean enabled) {
1094        if (enabled) {
1095            doBooleanCommand("SET ps 1");
1096        } else {
1097            doBooleanCommand("SET ps 0");
1098        }
1099    }
1100
1101    public boolean setP2pPowerSave(String iface, boolean enabled) {
1102        synchronized (sLock) {
1103            if (enabled) {
1104                return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 1");
1105            } else {
1106                return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 0");
1107            }
1108        }
1109    }
1110
1111    public boolean setWfdEnable(boolean enable) {
1112        return doBooleanCommand("SET wifi_display " + (enable ? "1" : "0"));
1113    }
1114
1115    public boolean setWfdDeviceInfo(String hex) {
1116        return doBooleanCommand("WFD_SUBELEM_SET 0 " + hex);
1117    }
1118
1119    /**
1120     * "sta" prioritizes STA connection over P2P and "p2p" prioritizes
1121     * P2P connection over STA
1122     */
1123    public boolean setConcurrencyPriority(String s) {
1124        return doBooleanCommand("P2P_SET conc_pref " + s);
1125    }
1126
1127    public boolean p2pFind() {
1128        return doBooleanCommand("P2P_FIND");
1129    }
1130
1131    public boolean p2pFind(int timeout) {
1132        if (timeout <= 0) {
1133            return p2pFind();
1134        }
1135        return doBooleanCommand("P2P_FIND " + timeout);
1136    }
1137
1138    public boolean p2pStopFind() {
1139       return doBooleanCommand("P2P_STOP_FIND");
1140    }
1141
1142    public boolean p2pListen() {
1143        return doBooleanCommand("P2P_LISTEN");
1144    }
1145
1146    public boolean p2pListen(int timeout) {
1147        if (timeout <= 0) {
1148            return p2pListen();
1149        }
1150        return doBooleanCommand("P2P_LISTEN " + timeout);
1151    }
1152
1153    public boolean p2pExtListen(boolean enable, int period, int interval) {
1154        if (enable && interval < period) {
1155            return false;
1156        }
1157        return doBooleanCommand("P2P_EXT_LISTEN"
1158                    + (enable ? (" " + period + " " + interval) : ""));
1159    }
1160
1161    public boolean p2pSetChannel(int lc, int oc) {
1162        if (DBG) Log.d(mTAG, "p2pSetChannel: lc="+lc+", oc="+oc);
1163
1164        synchronized (sLock) {
1165            if (lc >=1 && lc <= 11) {
1166                if (!doBooleanCommand("P2P_SET listen_channel " + lc)) {
1167                    return false;
1168                }
1169            } else if (lc != 0) {
1170                return false;
1171            }
1172
1173            if (oc >= 1 && oc <= 165 ) {
1174                int freq = (oc <= 14 ? 2407 : 5000) + oc * 5;
1175                return doBooleanCommand("P2P_SET disallow_freq 1000-"
1176                        + (freq - 5) + "," + (freq + 5) + "-6000");
1177            } else if (oc == 0) {
1178                /* oc==0 disables "P2P_SET disallow_freq" (enables all freqs) */
1179                return doBooleanCommand("P2P_SET disallow_freq \"\"");
1180            }
1181        }
1182        return false;
1183    }
1184
1185    public boolean p2pFlush() {
1186        return doBooleanCommand("P2P_FLUSH");
1187    }
1188
1189    private static final int DEFAULT_GROUP_OWNER_INTENT     = 6;
1190    /* p2p_connect <peer device address> <pbc|pin|PIN#> [label|display|keypad]
1191        [persistent] [join|auth] [go_intent=<0..15>] [freq=<in MHz>] */
1192    public String p2pConnect(WifiP2pConfig config, boolean joinExistingGroup) {
1193        if (config == null) return null;
1194        List<String> args = new ArrayList<String>();
1195        WpsInfo wps = config.wps;
1196        args.add(config.deviceAddress);
1197
1198        switch (wps.setup) {
1199            case WpsInfo.PBC:
1200                args.add("pbc");
1201                break;
1202            case WpsInfo.DISPLAY:
1203                if (TextUtils.isEmpty(wps.pin)) {
1204                    args.add("pin");
1205                } else {
1206                    args.add(wps.pin);
1207                }
1208                args.add("display");
1209                break;
1210            case WpsInfo.KEYPAD:
1211                args.add(wps.pin);
1212                args.add("keypad");
1213                break;
1214            case WpsInfo.LABEL:
1215                args.add(wps.pin);
1216                args.add("label");
1217            default:
1218                break;
1219        }
1220
1221        if (config.netId == WifiP2pGroup.PERSISTENT_NET_ID) {
1222            args.add("persistent");
1223        }
1224
1225        if (joinExistingGroup) {
1226            args.add("join");
1227        } else {
1228            //TODO: This can be adapted based on device plugged in state and
1229            //device battery state
1230            int groupOwnerIntent = config.groupOwnerIntent;
1231            if (groupOwnerIntent < 0 || groupOwnerIntent > 15) {
1232                groupOwnerIntent = DEFAULT_GROUP_OWNER_INTENT;
1233            }
1234            args.add("go_intent=" + groupOwnerIntent);
1235        }
1236
1237        String command = "P2P_CONNECT ";
1238        for (String s : args) command += s + " ";
1239
1240        return doStringCommand(command);
1241    }
1242
1243    public boolean p2pCancelConnect() {
1244        return doBooleanCommand("P2P_CANCEL");
1245    }
1246
1247    public boolean p2pProvisionDiscovery(WifiP2pConfig config) {
1248        if (config == null) return false;
1249
1250        switch (config.wps.setup) {
1251            case WpsInfo.PBC:
1252                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " pbc");
1253            case WpsInfo.DISPLAY:
1254                //We are doing display, so provision discovery is keypad
1255                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " keypad");
1256            case WpsInfo.KEYPAD:
1257                //We are doing keypad, so provision discovery is display
1258                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " display");
1259            default:
1260                break;
1261        }
1262        return false;
1263    }
1264
1265    public boolean p2pGroupAdd(boolean persistent) {
1266        if (persistent) {
1267            return doBooleanCommand("P2P_GROUP_ADD persistent");
1268        }
1269        return doBooleanCommand("P2P_GROUP_ADD");
1270    }
1271
1272    public boolean p2pGroupAdd(int netId) {
1273        return doBooleanCommand("P2P_GROUP_ADD persistent=" + netId);
1274    }
1275
1276    public boolean p2pGroupRemove(String iface) {
1277        if (TextUtils.isEmpty(iface)) return false;
1278        synchronized (sLock) {
1279            return doBooleanCommandNative("IFNAME=" + iface + " P2P_GROUP_REMOVE " + iface);
1280        }
1281    }
1282
1283    public boolean p2pReject(String deviceAddress) {
1284        return doBooleanCommand("P2P_REJECT " + deviceAddress);
1285    }
1286
1287    /* Invite a peer to a group */
1288    public boolean p2pInvite(WifiP2pGroup group, String deviceAddress) {
1289        if (TextUtils.isEmpty(deviceAddress)) return false;
1290
1291        if (group == null) {
1292            return doBooleanCommand("P2P_INVITE peer=" + deviceAddress);
1293        } else {
1294            return doBooleanCommand("P2P_INVITE group=" + group.getInterface()
1295                    + " peer=" + deviceAddress + " go_dev_addr=" + group.getOwner().deviceAddress);
1296        }
1297    }
1298
1299    /* Reinvoke a persistent connection */
1300    public boolean p2pReinvoke(int netId, String deviceAddress) {
1301        if (TextUtils.isEmpty(deviceAddress) || netId < 0) return false;
1302
1303        return doBooleanCommand("P2P_INVITE persistent=" + netId + " peer=" + deviceAddress);
1304    }
1305
1306    public String p2pGetSsid(String deviceAddress) {
1307        return p2pGetParam(deviceAddress, "oper_ssid");
1308    }
1309
1310    public String p2pGetDeviceAddress() {
1311        Log.d(TAG, "p2pGetDeviceAddress");
1312
1313        String status = null;
1314
1315        /* Explicitly calling the API without IFNAME= prefix to take care of the devices that
1316        don't have p2p0 interface. Supplicant seems to be returning the correct address anyway. */
1317
1318        synchronized (sLock) {
1319            status = doStringCommandNative("STATUS");
1320        }
1321
1322        String result = "";
1323        if (status != null) {
1324            String[] tokens = status.split("\n");
1325            for (String token : tokens) {
1326                if (token.startsWith("p2p_device_address=")) {
1327                    String[] nameValue = token.split("=");
1328                    if (nameValue.length != 2)
1329                        break;
1330                    result = nameValue[1];
1331                }
1332            }
1333        }
1334
1335        Log.d(TAG, "p2pGetDeviceAddress returning " + result);
1336        return result;
1337    }
1338
1339    public int getGroupCapability(String deviceAddress) {
1340        int gc = 0;
1341        if (TextUtils.isEmpty(deviceAddress)) return gc;
1342        String peerInfo = p2pPeer(deviceAddress);
1343        if (TextUtils.isEmpty(peerInfo)) return gc;
1344
1345        String[] tokens = peerInfo.split("\n");
1346        for (String token : tokens) {
1347            if (token.startsWith("group_capab=")) {
1348                String[] nameValue = token.split("=");
1349                if (nameValue.length != 2) break;
1350                try {
1351                    return Integer.decode(nameValue[1]);
1352                } catch(NumberFormatException e) {
1353                    return gc;
1354                }
1355            }
1356        }
1357        return gc;
1358    }
1359
1360    public String p2pPeer(String deviceAddress) {
1361        return doStringCommand("P2P_PEER " + deviceAddress);
1362    }
1363
1364    private String p2pGetParam(String deviceAddress, String key) {
1365        if (deviceAddress == null) return null;
1366
1367        String peerInfo = p2pPeer(deviceAddress);
1368        if (peerInfo == null) return null;
1369        String[] tokens= peerInfo.split("\n");
1370
1371        key += "=";
1372        for (String token : tokens) {
1373            if (token.startsWith(key)) {
1374                String[] nameValue = token.split("=");
1375                if (nameValue.length != 2) break;
1376                return nameValue[1];
1377            }
1378        }
1379        return null;
1380    }
1381
1382    public boolean p2pServiceAdd(WifiP2pServiceInfo servInfo) {
1383        /*
1384         * P2P_SERVICE_ADD bonjour <query hexdump> <RDATA hexdump>
1385         * P2P_SERVICE_ADD upnp <version hex> <service>
1386         *
1387         * e.g)
1388         * [Bonjour]
1389         * # IP Printing over TCP (PTR) (RDATA=MyPrinter._ipp._tcp.local.)
1390         * P2P_SERVICE_ADD bonjour 045f697070c00c000c01 094d795072696e746572c027
1391         * # IP Printing over TCP (TXT) (RDATA=txtvers=1,pdl=application/postscript)
1392         * P2P_SERVICE_ADD bonjour 096d797072696e746572045f697070c00c001001
1393         *  09747874766572733d311a70646c3d6170706c69636174696f6e2f706f7374736372797074
1394         *
1395         * [UPnP]
1396         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012
1397         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice
1398         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp
1399         * -org:device:InternetGatewayDevice:1
1400         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9322-123456789012::urn:schemas-upnp
1401         * -org:service:ContentDirectory:2
1402         */
1403        synchronized (sLock) {
1404            for (String s : servInfo.getSupplicantQueryList()) {
1405                String command = "P2P_SERVICE_ADD";
1406                command += (" " + s);
1407                if (!doBooleanCommand(command)) {
1408                    return false;
1409                }
1410            }
1411        }
1412        return true;
1413    }
1414
1415    public boolean p2pServiceDel(WifiP2pServiceInfo servInfo) {
1416        /*
1417         * P2P_SERVICE_DEL bonjour <query hexdump>
1418         * P2P_SERVICE_DEL upnp <version hex> <service>
1419         */
1420        synchronized (sLock) {
1421            for (String s : servInfo.getSupplicantQueryList()) {
1422                String command = "P2P_SERVICE_DEL ";
1423
1424                String[] data = s.split(" ");
1425                if (data.length < 2) {
1426                    return false;
1427                }
1428                if ("upnp".equals(data[0])) {
1429                    command += s;
1430                } else if ("bonjour".equals(data[0])) {
1431                    command += data[0];
1432                    command += (" " + data[1]);
1433                } else {
1434                    return false;
1435                }
1436                if (!doBooleanCommand(command)) {
1437                    return false;
1438                }
1439            }
1440        }
1441        return true;
1442    }
1443
1444    public boolean p2pServiceFlush() {
1445        return doBooleanCommand("P2P_SERVICE_FLUSH");
1446    }
1447
1448    public String p2pServDiscReq(String addr, String query) {
1449        String command = "P2P_SERV_DISC_REQ";
1450        command += (" " + addr);
1451        command += (" " + query);
1452
1453        return doStringCommand(command);
1454    }
1455
1456    public boolean p2pServDiscCancelReq(String id) {
1457        return doBooleanCommand("P2P_SERV_DISC_CANCEL_REQ " + id);
1458    }
1459
1460    /* Set the current mode of miracast operation.
1461     *  0 = disabled
1462     *  1 = operating as source
1463     *  2 = operating as sink
1464     */
1465    public void setMiracastMode(int mode) {
1466        // Note: optional feature on the driver. It is ok for this to fail.
1467        doBooleanCommand("DRIVER MIRACAST " + mode);
1468    }
1469
1470    public boolean fetchAnqp(String bssid, String subtypes) {
1471        return doBooleanCommand("ANQP_GET " + bssid + " " + subtypes);
1472    }
1473
1474    /*
1475     * NFC-related calls
1476     */
1477    public String getNfcWpsConfigurationToken(int netId) {
1478        return doStringCommand("WPS_NFC_CONFIG_TOKEN WPS " + netId);
1479    }
1480
1481    public String getNfcHandoverRequest() {
1482        return doStringCommand("NFC_GET_HANDOVER_REQ NDEF P2P-CR");
1483    }
1484
1485    public String getNfcHandoverSelect() {
1486        return doStringCommand("NFC_GET_HANDOVER_SEL NDEF P2P-CR");
1487    }
1488
1489    public boolean initiatorReportNfcHandover(String selectMessage) {
1490        return doBooleanCommand("NFC_REPORT_HANDOVER INIT P2P 00 " + selectMessage);
1491    }
1492
1493    public boolean responderReportNfcHandover(String requestMessage) {
1494        return doBooleanCommand("NFC_REPORT_HANDOVER RESP P2P " + requestMessage + " 00");
1495    }
1496
1497    /* WIFI HAL support */
1498
1499    // HAL command ids
1500    private static int sCmdId = 1;
1501    private static int getNewCmdIdLocked() {
1502        return sCmdId++;
1503    }
1504
1505    private static final String TAG = "WifiNative-HAL";
1506    private static long sWifiHalHandle = 0;             /* used by JNI to save wifi_handle */
1507    private static long[] sWifiIfaceHandles = null;     /* used by JNI to save interface handles */
1508    public static int sWlan0Index = -1;
1509    private static int sP2p0Index = -1;
1510    private static MonitorThread sThread;
1511    private static final int STOP_HAL_TIMEOUT_MS = 1000;
1512
1513    private static native boolean startHalNative();
1514    private static native void stopHalNative();
1515    private static native void waitForHalEventNative();
1516
1517    private static class MonitorThread extends Thread {
1518        public void run() {
1519            Log.i(TAG, "Waiting for HAL events mWifiHalHandle=" + Long.toString(sWifiHalHandle));
1520            waitForHalEventNative();
1521        }
1522    }
1523
1524    public boolean startHal() {
1525        String debugLog = "startHal stack: ";
1526        java.lang.StackTraceElement[] elements = Thread.currentThread().getStackTrace();
1527        for (int i = 2; i < elements.length && i <= 7; i++ ) {
1528            debugLog = debugLog + " - " + elements[i].getMethodName();
1529        }
1530
1531        sLocalLog.log(debugLog);
1532
1533        synchronized (sLock) {
1534            if (startHalNative() && (getInterfaces() != 0) && (sWlan0Index != -1)) {
1535                sThread = new MonitorThread();
1536                sThread.start();
1537                return true;
1538            } else {
1539                if (DBG) sLocalLog.log("Could not start hal");
1540                Log.e(TAG, "Could not start hal");
1541                return false;
1542            }
1543        }
1544    }
1545
1546    public void stopHal() {
1547        synchronized (sLock) {
1548            if (isHalStarted()) {
1549                stopHalNative();
1550                try {
1551                    sThread.join(STOP_HAL_TIMEOUT_MS);
1552                    Log.d(TAG, "HAL event thread stopped successfully");
1553                } catch (InterruptedException e) {
1554                    Log.e(TAG, "Could not stop HAL cleanly");
1555                }
1556                sThread = null;
1557                sWifiHalHandle = 0;
1558                sWifiIfaceHandles = null;
1559                sWlan0Index = -1;
1560                sP2p0Index = -1;
1561            }
1562        }
1563    }
1564
1565    public boolean isHalStarted() {
1566        return (sWifiHalHandle != 0);
1567    }
1568    private static native int getInterfacesNative();
1569
1570    public int getInterfaces() {
1571        synchronized (sLock) {
1572            if (isHalStarted()) {
1573                if (sWifiIfaceHandles == null) {
1574                    int num = getInterfacesNative();
1575                    int wifi_num = 0;
1576                    for (int i = 0; i < num; i++) {
1577                        String name = getInterfaceNameNative(i);
1578                        Log.i(TAG, "interface[" + i + "] = " + name);
1579                        if (name.equals("wlan0")) {
1580                            sWlan0Index = i;
1581                            wifi_num++;
1582                        } else if (name.equals("p2p0")) {
1583                            sP2p0Index = i;
1584                            wifi_num++;
1585                        }
1586                    }
1587                    return wifi_num;
1588                } else {
1589                    return sWifiIfaceHandles.length;
1590                }
1591            } else {
1592                return 0;
1593            }
1594        }
1595    }
1596
1597    private static native String getInterfaceNameNative(int index);
1598    public String getInterfaceName(int index) {
1599        synchronized (sLock) {
1600            return getInterfaceNameNative(index);
1601        }
1602    }
1603
1604    // TODO: Change variable names to camel style.
1605    public static class ScanCapabilities {
1606        public int  max_scan_cache_size;
1607        public int  max_scan_buckets;
1608        public int  max_ap_cache_per_scan;
1609        public int  max_rssi_sample_size;
1610        public int  max_scan_reporting_threshold;
1611        public int  max_hotlist_bssids;
1612        public int  max_significant_wifi_change_aps;
1613    }
1614
1615    public boolean getScanCapabilities(ScanCapabilities capabilities) {
1616        synchronized (sLock) {
1617            return isHalStarted() && getScanCapabilitiesNative(sWlan0Index, capabilities);
1618        }
1619    }
1620
1621    private static native boolean getScanCapabilitiesNative(
1622            int iface, ScanCapabilities capabilities);
1623
1624    private static native boolean startScanNative(int iface, int id, ScanSettings settings);
1625    private static native boolean stopScanNative(int iface, int id);
1626    private static native WifiScanner.ScanData[] getScanResultsNative(int iface, boolean flush);
1627    private static native WifiLinkLayerStats getWifiLinkLayerStatsNative(int iface);
1628    private static native void setWifiLinkLayerStatsNative(int iface, int enable);
1629
1630    public static class ChannelSettings {
1631        int frequency;
1632        int dwell_time_ms;
1633        boolean passive;
1634    }
1635
1636    public static class BucketSettings {
1637        int bucket;
1638        int band;
1639        int period_ms;
1640        int max_period_ms;
1641        int step_count;
1642        int report_events;
1643        int num_channels;
1644        ChannelSettings channels[];
1645    }
1646
1647    public static class ScanSettings {
1648        int base_period_ms;
1649        int max_ap_per_scan;
1650        int report_threshold_percent;
1651        int report_threshold_num_scans;
1652        int num_buckets;
1653        BucketSettings buckets[];
1654    }
1655
1656    public static interface ScanEventHandler {
1657        void onScanResultsAvailable();
1658        void onFullScanResult(ScanResult fullScanResult);
1659        void onScanStatus();
1660        void onScanPaused(WifiScanner.ScanData[] data);
1661        void onScanRestarted();
1662    }
1663
1664    // Callback from native
1665    private static void onScanResultsAvailable(int id) {
1666        ScanEventHandler handler = sScanEventHandler;
1667        if (handler != null) {
1668            handler.onScanResultsAvailable();
1669        }
1670    }
1671
1672    /* scan status, keep these values in sync with gscan.h */
1673    private static int WIFI_SCAN_BUFFER_FULL = 0;
1674    private static int WIFI_SCAN_COMPLETE = 1;
1675
1676    // Callback from native
1677    private static void onScanStatus(int status) {
1678        ScanEventHandler handler = sScanEventHandler;
1679        if (status == WIFI_SCAN_BUFFER_FULL) {
1680            /* we have a separate event to take care of this */
1681        } else if (status == WIFI_SCAN_COMPLETE) {
1682            if (handler != null) {
1683                handler.onScanStatus();
1684            }
1685        }
1686    }
1687
1688    public static  WifiSsid createWifiSsid(byte[] rawSsid) {
1689        String ssidHexString = String.valueOf(HexEncoding.encode(rawSsid));
1690
1691        if (ssidHexString == null) {
1692            return null;
1693        }
1694
1695        WifiSsid wifiSsid = WifiSsid.createFromHex(ssidHexString);
1696
1697        return wifiSsid;
1698    }
1699
1700    public static String ssidConvert(byte[] rawSsid) {
1701        String ssid;
1702
1703        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
1704        try {
1705            CharBuffer decoded = decoder.decode(ByteBuffer.wrap(rawSsid));
1706            ssid = decoded.toString();
1707        } catch (CharacterCodingException cce) {
1708            ssid = null;
1709        }
1710
1711        if (ssid == null) {
1712            ssid = new String(rawSsid, StandardCharsets.ISO_8859_1);
1713        }
1714
1715        return ssid;
1716    }
1717
1718    // Called from native
1719    public static boolean setSsid(byte[] rawSsid, ScanResult result) {
1720        if (rawSsid == null || rawSsid.length == 0 || result == null) {
1721            return false;
1722        }
1723
1724        result.SSID = ssidConvert(rawSsid);
1725        result.wifiSsid = createWifiSsid(rawSsid);
1726        return true;
1727    }
1728
1729    private static void populateScanResult(ScanResult result, byte bytes[], String dbg) {
1730        if (bytes == null) return;
1731        if (dbg == null) dbg = "";
1732
1733        InformationElementUtil.HtOperation htOperation = new InformationElementUtil.HtOperation();
1734        InformationElementUtil.VhtOperation vhtOperation =
1735                new InformationElementUtil.VhtOperation();
1736        InformationElementUtil.ExtendedCapabilities extendedCaps =
1737                new InformationElementUtil.ExtendedCapabilities();
1738
1739        ScanResult.InformationElement elements[] =
1740                InformationElementUtil.parseInformationElements(bytes);
1741        for (ScanResult.InformationElement ie : elements) {
1742            if(ie.id == ScanResult.InformationElement.EID_HT_OPERATION) {
1743                htOperation.from(ie);
1744            } else if(ie.id == ScanResult.InformationElement.EID_VHT_OPERATION) {
1745                vhtOperation.from(ie);
1746            } else if (ie.id == ScanResult.InformationElement.EID_EXTENDED_CAPS) {
1747                extendedCaps.from(ie);
1748            }
1749        }
1750
1751        if (extendedCaps.is80211McRTTResponder) {
1752            result.setFlag(ScanResult.FLAG_80211mc_RESPONDER);
1753        } else {
1754            result.clearFlag(ScanResult.FLAG_80211mc_RESPONDER);
1755        }
1756
1757        //handle RTT related information
1758        if (vhtOperation.isValid()) {
1759            result.channelWidth = vhtOperation.getChannelWidth();
1760            result.centerFreq0 = vhtOperation.getCenterFreq0();
1761            result.centerFreq1 = vhtOperation.getCenterFreq1();
1762        } else {
1763            result.channelWidth = htOperation.getChannelWidth();
1764            result.centerFreq0 = htOperation.getCenterFreq0(result.frequency);
1765            result.centerFreq1  = 0;
1766        }
1767        if(DBG) {
1768            Log.d(TAG, dbg + "SSID: " + result.SSID + " ChannelWidth is: " + result.channelWidth +
1769                    " PrimaryFreq: " + result.frequency +" mCenterfreq0: " + result.centerFreq0 +
1770                    " mCenterfreq1: " + result.centerFreq1 + (extendedCaps.is80211McRTTResponder ?
1771                    "Support RTT reponder: " : "Do not support RTT responder"));
1772        }
1773
1774        result.informationElements = elements;
1775    }
1776
1777    // Callback from native
1778    private static void onFullScanResult(int id, ScanResult result, byte bytes[]) {
1779        if (DBG) Log.i(TAG, "Got a full scan results event, ssid = " + result.SSID + ", " +
1780                "num = " + bytes.length);
1781
1782        ScanEventHandler handler = sScanEventHandler;
1783        if (handler != null) {
1784            populateScanResult(result, bytes, " onFullScanResult ");
1785            handler.onFullScanResult(result);
1786        }
1787    }
1788
1789    private static int sScanCmdId = 0;
1790    private static ScanEventHandler sScanEventHandler;
1791    private static ScanSettings sScanSettings;
1792
1793    public boolean startScan(ScanSettings settings, ScanEventHandler eventHandler) {
1794        synchronized (sLock) {
1795            if (isHalStarted()) {
1796                if (sScanCmdId != 0) {
1797                    stopScan();
1798                } else if (sScanSettings != null || sScanEventHandler != null) {
1799                /* current scan is paused; no need to stop it */
1800                }
1801
1802                sScanCmdId = getNewCmdIdLocked();
1803
1804                sScanSettings = settings;
1805                sScanEventHandler = eventHandler;
1806
1807                if (startScanNative(sWlan0Index, sScanCmdId, settings) == false) {
1808                    sScanEventHandler = null;
1809                    sScanSettings = null;
1810                    sScanCmdId = 0;
1811                    return false;
1812                }
1813
1814                return true;
1815            } else {
1816                return false;
1817            }
1818        }
1819    }
1820
1821    public void stopScan() {
1822        synchronized (sLock) {
1823            if (isHalStarted()) {
1824                if (sScanCmdId != 0) {
1825                    stopScanNative(sWlan0Index, sScanCmdId);
1826                }
1827                sScanSettings = null;
1828                sScanEventHandler = null;
1829                sScanCmdId = 0;
1830            }
1831        }
1832    }
1833
1834    public void pauseScan() {
1835        synchronized (sLock) {
1836            if (isHalStarted()) {
1837                if (sScanCmdId != 0 && sScanSettings != null && sScanEventHandler != null) {
1838                    Log.d(TAG, "Pausing scan");
1839                    WifiScanner.ScanData scanData[] = getScanResultsNative(sWlan0Index, true);
1840                    stopScanNative(sWlan0Index, sScanCmdId);
1841                    sScanCmdId = 0;
1842                    sScanEventHandler.onScanPaused(scanData);
1843                }
1844            }
1845        }
1846    }
1847
1848    public void restartScan() {
1849        synchronized (sLock) {
1850            if (isHalStarted()) {
1851                if (sScanCmdId == 0 && sScanSettings != null && sScanEventHandler != null) {
1852                    Log.d(TAG, "Restarting scan");
1853                    ScanEventHandler handler = sScanEventHandler;
1854                    ScanSettings settings = sScanSettings;
1855                    if (startScan(sScanSettings, sScanEventHandler)) {
1856                        sScanEventHandler.onScanRestarted();
1857                    } else {
1858                    /* we are still paused; don't change state */
1859                        sScanEventHandler = handler;
1860                        sScanSettings = settings;
1861                    }
1862                }
1863            }
1864        }
1865    }
1866
1867    public WifiScanner.ScanData[] getScanResults(boolean flush) {
1868        synchronized (sLock) {
1869            WifiScanner.ScanData[] sd = null;
1870            if (isHalStarted()) {
1871                sd = getScanResultsNative(sWlan0Index, flush);
1872            }
1873
1874            if (sd != null) {
1875                return sd;
1876            } else {
1877                return new WifiScanner.ScanData[0];
1878            }
1879        }
1880    }
1881
1882    public static interface HotlistEventHandler {
1883        void onHotlistApFound (ScanResult[] result);
1884        void onHotlistApLost  (ScanResult[] result);
1885    }
1886
1887    private static int sHotlistCmdId = 0;
1888    private static HotlistEventHandler sHotlistEventHandler;
1889
1890    private native static boolean setHotlistNative(int iface, int id,
1891            WifiScanner.HotlistSettings settings);
1892    private native static boolean resetHotlistNative(int iface, int id);
1893
1894    public boolean setHotlist(WifiScanner.HotlistSettings settings,
1895            HotlistEventHandler eventHandler) {
1896        synchronized (sLock) {
1897            if (isHalStarted()) {
1898                if (sHotlistCmdId != 0) {
1899                    return false;
1900                } else {
1901                    sHotlistCmdId = getNewCmdIdLocked();
1902                }
1903
1904                sHotlistEventHandler = eventHandler;
1905                if (setHotlistNative(sWlan0Index, sHotlistCmdId, settings) == false) {
1906                    sHotlistEventHandler = null;
1907                    return false;
1908                }
1909
1910                return true;
1911            } else {
1912                return false;
1913            }
1914        }
1915    }
1916
1917    public void resetHotlist() {
1918        synchronized (sLock) {
1919            if (isHalStarted()) {
1920                if (sHotlistCmdId != 0) {
1921                    resetHotlistNative(sWlan0Index, sHotlistCmdId);
1922                    sHotlistCmdId = 0;
1923                    sHotlistEventHandler = null;
1924                }
1925            }
1926        }
1927    }
1928
1929    // Callback from native
1930    private static void onHotlistApFound(int id, ScanResult[] results) {
1931        HotlistEventHandler handler = sHotlistEventHandler;
1932        if (handler != null) {
1933            handler.onHotlistApFound(results);
1934        } else {
1935            /* this can happen because of race conditions */
1936            Log.d(TAG, "Ignoring hotlist AP found event");
1937        }
1938    }
1939
1940    // Callback from native
1941    private static void onHotlistApLost(int id, ScanResult[] results) {
1942        HotlistEventHandler handler = sHotlistEventHandler;
1943        if (handler != null) {
1944            handler.onHotlistApLost(results);
1945        } else {
1946            /* this can happen because of race conditions */
1947            Log.d(TAG, "Ignoring hotlist AP lost event");
1948        }
1949    }
1950
1951    public static interface SignificantWifiChangeEventHandler {
1952        void onChangesFound(ScanResult[] result);
1953    }
1954
1955    private static SignificantWifiChangeEventHandler sSignificantWifiChangeHandler;
1956    private static int sSignificantWifiChangeCmdId;
1957
1958    private static native boolean trackSignificantWifiChangeNative(
1959            int iface, int id, WifiScanner.WifiChangeSettings settings);
1960    private static native boolean untrackSignificantWifiChangeNative(int iface, int id);
1961
1962    public boolean trackSignificantWifiChange(
1963            WifiScanner.WifiChangeSettings settings, SignificantWifiChangeEventHandler handler) {
1964        synchronized (sLock) {
1965            if (isHalStarted()) {
1966                if (sSignificantWifiChangeCmdId != 0) {
1967                    return false;
1968                } else {
1969                    sSignificantWifiChangeCmdId = getNewCmdIdLocked();
1970                }
1971
1972                sSignificantWifiChangeHandler = handler;
1973                if (trackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId,
1974                        settings) == false) {
1975                    sSignificantWifiChangeHandler = null;
1976                    return false;
1977                }
1978
1979                return true;
1980            } else {
1981                return false;
1982            }
1983
1984        }
1985    }
1986
1987    public void untrackSignificantWifiChange() {
1988        synchronized (sLock) {
1989            if (isHalStarted()) {
1990                if (sSignificantWifiChangeCmdId != 0) {
1991                    untrackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId);
1992                    sSignificantWifiChangeCmdId = 0;
1993                    sSignificantWifiChangeHandler = null;
1994                }
1995            }
1996        }
1997    }
1998
1999    // Callback from native
2000    private static void onSignificantWifiChange(int id, ScanResult[] results) {
2001        SignificantWifiChangeEventHandler handler = sSignificantWifiChangeHandler;
2002        if (handler != null) {
2003            handler.onChangesFound(results);
2004        } else {
2005            /* this can happen because of race conditions */
2006            Log.d(TAG, "Ignoring significant wifi change");
2007        }
2008    }
2009
2010    public WifiLinkLayerStats getWifiLinkLayerStats(String iface) {
2011        // TODO: use correct iface name to Index translation
2012        if (iface == null) return null;
2013        synchronized (sLock) {
2014            if (isHalStarted()) {
2015                return getWifiLinkLayerStatsNative(sWlan0Index);
2016            } else {
2017                return null;
2018            }
2019        }
2020    }
2021
2022    public void setWifiLinkLayerStats(String iface, int enable) {
2023        if (iface == null) return;
2024        synchronized (sLock) {
2025            if (isHalStarted()) {
2026                setWifiLinkLayerStatsNative(sWlan0Index, enable);
2027            }
2028        }
2029    }
2030
2031    public static native int getSupportedFeatureSetNative(int iface);
2032    public int getSupportedFeatureSet() {
2033        synchronized (sLock) {
2034            if (isHalStarted()) {
2035                return getSupportedFeatureSetNative(sWlan0Index);
2036            } else {
2037                Log.d(TAG, "Failing getSupportedFeatureset because HAL isn't started");
2038                return 0;
2039            }
2040        }
2041    }
2042
2043    /* Rtt related commands/events */
2044    public static interface RttEventHandler {
2045        void onRttResults(RttManager.RttResult[] result);
2046    }
2047
2048    private static RttEventHandler sRttEventHandler;
2049    private static int sRttCmdId;
2050
2051    // Callback from native
2052    private static void onRttResults(int id, RttManager.RttResult[] results) {
2053        RttEventHandler handler = sRttEventHandler;
2054        if (handler != null && id == sRttCmdId) {
2055            Log.d(TAG, "Received " + results.length + " rtt results");
2056            handler.onRttResults(results);
2057            sRttCmdId = 0;
2058        } else {
2059            Log.d(TAG, "RTT Received event for unknown cmd = " + id +
2060                    ", current id = " + sRttCmdId);
2061        }
2062    }
2063
2064    private static native boolean requestRangeNative(
2065            int iface, int id, RttManager.RttParams[] params);
2066    private static native boolean cancelRangeRequestNative(
2067            int iface, int id, RttManager.RttParams[] params);
2068
2069    public boolean requestRtt(
2070            RttManager.RttParams[] params, RttEventHandler handler) {
2071        synchronized (sLock) {
2072            if (isHalStarted()) {
2073                if (sRttCmdId != 0) {
2074                    Log.v("TAG", "Last one is still under measurement!");
2075                    return false;
2076                } else {
2077                    sRttCmdId = getNewCmdIdLocked();
2078                }
2079                sRttEventHandler = handler;
2080                Log.v(TAG, "native issue RTT request");
2081                return requestRangeNative(sWlan0Index, sRttCmdId, params);
2082            } else {
2083                return false;
2084            }
2085        }
2086    }
2087
2088    public boolean cancelRtt(RttManager.RttParams[] params) {
2089        synchronized (sLock) {
2090            if (isHalStarted()) {
2091                if (sRttCmdId == 0) {
2092                    return false;
2093                }
2094
2095                sRttCmdId = 0;
2096
2097                if (cancelRangeRequestNative(sWlan0Index, sRttCmdId, params)) {
2098                    sRttEventHandler = null;
2099                    Log.v(TAG, "RTT cancel Request Successfully");
2100                    return true;
2101                } else {
2102                    Log.e(TAG, "RTT cancel Request failed");
2103                    return false;
2104                }
2105            } else {
2106                return false;
2107            }
2108        }
2109    }
2110
2111    private static native boolean setScanningMacOuiNative(int iface, byte[] oui);
2112
2113    public boolean setScanningMacOui(byte[] oui) {
2114        synchronized (sLock) {
2115            if (isHalStarted()) {
2116                return setScanningMacOuiNative(sWlan0Index, oui);
2117            } else {
2118                return false;
2119            }
2120        }
2121    }
2122
2123    private static native int[] getChannelsForBandNative(
2124            int iface, int band);
2125
2126    public int [] getChannelsForBand(int band) {
2127        synchronized (sLock) {
2128            if (isHalStarted()) {
2129                return getChannelsForBandNative(sWlan0Index, band);
2130            } else {
2131                return null;
2132            }
2133        }
2134    }
2135
2136    private static native boolean isGetChannelsForBandSupportedNative();
2137    public boolean isGetChannelsForBandSupported(){
2138        synchronized (sLock) {
2139            if (isHalStarted()) {
2140                return isGetChannelsForBandSupportedNative();
2141            } else {
2142                return false;
2143            }
2144        }
2145    }
2146
2147    private static native boolean setDfsFlagNative(int iface, boolean dfsOn);
2148    public boolean setDfsFlag(boolean dfsOn) {
2149        synchronized (sLock) {
2150            if (isHalStarted()) {
2151                return setDfsFlagNative(sWlan0Index, dfsOn);
2152            } else {
2153                return false;
2154            }
2155        }
2156    }
2157
2158    private static native boolean toggleInterfaceNative(int on);
2159    public boolean toggleInterface(int on) {
2160        synchronized (sLock) {
2161            if (isHalStarted()) {
2162                return toggleInterfaceNative(on);
2163            } else {
2164                return false;
2165            }
2166        }
2167    }
2168
2169    private static native RttManager.RttCapabilities getRttCapabilitiesNative(int iface);
2170    public RttManager.RttCapabilities getRttCapabilities() {
2171        synchronized (sLock) {
2172            if (isHalStarted()) {
2173                return getRttCapabilitiesNative(sWlan0Index);
2174            } else {
2175                return null;
2176            }
2177        }
2178    }
2179
2180    private static native boolean setCountryCodeHalNative(int iface, String CountryCode);
2181    public boolean setCountryCodeHal(String CountryCode) {
2182        synchronized (sLock) {
2183            if (isHalStarted()) {
2184                return setCountryCodeHalNative(sWlan0Index, CountryCode);
2185            } else {
2186                return false;
2187            }
2188        }
2189    }
2190
2191    /* Rtt related commands/events */
2192    public abstract class TdlsEventHandler {
2193        abstract public void onTdlsStatus(String macAddr, int status, int reason);
2194    }
2195
2196    private static TdlsEventHandler sTdlsEventHandler;
2197
2198    private static native boolean enableDisableTdlsNative(int iface, boolean enable,
2199            String macAddr);
2200    public boolean enableDisableTdls(boolean enable, String macAdd, TdlsEventHandler tdlsCallBack) {
2201        synchronized (sLock) {
2202            sTdlsEventHandler = tdlsCallBack;
2203            return enableDisableTdlsNative(sWlan0Index, enable, macAdd);
2204        }
2205    }
2206
2207    // Once TDLS per mac and event feature is implemented, this class definition should be
2208    // moved to the right place, like WifiManager etc
2209    public static class TdlsStatus {
2210        int channel;
2211        int global_operating_class;
2212        int state;
2213        int reason;
2214    }
2215    private static native TdlsStatus getTdlsStatusNative(int iface, String macAddr);
2216    public TdlsStatus getTdlsStatus(String macAdd) {
2217        synchronized (sLock) {
2218            if (isHalStarted()) {
2219                return getTdlsStatusNative(sWlan0Index, macAdd);
2220            } else {
2221                return null;
2222            }
2223        }
2224    }
2225
2226    //ToFix: Once TDLS per mac and event feature is implemented, this class definition should be
2227    // moved to the right place, like WifiStateMachine etc
2228    public static class TdlsCapabilities {
2229        /* Maximum TDLS session number can be supported by the Firmware and hardware */
2230        int maxConcurrentTdlsSessionNumber;
2231        boolean isGlobalTdlsSupported;
2232        boolean isPerMacTdlsSupported;
2233        boolean isOffChannelTdlsSupported;
2234    }
2235
2236
2237
2238    private static native TdlsCapabilities getTdlsCapabilitiesNative(int iface);
2239    public TdlsCapabilities getTdlsCapabilities () {
2240        synchronized (sLock) {
2241            if (isHalStarted()) {
2242                return getTdlsCapabilitiesNative(sWlan0Index);
2243            } else {
2244                return null;
2245            }
2246        }
2247    }
2248
2249    private static boolean onTdlsStatus(String macAddr, int status, int reason) {
2250        TdlsEventHandler handler = sTdlsEventHandler;
2251        if (handler == null) {
2252            return false;
2253        } else {
2254            handler.onTdlsStatus(macAddr, status, reason);
2255            return true;
2256        }
2257    }
2258
2259    //---------------------------------------------------------------------------------
2260
2261    /* Wifi Logger commands/events */
2262
2263    public static interface WifiLoggerEventHandler {
2264        void onRingBufferData(RingBufferStatus status, byte[] buffer);
2265        void onWifiAlert(int errorCode, byte[] buffer);
2266    }
2267
2268    private static WifiLoggerEventHandler sWifiLoggerEventHandler = null;
2269
2270    // Callback from native
2271    private static void onRingBufferData(RingBufferStatus status, byte[] buffer) {
2272        WifiLoggerEventHandler handler = sWifiLoggerEventHandler;
2273        if (handler != null)
2274            handler.onRingBufferData(status, buffer);
2275    }
2276
2277    // Callback from native
2278    private static void onWifiAlert(byte[] buffer, int errorCode) {
2279        WifiLoggerEventHandler handler = sWifiLoggerEventHandler;
2280        if (handler != null)
2281            handler.onWifiAlert(errorCode, buffer);
2282    }
2283
2284    private static int sLogCmdId = -1;
2285    private static native boolean setLoggingEventHandlerNative(int iface, int id);
2286    public boolean setLoggingEventHandler(WifiLoggerEventHandler handler) {
2287        synchronized (sLock) {
2288            if (isHalStarted()) {
2289                int oldId =  sLogCmdId;
2290                sLogCmdId = getNewCmdIdLocked();
2291                if (!setLoggingEventHandlerNative(sWlan0Index, sLogCmdId)) {
2292                    sLogCmdId = oldId;
2293                    return false;
2294                }
2295                sWifiLoggerEventHandler = handler;
2296                return true;
2297            } else {
2298                return false;
2299            }
2300        }
2301    }
2302
2303    private static native boolean startLoggingRingBufferNative(int iface, int verboseLevel,
2304            int flags, int minIntervalSec ,int minDataSize, String ringName);
2305    public boolean startLoggingRingBuffer(int verboseLevel, int flags, int maxInterval,
2306            int minDataSize, String ringName){
2307        synchronized (sLock) {
2308            if (isHalStarted()) {
2309                return startLoggingRingBufferNative(sWlan0Index, verboseLevel, flags, maxInterval,
2310                        minDataSize, ringName);
2311            } else {
2312                return false;
2313            }
2314        }
2315    }
2316
2317    private static native int getSupportedLoggerFeatureSetNative(int iface);
2318    public int getSupportedLoggerFeatureSet() {
2319        synchronized (sLock) {
2320            if (isHalStarted()) {
2321                return getSupportedLoggerFeatureSetNative(sWlan0Index);
2322            } else {
2323                return 0;
2324            }
2325        }
2326    }
2327
2328    private static native boolean resetLogHandlerNative(int iface, int id);
2329    public boolean resetLogHandler() {
2330        synchronized (sLock) {
2331            if (isHalStarted()) {
2332                if (sLogCmdId == -1) {
2333                    Log.e(TAG,"Can not reset handler Before set any handler");
2334                    return false;
2335                }
2336                sWifiLoggerEventHandler = null;
2337                if (resetLogHandlerNative(sWlan0Index, sLogCmdId)) {
2338                    sLogCmdId = -1;
2339                    return true;
2340                } else {
2341                    return false;
2342                }
2343            } else {
2344                return false;
2345            }
2346        }
2347    }
2348
2349    private static native String getDriverVersionNative(int iface);
2350    public String getDriverVersion() {
2351        synchronized (sLock) {
2352            if (isHalStarted()) {
2353                return getDriverVersionNative(sWlan0Index);
2354            } else {
2355                return "";
2356            }
2357        }
2358    }
2359
2360
2361    private static native String getFirmwareVersionNative(int iface);
2362    public String getFirmwareVersion() {
2363        synchronized (sLock) {
2364            if (isHalStarted()) {
2365                return getFirmwareVersionNative(sWlan0Index);
2366            } else {
2367                return "";
2368            }
2369        }
2370    }
2371
2372    public static class RingBufferStatus{
2373        String name;
2374        int flag;
2375        int ringBufferId;
2376        int ringBufferByteSize;
2377        int verboseLevel;
2378        int writtenBytes;
2379        int readBytes;
2380        int writtenRecords;
2381
2382        @Override
2383        public String toString() {
2384            return "name: " + name + " flag: " + flag + " ringBufferId: " + ringBufferId +
2385                    " ringBufferByteSize: " +ringBufferByteSize + " verboseLevel: " +verboseLevel +
2386                    " writtenBytes: " + writtenBytes + " readBytes: " + readBytes +
2387                    " writtenRecords: " + writtenRecords;
2388        }
2389    }
2390
2391    private static native RingBufferStatus[] getRingBufferStatusNative(int iface);
2392    public RingBufferStatus[] getRingBufferStatus() {
2393        synchronized (sLock) {
2394            if (isHalStarted()) {
2395                return getRingBufferStatusNative(sWlan0Index);
2396            } else {
2397                return null;
2398            }
2399        }
2400    }
2401
2402    private static native boolean getRingBufferDataNative(int iface, String ringName);
2403    public boolean getRingBufferData(String ringName) {
2404        synchronized (sLock) {
2405            if (isHalStarted()) {
2406                return getRingBufferDataNative(sWlan0Index, ringName);
2407            } else {
2408                return false;
2409            }
2410        }
2411    }
2412
2413    private static byte[] mFwMemoryDump;
2414    // Callback from native
2415    private static void onWifiFwMemoryAvailable(byte[] buffer) {
2416        mFwMemoryDump = buffer;
2417        if (DBG) {
2418            Log.d(TAG, "onWifiFwMemoryAvailable is called and buffer length is: " +
2419                    (buffer == null ? 0 :  buffer.length));
2420        }
2421    }
2422
2423    private static native boolean getFwMemoryDumpNative(int iface);
2424    public byte[] getFwMemoryDump() {
2425        synchronized (sLock) {
2426            if (isHalStarted()) {
2427                if(getFwMemoryDumpNative(sWlan0Index)) {
2428                    byte[] fwMemoryDump = mFwMemoryDump;
2429                    mFwMemoryDump = null;
2430                    return fwMemoryDump;
2431                } else {
2432                    return null;
2433                }
2434            }
2435            return null;
2436        }
2437    }
2438
2439    //---------------------------------------------------------------------------------
2440    /* Configure ePNO */
2441
2442    /* pno flags, keep these values in sync with gscan.h */
2443    private static int WIFI_PNO_AUTH_CODE_OPEN  = 1; // open
2444    private static int WIFI_PNO_AUTH_CODE_PSK   = 2; // WPA_PSK or WPA2PSK
2445    private static int WIFI_PNO_AUTH_CODE_EAPOL = 4; // any EAPOL
2446
2447    // Whether directed scan needs to be performed (for hidden SSIDs)
2448    private static int WIFI_PNO_FLAG_DIRECTED_SCAN = 1;
2449    // Whether PNO event shall be triggered if the network is found on A band
2450    private static int WIFI_PNO_FLAG_A_BAND = 2;
2451    // Whether PNO event shall be triggered if the network is found on G band
2452    private static int WIFI_PNO_FLAG_G_BAND = 4;
2453    // Whether strict matching is required (i.e. firmware shall not match on the entire SSID)
2454    private static int WIFI_PNO_FLAG_STRICT_MATCH = 8;
2455
2456    public static class WifiPnoNetwork {
2457        String SSID;
2458        int rssi_threshold;
2459        int flags;
2460        int auth;
2461        String configKey; // kept for reference
2462
2463        WifiPnoNetwork(WifiConfiguration config, int threshold) {
2464            if (config.SSID == null) {
2465                this.SSID = "";
2466                this.flags = WIFI_PNO_FLAG_DIRECTED_SCAN;
2467            } else {
2468                this.SSID = config.SSID;
2469            }
2470            this.rssi_threshold = threshold;
2471            if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
2472                auth |= WIFI_PNO_AUTH_CODE_PSK;
2473            } else if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) ||
2474                    config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
2475                auth |= WIFI_PNO_AUTH_CODE_EAPOL;
2476            } else if (config.wepKeys[0] != null) {
2477                auth |= WIFI_PNO_AUTH_CODE_OPEN;
2478            } else {
2479                auth |= WIFI_PNO_AUTH_CODE_OPEN;
2480            }
2481
2482            flags |= WIFI_PNO_FLAG_A_BAND | WIFI_PNO_FLAG_G_BAND;
2483            configKey = config.configKey();
2484        }
2485
2486        @Override
2487        public String toString() {
2488            StringBuilder sbuf = new StringBuilder();
2489            sbuf.append(this.SSID);
2490            sbuf.append(" flags=").append(this.flags);
2491            sbuf.append(" rssi=").append(this.rssi_threshold);
2492            sbuf.append(" auth=").append(this.auth);
2493            return sbuf.toString();
2494        }
2495    }
2496
2497    public static interface WifiPnoEventHandler {
2498        void onPnoNetworkFound(ScanResult results[]);
2499    }
2500
2501    private static WifiPnoEventHandler sWifiPnoEventHandler;
2502
2503    private static int sPnoCmdId = 0;
2504
2505    private native static boolean setPnoListNative(int iface, int id, WifiPnoNetwork list[]);
2506
2507    public boolean setPnoList(WifiPnoNetwork list[],
2508                                                  WifiPnoEventHandler eventHandler) {
2509        Log.e(TAG, "setPnoList cmd " + sPnoCmdId);
2510
2511        synchronized (sLock) {
2512            if (isHalStarted()) {
2513
2514                sPnoCmdId = getNewCmdIdLocked();
2515
2516                sWifiPnoEventHandler = eventHandler;
2517                if (setPnoListNative(sWlan0Index, sPnoCmdId, list)) {
2518                    return true;
2519                }
2520            }
2521
2522            sWifiPnoEventHandler = null;
2523            return false;
2524        }
2525    }
2526
2527    // Callback from native
2528    private static void onPnoNetworkFound(int id, ScanResult[] results) {
2529        if (results == null) {
2530            Log.e(TAG, "onPnoNetworkFound null results");
2531            return;
2532
2533        }
2534        Log.d(TAG, "WifiNative.onPnoNetworkFound result " + results.length);
2535
2536        WifiPnoEventHandler handler = sWifiPnoEventHandler;
2537        if (sPnoCmdId != 0 && handler != null) {
2538            for (int i=0; i<results.length; i++) {
2539                Log.e(TAG, "onPnoNetworkFound SSID " + results[i].SSID
2540                        + " " + results[i].level + " " + results[i].frequency);
2541
2542                populateScanResult(results[i], results[i].bytes, "onPnoNetworkFound ");
2543                results[i].wifiSsid = WifiSsid.createFromAsciiEncoded(results[i].SSID);
2544            }
2545
2546            handler.onPnoNetworkFound(results);
2547        } else {
2548            /* this can happen because of race conditions */
2549            Log.d(TAG, "Ignoring Pno Network found event");
2550        }
2551    }
2552
2553    public static class WifiLazyRoamParams {
2554        int A_band_boost_threshold;
2555        int A_band_penalty_threshold;
2556        int A_band_boost_factor;
2557        int A_band_penalty_factor;
2558        int A_band_max_boost;
2559        int lazy_roam_hysteresis;
2560        int alert_roam_rssi_trigger;
2561
2562        WifiLazyRoamParams() {
2563        }
2564
2565        @Override
2566        public String toString() {
2567            StringBuilder sbuf = new StringBuilder();
2568            sbuf.append(" A_band_boost_threshold=").append(this.A_band_boost_threshold);
2569            sbuf.append(" A_band_penalty_threshold=").append(this.A_band_penalty_threshold);
2570            sbuf.append(" A_band_boost_factor=").append(this.A_band_boost_factor);
2571            sbuf.append(" A_band_penalty_factor=").append(this.A_band_penalty_factor);
2572            sbuf.append(" A_band_max_boost=").append(this.A_band_max_boost);
2573            sbuf.append(" lazy_roam_hysteresis=").append(this.lazy_roam_hysteresis);
2574            sbuf.append(" alert_roam_rssi_trigger=").append(this.alert_roam_rssi_trigger);
2575            return sbuf.toString();
2576        }
2577    }
2578
2579    private native static boolean setLazyRoamNative(int iface, int id,
2580                                              boolean enabled, WifiLazyRoamParams param);
2581
2582    public boolean setLazyRoam(boolean enabled, WifiLazyRoamParams params) {
2583        synchronized (sLock) {
2584            if (isHalStarted()) {
2585                sPnoCmdId = getNewCmdIdLocked();
2586                return setLazyRoamNative(sWlan0Index, sPnoCmdId, enabled, params);
2587            } else {
2588                return false;
2589            }
2590        }
2591    }
2592
2593    private native static boolean setBssidBlacklistNative(int iface, int id,
2594                                              String list[]);
2595
2596    public boolean setBssidBlacklist(String list[]) {
2597        int size = 0;
2598        if (list != null) {
2599            size = list.length;
2600        }
2601        Log.e(TAG, "setBssidBlacklist cmd " + sPnoCmdId + " size " + size);
2602
2603        synchronized (sLock) {
2604            if (isHalStarted()) {
2605                sPnoCmdId = getNewCmdIdLocked();
2606                return setBssidBlacklistNative(sWlan0Index, sPnoCmdId, list);
2607            } else {
2608                return false;
2609            }
2610        }
2611    }
2612
2613    private native static boolean setSsidWhitelistNative(int iface, int id, String list[]);
2614
2615    public boolean setSsidWhitelist(String list[]) {
2616        int size = 0;
2617        if (list != null) {
2618            size = list.length;
2619        }
2620        Log.e(TAG, "setSsidWhitelist cmd " + sPnoCmdId + " size " + size);
2621
2622        synchronized (sLock) {
2623            if (isHalStarted()) {
2624                sPnoCmdId = getNewCmdIdLocked();
2625
2626                return setSsidWhitelistNative(sWlan0Index, sPnoCmdId, list);
2627            } else {
2628                return false;
2629            }
2630        }
2631    }
2632
2633    private native static int startSendingOffloadedPacketNative(int iface, int idx,
2634                                    byte[] srcMac, byte[] dstMac, byte[] pktData, int period);
2635
2636    public int
2637    startSendingOffloadedPacket(int slot, KeepalivePacketData keepAlivePacket, int period) {
2638        Log.d(TAG, "startSendingOffloadedPacket slot=" + slot + " period=" + period);
2639
2640        String[] macAddrStr = getMacAddress().split(":");
2641        byte[] srcMac = new byte[6];
2642        for(int i = 0; i < 6; i++) {
2643            Integer hexVal = Integer.parseInt(macAddrStr[i], 16);
2644            srcMac[i] = hexVal.byteValue();
2645        }
2646        synchronized (sLock) {
2647            if (isHalStarted()) {
2648                return startSendingOffloadedPacketNative(sWlan0Index, slot, srcMac,
2649                        keepAlivePacket.dstMac, keepAlivePacket.data, period);
2650            } else {
2651                return -1;
2652            }
2653        }
2654    }
2655
2656    private native static int stopSendingOffloadedPacketNative(int iface, int idx);
2657
2658    public int
2659    stopSendingOffloadedPacket(int slot) {
2660        Log.d(TAG, "stopSendingOffloadedPacket " + slot);
2661        synchronized (sLock) {
2662            if (isHalStarted()) {
2663                return stopSendingOffloadedPacketNative(sWlan0Index, slot);
2664            } else {
2665                return -1;
2666            }
2667        }
2668    }
2669
2670    public static interface WifiRssiEventHandler {
2671        void onRssiThresholdBreached(byte curRssi);
2672    }
2673
2674    private static WifiRssiEventHandler sWifiRssiEventHandler;
2675
2676    // Callback from native
2677    private static void onRssiThresholdBreached(int id, byte curRssi) {
2678        WifiRssiEventHandler handler = sWifiRssiEventHandler;
2679        if (handler != null) {
2680            handler.onRssiThresholdBreached(curRssi);
2681        }
2682    }
2683
2684    private native static int startRssiMonitoringNative(int iface, int id,
2685                                        byte maxRssi, byte minRssi);
2686
2687    private static int sRssiMonitorCmdId = 0;
2688
2689    public int startRssiMonitoring(byte maxRssi, byte minRssi,
2690                                                WifiRssiEventHandler rssiEventHandler) {
2691        Log.d(TAG, "startRssiMonitoring: maxRssi=" + maxRssi + " minRssi=" + minRssi);
2692        synchronized (sLock) {
2693            sWifiRssiEventHandler = rssiEventHandler;
2694            if (isHalStarted()) {
2695                if (sRssiMonitorCmdId != 0) {
2696                    stopRssiMonitoring();
2697                }
2698
2699                sRssiMonitorCmdId = getNewCmdIdLocked();
2700                Log.d(TAG, "sRssiMonitorCmdId = " + sRssiMonitorCmdId);
2701                int ret = startRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId,
2702                        maxRssi, minRssi);
2703                if (ret != 0) { // if not success
2704                    sRssiMonitorCmdId = 0;
2705                }
2706                return ret;
2707            } else {
2708                return -1;
2709            }
2710        }
2711    }
2712
2713    private native static int stopRssiMonitoringNative(int iface, int idx);
2714
2715    public int stopRssiMonitoring() {
2716        Log.d(TAG, "stopRssiMonitoring, cmdId " + sRssiMonitorCmdId);
2717        synchronized (sLock) {
2718            if (isHalStarted()) {
2719                int ret = 0;
2720                if (sRssiMonitorCmdId != 0) {
2721                    ret = stopRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId);
2722                }
2723                sRssiMonitorCmdId = 0;
2724                return ret;
2725            } else {
2726                return -1;
2727            }
2728        }
2729    }
2730
2731    private static native WifiWakeReasonAndCounts getWlanWakeReasonCountNative(int iface);
2732}
2733