WifiNative.java revision 297c3acabe7a85eb87240fe3ccf772e57ce6aef7
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.WifiManager;
25import android.net.wifi.WifiScanner;
26import android.net.wifi.WifiSsid;
27import android.net.wifi.WpsInfo;
28import android.net.wifi.p2p.WifiP2pConfig;
29import android.net.wifi.p2p.WifiP2pGroup;
30import android.net.wifi.p2p.nsd.WifiP2pServiceInfo;
31import android.os.SystemClock;
32import android.os.SystemProperties;
33import android.text.TextUtils;
34import android.util.LocalLog;
35import android.util.Log;
36import android.content.Context;
37import android.content.Intent;
38import android.app.AlarmManager;
39import android.app.PendingIntent;
40import android.content.IntentFilter;
41import android.content.BroadcastReceiver;
42import com.android.server.connectivity.KeepalivePacketData;
43import com.android.server.wifi.hotspot2.NetworkDetail;
44import com.android.server.wifi.hotspot2.SupplicantBridge;
45import com.android.server.wifi.hotspot2.Utils;
46import com.android.server.wifi.util.InformationElementUtil;
47
48import libcore.util.HexEncoding;
49
50import java.nio.ByteBuffer;
51import java.nio.CharBuffer;
52import java.nio.charset.CharacterCodingException;
53import java.nio.charset.CharsetDecoder;
54import java.nio.charset.StandardCharsets;
55import java.util.ArrayList;
56import java.util.List;
57import java.util.Locale;
58import java.util.Set;
59
60/**
61 * Native calls for bring up/shut down of the supplicant daemon and for
62 * sending requests to the supplicant daemon
63 *
64 * waitForEvent() is called on the monitor thread for events. All other methods
65 * must be serialized from the framework.
66 *
67 * {@hide}
68 */
69public class WifiNative {
70    private static boolean DBG = false;
71
72    /**
73     * Hold this lock before calling supplicant or HAL methods
74     * it is required to mutually exclude access to the driver
75     */
76    private static final Object mLock = new Object();
77
78    private static final LocalLog mLocalLog = new LocalLog(16384);
79
80    public static LocalLog getLocalLog() {
81        return mLocalLog;
82    }
83
84    /* Register native functions */
85    static {
86        /* Native functions are defined in libwifi-service.so */
87        System.loadLibrary("wifi-service");
88        registerNatives();
89    }
90
91    private static native int registerNatives();
92
93    /*
94     * Singleton WifiNative instances
95     */
96    private static WifiNative wlanNativeInterface =
97            new WifiNative(SystemProperties.get("wifi.interface", "wlan0"));
98    public static WifiNative getWlanNativeInterface() {
99        return wlanNativeInterface;
100    }
101
102    //STOPSHIP: get interface name from native side
103    private static WifiNative p2pNativeInterface = new WifiNative("p2p0");
104    public static WifiNative getP2pNativeInterface() {
105        return p2pNativeInterface;
106    }
107
108
109    private final String mTAG;
110    private final String mInterfaceName;
111    private final String mInterfacePrefix;
112
113    private Context mContext = null;
114    private PnoMonitor mPnoMonitor = null;
115    public void initContext(Context context) {
116        if (mContext == null && context != null) {
117            mContext = context;
118            mPnoMonitor = new PnoMonitor();
119        }
120    }
121
122    private WifiNative(String interfaceName) {
123        mInterfaceName = interfaceName;
124        mTAG = "WifiNative-" + interfaceName;
125
126        if (!interfaceName.equals("p2p0")) {
127            mInterfacePrefix = "IFNAME=" + interfaceName + " ";
128        } else {
129            // commands for p2p0 interface don't need prefix
130            mInterfacePrefix = "";
131        }
132    }
133
134    public String getInterfaceName() {
135        return mInterfaceName;
136    }
137
138    // Note this affects logging on for all interfaces
139    void enableVerboseLogging(int verbose) {
140        if (verbose > 0) {
141            DBG = true;
142        } else {
143            DBG = false;
144        }
145    }
146
147    private void localLog(String s) {
148        if (mLocalLog != null)
149            mLocalLog.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 (mLock) {
160            return loadDriverNative();
161        }
162    }
163
164    private native static boolean isDriverLoadedNative();
165    public boolean isDriverLoaded() {
166        synchronized (mLock) {
167            return isDriverLoadedNative();
168        }
169    }
170
171    private native static boolean unloadDriverNative();
172    public boolean unloadDriver() {
173        synchronized (mLock) {
174            return unloadDriverNative();
175        }
176    }
177
178    private native static boolean startSupplicantNative(boolean p2pSupported);
179    public boolean startSupplicant(boolean p2pSupported) {
180        synchronized (mLock) {
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 (mLock) {
190            return killSupplicantNative(p2pSupported);
191        }
192    }
193
194    private native static boolean connectToSupplicantNative();
195    public boolean connectToSupplicant() {
196        synchronized (mLock) {
197            localLog(mInterfacePrefix + "connectToSupplicant");
198            return connectToSupplicantNative();
199        }
200    }
201
202    private native static void closeSupplicantConnectionNative();
203    public void closeSupplicantConnection() {
204        synchronized (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 (mLock) {
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 simIdentityResponse(int id, String response) {
1027        return doBooleanCommand("CTRL-RSP-IDENTITY-" + id + ":" + response);
1028    }
1029
1030    /* Configures an access point connection */
1031    public boolean startWpsRegistrar(String bssid, String pin) {
1032        if (TextUtils.isEmpty(bssid) || TextUtils.isEmpty(pin)) return false;
1033        return doBooleanCommand("WPS_REG " + bssid + " " + pin);
1034    }
1035
1036    public boolean cancelWps() {
1037        return doBooleanCommand("WPS_CANCEL");
1038    }
1039
1040    public boolean setPersistentReconnect(boolean enabled) {
1041        int value = (enabled == true) ? 1 : 0;
1042        return doBooleanCommand("SET persistent_reconnect " + value);
1043    }
1044
1045    public boolean setDeviceName(String name) {
1046        return doBooleanCommand("SET device_name " + name);
1047    }
1048
1049    public boolean setDeviceType(String type) {
1050        return doBooleanCommand("SET device_type " + type);
1051    }
1052
1053    public boolean setConfigMethods(String cfg) {
1054        return doBooleanCommand("SET config_methods " + cfg);
1055    }
1056
1057    public boolean setManufacturer(String value) {
1058        return doBooleanCommand("SET manufacturer " + value);
1059    }
1060
1061    public boolean setModelName(String value) {
1062        return doBooleanCommand("SET model_name " + value);
1063    }
1064
1065    public boolean setModelNumber(String value) {
1066        return doBooleanCommand("SET model_number " + value);
1067    }
1068
1069    public boolean setSerialNumber(String value) {
1070        return doBooleanCommand("SET serial_number " + value);
1071    }
1072
1073    public boolean setP2pSsidPostfix(String postfix) {
1074        return doBooleanCommand("SET p2p_ssid_postfix " + postfix);
1075    }
1076
1077    public boolean setP2pGroupIdle(String iface, int time) {
1078        synchronized (mLock) {
1079            return doBooleanCommandNative("IFNAME=" + iface + " SET p2p_group_idle " + time);
1080        }
1081    }
1082
1083    public void setPowerSave(boolean enabled) {
1084        if (enabled) {
1085            doBooleanCommand("SET ps 1");
1086        } else {
1087            doBooleanCommand("SET ps 0");
1088        }
1089    }
1090
1091    public boolean setP2pPowerSave(String iface, boolean enabled) {
1092        synchronized (mLock) {
1093            if (enabled) {
1094                return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 1");
1095            } else {
1096                return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 0");
1097            }
1098        }
1099    }
1100
1101    public boolean setWfdEnable(boolean enable) {
1102        return doBooleanCommand("SET wifi_display " + (enable ? "1" : "0"));
1103    }
1104
1105    public boolean setWfdDeviceInfo(String hex) {
1106        return doBooleanCommand("WFD_SUBELEM_SET 0 " + hex);
1107    }
1108
1109    /**
1110     * "sta" prioritizes STA connection over P2P and "p2p" prioritizes
1111     * P2P connection over STA
1112     */
1113    public boolean setConcurrencyPriority(String s) {
1114        return doBooleanCommand("P2P_SET conc_pref " + s);
1115    }
1116
1117    public boolean p2pFind() {
1118        return doBooleanCommand("P2P_FIND");
1119    }
1120
1121    public boolean p2pFind(int timeout) {
1122        if (timeout <= 0) {
1123            return p2pFind();
1124        }
1125        return doBooleanCommand("P2P_FIND " + timeout);
1126    }
1127
1128    public boolean p2pStopFind() {
1129       return doBooleanCommand("P2P_STOP_FIND");
1130    }
1131
1132    public boolean p2pListen() {
1133        return doBooleanCommand("P2P_LISTEN");
1134    }
1135
1136    public boolean p2pListen(int timeout) {
1137        if (timeout <= 0) {
1138            return p2pListen();
1139        }
1140        return doBooleanCommand("P2P_LISTEN " + timeout);
1141    }
1142
1143    public boolean p2pExtListen(boolean enable, int period, int interval) {
1144        if (enable && interval < period) {
1145            return false;
1146        }
1147        return doBooleanCommand("P2P_EXT_LISTEN"
1148                    + (enable ? (" " + period + " " + interval) : ""));
1149    }
1150
1151    public boolean p2pSetChannel(int lc, int oc) {
1152        if (DBG) Log.d(mTAG, "p2pSetChannel: lc="+lc+", oc="+oc);
1153
1154        synchronized (mLock) {
1155            if (lc >=1 && lc <= 11) {
1156                if (!doBooleanCommand("P2P_SET listen_channel " + lc)) {
1157                    return false;
1158                }
1159            } else if (lc != 0) {
1160                return false;
1161            }
1162
1163            if (oc >= 1 && oc <= 165 ) {
1164                int freq = (oc <= 14 ? 2407 : 5000) + oc * 5;
1165                return doBooleanCommand("P2P_SET disallow_freq 1000-"
1166                        + (freq - 5) + "," + (freq + 5) + "-6000");
1167            } else if (oc == 0) {
1168                /* oc==0 disables "P2P_SET disallow_freq" (enables all freqs) */
1169                return doBooleanCommand("P2P_SET disallow_freq \"\"");
1170            }
1171        }
1172        return false;
1173    }
1174
1175    public boolean p2pFlush() {
1176        return doBooleanCommand("P2P_FLUSH");
1177    }
1178
1179    private static final int DEFAULT_GROUP_OWNER_INTENT     = 6;
1180    /* p2p_connect <peer device address> <pbc|pin|PIN#> [label|display|keypad]
1181        [persistent] [join|auth] [go_intent=<0..15>] [freq=<in MHz>] */
1182    public String p2pConnect(WifiP2pConfig config, boolean joinExistingGroup) {
1183        if (config == null) return null;
1184        List<String> args = new ArrayList<String>();
1185        WpsInfo wps = config.wps;
1186        args.add(config.deviceAddress);
1187
1188        switch (wps.setup) {
1189            case WpsInfo.PBC:
1190                args.add("pbc");
1191                break;
1192            case WpsInfo.DISPLAY:
1193                if (TextUtils.isEmpty(wps.pin)) {
1194                    args.add("pin");
1195                } else {
1196                    args.add(wps.pin);
1197                }
1198                args.add("display");
1199                break;
1200            case WpsInfo.KEYPAD:
1201                args.add(wps.pin);
1202                args.add("keypad");
1203                break;
1204            case WpsInfo.LABEL:
1205                args.add(wps.pin);
1206                args.add("label");
1207            default:
1208                break;
1209        }
1210
1211        if (config.netId == WifiP2pGroup.PERSISTENT_NET_ID) {
1212            args.add("persistent");
1213        }
1214
1215        if (joinExistingGroup) {
1216            args.add("join");
1217        } else {
1218            //TODO: This can be adapted based on device plugged in state and
1219            //device battery state
1220            int groupOwnerIntent = config.groupOwnerIntent;
1221            if (groupOwnerIntent < 0 || groupOwnerIntent > 15) {
1222                groupOwnerIntent = DEFAULT_GROUP_OWNER_INTENT;
1223            }
1224            args.add("go_intent=" + groupOwnerIntent);
1225        }
1226
1227        String command = "P2P_CONNECT ";
1228        for (String s : args) command += s + " ";
1229
1230        return doStringCommand(command);
1231    }
1232
1233    public boolean p2pCancelConnect() {
1234        return doBooleanCommand("P2P_CANCEL");
1235    }
1236
1237    public boolean p2pProvisionDiscovery(WifiP2pConfig config) {
1238        if (config == null) return false;
1239
1240        switch (config.wps.setup) {
1241            case WpsInfo.PBC:
1242                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " pbc");
1243            case WpsInfo.DISPLAY:
1244                //We are doing display, so provision discovery is keypad
1245                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " keypad");
1246            case WpsInfo.KEYPAD:
1247                //We are doing keypad, so provision discovery is display
1248                return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " display");
1249            default:
1250                break;
1251        }
1252        return false;
1253    }
1254
1255    public boolean p2pGroupAdd(boolean persistent) {
1256        if (persistent) {
1257            return doBooleanCommand("P2P_GROUP_ADD persistent");
1258        }
1259        return doBooleanCommand("P2P_GROUP_ADD");
1260    }
1261
1262    public boolean p2pGroupAdd(int netId) {
1263        return doBooleanCommand("P2P_GROUP_ADD persistent=" + netId);
1264    }
1265
1266    public boolean p2pGroupRemove(String iface) {
1267        if (TextUtils.isEmpty(iface)) return false;
1268        synchronized (mLock) {
1269            return doBooleanCommandNative("IFNAME=" + iface + " P2P_GROUP_REMOVE " + iface);
1270        }
1271    }
1272
1273    public boolean p2pReject(String deviceAddress) {
1274        return doBooleanCommand("P2P_REJECT " + deviceAddress);
1275    }
1276
1277    /* Invite a peer to a group */
1278    public boolean p2pInvite(WifiP2pGroup group, String deviceAddress) {
1279        if (TextUtils.isEmpty(deviceAddress)) return false;
1280
1281        if (group == null) {
1282            return doBooleanCommand("P2P_INVITE peer=" + deviceAddress);
1283        } else {
1284            return doBooleanCommand("P2P_INVITE group=" + group.getInterface()
1285                    + " peer=" + deviceAddress + " go_dev_addr=" + group.getOwner().deviceAddress);
1286        }
1287    }
1288
1289    /* Reinvoke a persistent connection */
1290    public boolean p2pReinvoke(int netId, String deviceAddress) {
1291        if (TextUtils.isEmpty(deviceAddress) || netId < 0) return false;
1292
1293        return doBooleanCommand("P2P_INVITE persistent=" + netId + " peer=" + deviceAddress);
1294    }
1295
1296    public String p2pGetSsid(String deviceAddress) {
1297        return p2pGetParam(deviceAddress, "oper_ssid");
1298    }
1299
1300    public String p2pGetDeviceAddress() {
1301        Log.d(TAG, "p2pGetDeviceAddress");
1302
1303        String status = null;
1304
1305        /* Explicitly calling the API without IFNAME= prefix to take care of the devices that
1306        don't have p2p0 interface. Supplicant seems to be returning the correct address anyway. */
1307
1308        synchronized (mLock) {
1309            status = doStringCommandNative("STATUS");
1310        }
1311
1312        String result = "";
1313        if (status != null) {
1314            String[] tokens = status.split("\n");
1315            for (String token : tokens) {
1316                if (token.startsWith("p2p_device_address=")) {
1317                    String[] nameValue = token.split("=");
1318                    if (nameValue.length != 2)
1319                        break;
1320                    result = nameValue[1];
1321                }
1322            }
1323        }
1324
1325        Log.d(TAG, "p2pGetDeviceAddress returning " + result);
1326        return result;
1327    }
1328
1329    public int getGroupCapability(String deviceAddress) {
1330        int gc = 0;
1331        if (TextUtils.isEmpty(deviceAddress)) return gc;
1332        String peerInfo = p2pPeer(deviceAddress);
1333        if (TextUtils.isEmpty(peerInfo)) return gc;
1334
1335        String[] tokens = peerInfo.split("\n");
1336        for (String token : tokens) {
1337            if (token.startsWith("group_capab=")) {
1338                String[] nameValue = token.split("=");
1339                if (nameValue.length != 2) break;
1340                try {
1341                    return Integer.decode(nameValue[1]);
1342                } catch(NumberFormatException e) {
1343                    return gc;
1344                }
1345            }
1346        }
1347        return gc;
1348    }
1349
1350    public String p2pPeer(String deviceAddress) {
1351        return doStringCommand("P2P_PEER " + deviceAddress);
1352    }
1353
1354    private String p2pGetParam(String deviceAddress, String key) {
1355        if (deviceAddress == null) return null;
1356
1357        String peerInfo = p2pPeer(deviceAddress);
1358        if (peerInfo == null) return null;
1359        String[] tokens= peerInfo.split("\n");
1360
1361        key += "=";
1362        for (String token : tokens) {
1363            if (token.startsWith(key)) {
1364                String[] nameValue = token.split("=");
1365                if (nameValue.length != 2) break;
1366                return nameValue[1];
1367            }
1368        }
1369        return null;
1370    }
1371
1372    public boolean p2pServiceAdd(WifiP2pServiceInfo servInfo) {
1373        /*
1374         * P2P_SERVICE_ADD bonjour <query hexdump> <RDATA hexdump>
1375         * P2P_SERVICE_ADD upnp <version hex> <service>
1376         *
1377         * e.g)
1378         * [Bonjour]
1379         * # IP Printing over TCP (PTR) (RDATA=MyPrinter._ipp._tcp.local.)
1380         * P2P_SERVICE_ADD bonjour 045f697070c00c000c01 094d795072696e746572c027
1381         * # IP Printing over TCP (TXT) (RDATA=txtvers=1,pdl=application/postscript)
1382         * P2P_SERVICE_ADD bonjour 096d797072696e746572045f697070c00c001001
1383         *  09747874766572733d311a70646c3d6170706c69636174696f6e2f706f7374736372797074
1384         *
1385         * [UPnP]
1386         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012
1387         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice
1388         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp
1389         * -org:device:InternetGatewayDevice:1
1390         * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9322-123456789012::urn:schemas-upnp
1391         * -org:service:ContentDirectory:2
1392         */
1393        synchronized (mLock) {
1394            for (String s : servInfo.getSupplicantQueryList()) {
1395                String command = "P2P_SERVICE_ADD";
1396                command += (" " + s);
1397                if (!doBooleanCommand(command)) {
1398                    return false;
1399                }
1400            }
1401        }
1402        return true;
1403    }
1404
1405    public boolean p2pServiceDel(WifiP2pServiceInfo servInfo) {
1406        /*
1407         * P2P_SERVICE_DEL bonjour <query hexdump>
1408         * P2P_SERVICE_DEL upnp <version hex> <service>
1409         */
1410        synchronized (mLock) {
1411            for (String s : servInfo.getSupplicantQueryList()) {
1412                String command = "P2P_SERVICE_DEL ";
1413
1414                String[] data = s.split(" ");
1415                if (data.length < 2) {
1416                    return false;
1417                }
1418                if ("upnp".equals(data[0])) {
1419                    command += s;
1420                } else if ("bonjour".equals(data[0])) {
1421                    command += data[0];
1422                    command += (" " + data[1]);
1423                } else {
1424                    return false;
1425                }
1426                if (!doBooleanCommand(command)) {
1427                    return false;
1428                }
1429            }
1430        }
1431        return true;
1432    }
1433
1434    public boolean p2pServiceFlush() {
1435        return doBooleanCommand("P2P_SERVICE_FLUSH");
1436    }
1437
1438    public String p2pServDiscReq(String addr, String query) {
1439        String command = "P2P_SERV_DISC_REQ";
1440        command += (" " + addr);
1441        command += (" " + query);
1442
1443        return doStringCommand(command);
1444    }
1445
1446    public boolean p2pServDiscCancelReq(String id) {
1447        return doBooleanCommand("P2P_SERV_DISC_CANCEL_REQ " + id);
1448    }
1449
1450    /* Set the current mode of miracast operation.
1451     *  0 = disabled
1452     *  1 = operating as source
1453     *  2 = operating as sink
1454     */
1455    public void setMiracastMode(int mode) {
1456        // Note: optional feature on the driver. It is ok for this to fail.
1457        doBooleanCommand("DRIVER MIRACAST " + mode);
1458    }
1459
1460    public boolean fetchAnqp(String bssid, String subtypes) {
1461        return doBooleanCommand("ANQP_GET " + bssid + " " + subtypes);
1462    }
1463
1464    /*
1465     * NFC-related calls
1466     */
1467    public String getNfcWpsConfigurationToken(int netId) {
1468        return doStringCommand("WPS_NFC_CONFIG_TOKEN WPS " + netId);
1469    }
1470
1471    public String getNfcHandoverRequest() {
1472        return doStringCommand("NFC_GET_HANDOVER_REQ NDEF P2P-CR");
1473    }
1474
1475    public String getNfcHandoverSelect() {
1476        return doStringCommand("NFC_GET_HANDOVER_SEL NDEF P2P-CR");
1477    }
1478
1479    public boolean initiatorReportNfcHandover(String selectMessage) {
1480        return doBooleanCommand("NFC_REPORT_HANDOVER INIT P2P 00 " + selectMessage);
1481    }
1482
1483    public boolean responderReportNfcHandover(String requestMessage) {
1484        return doBooleanCommand("NFC_REPORT_HANDOVER RESP P2P " + requestMessage + " 00");
1485    }
1486
1487    /* WIFI HAL support */
1488
1489    // HAL command ids
1490    private static int sCmdId = 1;
1491    private static int getNewCmdIdLocked() {
1492        return sCmdId++;
1493    }
1494
1495    private static final String TAG = "WifiNative-HAL";
1496    private static long sWifiHalHandle = 0;             /* used by JNI to save wifi_handle */
1497    private static long[] sWifiIfaceHandles = null;     /* used by JNI to save interface handles */
1498    private static int sWlan0Index = -1;
1499    private static int sP2p0Index = -1;
1500    private static MonitorThread sThread;
1501    private static final int STOP_HAL_TIMEOUT_MS = 1000;
1502
1503    private static native boolean startHalNative();
1504    private static native void stopHalNative();
1505    private static native void waitForHalEventNative();
1506
1507    private static class MonitorThread extends Thread {
1508        public void run() {
1509            Log.i(TAG, "Waiting for HAL events mWifiHalHandle=" + Long.toString(sWifiHalHandle));
1510            waitForHalEventNative();
1511        }
1512    }
1513
1514    public boolean startHal() {
1515        String debugLog = "startHal stack: ";
1516        java.lang.StackTraceElement[] elements = Thread.currentThread().getStackTrace();
1517        for (int i = 2; i < elements.length && i <= 7; i++ ) {
1518            debugLog = debugLog + " - " + elements[i].getMethodName();
1519        }
1520
1521        mLocalLog.log(debugLog);
1522
1523        synchronized (mLock) {
1524            if (startHalNative() && (getInterfaces() != 0) && (sWlan0Index != -1)) {
1525                sThread = new MonitorThread();
1526                sThread.start();
1527                return true;
1528            } else {
1529                if (DBG) mLocalLog.log("Could not start hal");
1530                Log.e(TAG, "Could not start hal");
1531                return false;
1532            }
1533        }
1534    }
1535
1536    public void stopHal() {
1537        synchronized (mLock) {
1538            if (isHalStarted()) {
1539                stopHalNative();
1540                try {
1541                    sThread.join(STOP_HAL_TIMEOUT_MS);
1542                    Log.d(TAG, "HAL event thread stopped successfully");
1543                } catch (InterruptedException e) {
1544                    Log.e(TAG, "Could not stop HAL cleanly");
1545                }
1546                sThread = null;
1547                sWifiHalHandle = 0;
1548                sWifiIfaceHandles = null;
1549                sWlan0Index = -1;
1550                sP2p0Index = -1;
1551            }
1552        }
1553    }
1554
1555    public boolean isHalStarted() {
1556        return (sWifiHalHandle != 0);
1557    }
1558    private static native int getInterfacesNative();
1559
1560    public int getInterfaces() {
1561        synchronized (mLock) {
1562            if (isHalStarted()) {
1563                if (sWifiIfaceHandles == null) {
1564                    int num = getInterfacesNative();
1565                    int wifi_num = 0;
1566                    for (int i = 0; i < num; i++) {
1567                        String name = getInterfaceNameNative(i);
1568                        Log.i(TAG, "interface[" + i + "] = " + name);
1569                        if (name.equals("wlan0")) {
1570                            sWlan0Index = i;
1571                            wifi_num++;
1572                        } else if (name.equals("p2p0")) {
1573                            sP2p0Index = i;
1574                            wifi_num++;
1575                        }
1576                    }
1577                    return wifi_num;
1578                } else {
1579                    return sWifiIfaceHandles.length;
1580                }
1581            } else {
1582                return 0;
1583            }
1584        }
1585    }
1586
1587    private static native String getInterfaceNameNative(int index);
1588    public String getInterfaceName(int index) {
1589        synchronized (mLock) {
1590            return getInterfaceNameNative(index);
1591        }
1592    }
1593
1594    public static class ScanCapabilities {
1595        public int  max_scan_cache_size;
1596        public int  max_scan_buckets;
1597        public int  max_ap_cache_per_scan;
1598        public int  max_rssi_sample_size;
1599        public int  max_scan_reporting_threshold;
1600        public int  max_hotlist_bssids;
1601        public int  max_significant_wifi_change_aps;
1602    }
1603
1604    public boolean getScanCapabilities(ScanCapabilities capabilities) {
1605        synchronized (mLock) {
1606            return isHalStarted() && getScanCapabilitiesNative(sWlan0Index, capabilities);
1607        }
1608    }
1609
1610    private static native boolean getScanCapabilitiesNative(
1611            int iface, ScanCapabilities capabilities);
1612
1613    private static native boolean startScanNative(int iface, int id, ScanSettings settings);
1614    private static native boolean stopScanNative(int iface, int id);
1615    private static native WifiScanner.ScanData[] getScanResultsNative(int iface, boolean flush);
1616    private static native WifiLinkLayerStats getWifiLinkLayerStatsNative(int iface);
1617    private static native void setWifiLinkLayerStatsNative(int iface, int enable);
1618
1619    public static class ChannelSettings {
1620        int frequency;
1621        int dwell_time_ms;
1622        boolean passive;
1623    }
1624
1625    public static class BucketSettings {
1626        int bucket;
1627        int band;
1628        int period_ms;
1629        int report_events;
1630        int num_channels;
1631        ChannelSettings channels[];
1632    }
1633
1634    public static class ScanSettings {
1635        int base_period_ms;
1636        int max_ap_per_scan;
1637        int report_threshold_percent;
1638        int report_threshold_num_scans;
1639        int num_buckets;
1640        BucketSettings buckets[];
1641    }
1642
1643    public static interface ScanEventHandler {
1644        void onScanResultsAvailable();
1645        void onFullScanResult(ScanResult fullScanResult);
1646        void onScanStatus();
1647        void onScanPaused(WifiScanner.ScanData[] data);
1648        void onScanRestarted();
1649    }
1650
1651    // Callback from native
1652    private static void onScanResultsAvailable(int id) {
1653        ScanEventHandler handler = sScanEventHandler;
1654        if (handler != null) {
1655            handler.onScanResultsAvailable();
1656        }
1657    }
1658
1659    /* scan status, keep these values in sync with gscan.h */
1660    private static int WIFI_SCAN_BUFFER_FULL = 0;
1661    private static int WIFI_SCAN_COMPLETE = 1;
1662
1663    // Callback from native
1664    private static void onScanStatus(int status) {
1665        ScanEventHandler handler = sScanEventHandler;
1666        if (status == WIFI_SCAN_BUFFER_FULL) {
1667            /* we have a separate event to take care of this */
1668        } else if (status == WIFI_SCAN_COMPLETE) {
1669            if (handler != null) {
1670                handler.onScanStatus();
1671            }
1672        }
1673    }
1674
1675    public static  WifiSsid createWifiSsid(byte[] rawSsid) {
1676        String ssidHexString = String.valueOf(HexEncoding.encode(rawSsid));
1677
1678        if (ssidHexString == null) {
1679            return null;
1680        }
1681
1682        WifiSsid wifiSsid = WifiSsid.createFromHex(ssidHexString);
1683
1684        return wifiSsid;
1685    }
1686
1687    public static String ssidConvert(byte[] rawSsid) {
1688        String ssid;
1689
1690        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
1691        try {
1692            CharBuffer decoded = decoder.decode(ByteBuffer.wrap(rawSsid));
1693            ssid = decoded.toString();
1694        } catch (CharacterCodingException cce) {
1695            ssid = null;
1696        }
1697
1698        if (ssid == null) {
1699            ssid = new String(rawSsid, StandardCharsets.ISO_8859_1);
1700        }
1701
1702        return ssid;
1703    }
1704
1705    // Called from native
1706    public static boolean setSsid(byte[] rawSsid, ScanResult result) {
1707        if (rawSsid == null || rawSsid.length == 0 || result == null) {
1708            return false;
1709        }
1710
1711        result.SSID = ssidConvert(rawSsid);
1712        result.wifiSsid = createWifiSsid(rawSsid);
1713        return true;
1714    }
1715
1716    private static void populateScanResult(ScanResult result, byte bytes[], String dbg) {
1717        if (bytes == null) return;
1718        if (dbg == null) dbg = "";
1719
1720        InformationElementUtil.HtOperation htOperation = new InformationElementUtil.HtOperation();
1721        InformationElementUtil.VhtOperation vhtOperation =
1722                new InformationElementUtil.VhtOperation();
1723        InformationElementUtil.ExtendedCapabilities extendedCaps =
1724                new InformationElementUtil.ExtendedCapabilities();
1725
1726        ScanResult.InformationElement elements[] =
1727                InformationElementUtil.parseInformationElements(bytes);
1728        for (ScanResult.InformationElement ie : elements) {
1729            if(ie.id == ScanResult.InformationElement.EID_HT_OPERATION) {
1730                htOperation.from(ie);
1731            } else if(ie.id == ScanResult.InformationElement.EID_VHT_OPERATION) {
1732                vhtOperation.from(ie);
1733            } else if (ie.id == ScanResult.InformationElement.EID_EXTENDED_CAPS) {
1734                extendedCaps.from(ie);
1735            }
1736        }
1737
1738        if (extendedCaps.is80211McRTTResponder) {
1739            result.setFlag(ScanResult.FLAG_80211mc_RESPONDER);
1740        } else {
1741            result.clearFlag(ScanResult.FLAG_80211mc_RESPONDER);
1742        }
1743
1744        //handle RTT related information
1745        if (vhtOperation.isValid()) {
1746            result.channelWidth = vhtOperation.getChannelWidth();
1747            result.centerFreq0 = vhtOperation.getCenterFreq0();
1748            result.centerFreq1 = vhtOperation.getCenterFreq1();
1749        } else {
1750            result.channelWidth = htOperation.getChannelWidth();
1751            result.centerFreq0 = htOperation.getCenterFreq0(result.frequency);
1752            result.centerFreq1  = 0;
1753        }
1754        if(DBG) {
1755            Log.d(TAG, dbg + "SSID: " + result.SSID + " ChannelWidth is: " + result.channelWidth +
1756                    " PrimaryFreq: " + result.frequency +" mCenterfreq0: " + result.centerFreq0 +
1757                    " mCenterfreq1: " + result.centerFreq1 + (extendedCaps.is80211McRTTResponder ?
1758                    "Support RTT reponder: " : "Do not support RTT responder"));
1759        }
1760
1761        result.informationElements = elements;
1762    }
1763
1764    // Callback from native
1765    private static void onFullScanResult(int id, ScanResult result, byte bytes[]) {
1766        if (DBG) Log.i(TAG, "Got a full scan results event, ssid = " + result.SSID + ", " +
1767                "num = " + bytes.length);
1768
1769        ScanEventHandler handler = sScanEventHandler;
1770        if (handler != null) {
1771            populateScanResult(result, bytes, " onFullScanResult ");
1772            handler.onFullScanResult(result);
1773        }
1774    }
1775
1776    private static int sScanCmdId = 0;
1777    private static ScanEventHandler sScanEventHandler;
1778    private static ScanSettings sScanSettings;
1779
1780    public boolean startScan(ScanSettings settings, ScanEventHandler eventHandler) {
1781        synchronized (mLock) {
1782            if (isHalStarted()) {
1783                if (sScanCmdId != 0) {
1784                    stopScan();
1785                } else if (sScanSettings != null || sScanEventHandler != null) {
1786                /* current scan is paused; no need to stop it */
1787                }
1788
1789                sScanCmdId = getNewCmdIdLocked();
1790
1791                sScanSettings = settings;
1792                sScanEventHandler = eventHandler;
1793
1794                if (startScanNative(sWlan0Index, sScanCmdId, settings) == false) {
1795                    sScanEventHandler = null;
1796                    sScanSettings = null;
1797                    sScanCmdId = 0;
1798                    return false;
1799                }
1800
1801                return true;
1802            } else {
1803                return false;
1804            }
1805        }
1806    }
1807
1808    public void stopScan() {
1809        synchronized (mLock) {
1810            if (isHalStarted()) {
1811                if (sScanCmdId != 0) {
1812                    stopScanNative(sWlan0Index, sScanCmdId);
1813                }
1814                sScanSettings = null;
1815                sScanEventHandler = null;
1816                sScanCmdId = 0;
1817            }
1818        }
1819    }
1820
1821    public void pauseScan() {
1822        synchronized (mLock) {
1823            if (isHalStarted()) {
1824                if (sScanCmdId != 0 && sScanSettings != null && sScanEventHandler != null) {
1825                    Log.d(TAG, "Pausing scan");
1826                    WifiScanner.ScanData scanData[] = getScanResultsNative(sWlan0Index, true);
1827                    stopScanNative(sWlan0Index, sScanCmdId);
1828                    sScanCmdId = 0;
1829                    sScanEventHandler.onScanPaused(scanData);
1830                }
1831            }
1832        }
1833    }
1834
1835    public void restartScan() {
1836        synchronized (mLock) {
1837            if (isHalStarted()) {
1838                if (sScanCmdId == 0 && sScanSettings != null && sScanEventHandler != null) {
1839                    Log.d(TAG, "Restarting scan");
1840                    ScanEventHandler handler = sScanEventHandler;
1841                    ScanSettings settings = sScanSettings;
1842                    if (startScan(sScanSettings, sScanEventHandler)) {
1843                        sScanEventHandler.onScanRestarted();
1844                    } else {
1845                    /* we are still paused; don't change state */
1846                        sScanEventHandler = handler;
1847                        sScanSettings = settings;
1848                    }
1849                }
1850            }
1851        }
1852    }
1853
1854    public WifiScanner.ScanData[] getScanResults(boolean flush) {
1855        synchronized (mLock) {
1856            if (isHalStarted()) {
1857                return getScanResultsNative(sWlan0Index, flush);
1858            } else {
1859                return null;
1860            }
1861        }
1862    }
1863
1864    public static interface HotlistEventHandler {
1865        void onHotlistApFound (ScanResult[] result);
1866        void onHotlistApLost  (ScanResult[] result);
1867    }
1868
1869    private static int sHotlistCmdId = 0;
1870    private static HotlistEventHandler sHotlistEventHandler;
1871
1872    private native static boolean setHotlistNative(int iface, int id,
1873            WifiScanner.HotlistSettings settings);
1874    private native static boolean resetHotlistNative(int iface, int id);
1875
1876    public boolean setHotlist(WifiScanner.HotlistSettings settings,
1877            HotlistEventHandler eventHandler) {
1878        synchronized (mLock) {
1879            if (isHalStarted()) {
1880                if (sHotlistCmdId != 0) {
1881                    return false;
1882                } else {
1883                    sHotlistCmdId = getNewCmdIdLocked();
1884                }
1885
1886                sHotlistEventHandler = eventHandler;
1887                if (setHotlistNative(sWlan0Index, sHotlistCmdId, settings) == false) {
1888                    sHotlistEventHandler = null;
1889                    return false;
1890                }
1891
1892                return true;
1893            } else {
1894                return false;
1895            }
1896        }
1897    }
1898
1899    public void resetHotlist() {
1900        synchronized (mLock) {
1901            if (isHalStarted()) {
1902                if (sHotlistCmdId != 0) {
1903                    resetHotlistNative(sWlan0Index, sHotlistCmdId);
1904                    sHotlistCmdId = 0;
1905                    sHotlistEventHandler = null;
1906                }
1907            }
1908        }
1909    }
1910
1911    // Callback from native
1912    private static void onHotlistApFound(int id, ScanResult[] results) {
1913        HotlistEventHandler handler = sHotlistEventHandler;
1914        if (handler != null) {
1915            handler.onHotlistApFound(results);
1916        } else {
1917            /* this can happen because of race conditions */
1918            Log.d(TAG, "Ignoring hotlist AP found event");
1919        }
1920    }
1921
1922    // Callback from native
1923    private static void onHotlistApLost(int id, ScanResult[] results) {
1924        HotlistEventHandler handler = sHotlistEventHandler;
1925        if (handler != null) {
1926            handler.onHotlistApLost(results);
1927        } else {
1928            /* this can happen because of race conditions */
1929            Log.d(TAG, "Ignoring hotlist AP lost event");
1930        }
1931    }
1932
1933    public static interface SignificantWifiChangeEventHandler {
1934        void onChangesFound(ScanResult[] result);
1935    }
1936
1937    private static SignificantWifiChangeEventHandler sSignificantWifiChangeHandler;
1938    private static int sSignificantWifiChangeCmdId;
1939
1940    private static native boolean trackSignificantWifiChangeNative(
1941            int iface, int id, WifiScanner.WifiChangeSettings settings);
1942    private static native boolean untrackSignificantWifiChangeNative(int iface, int id);
1943
1944    public boolean trackSignificantWifiChange(
1945            WifiScanner.WifiChangeSettings settings, SignificantWifiChangeEventHandler handler) {
1946        synchronized (mLock) {
1947            if (isHalStarted()) {
1948                if (sSignificantWifiChangeCmdId != 0) {
1949                    return false;
1950                } else {
1951                    sSignificantWifiChangeCmdId = getNewCmdIdLocked();
1952                }
1953
1954                sSignificantWifiChangeHandler = handler;
1955                if (trackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId,
1956                        settings) == false) {
1957                    sSignificantWifiChangeHandler = null;
1958                    return false;
1959                }
1960
1961                return true;
1962            } else {
1963                return false;
1964            }
1965
1966        }
1967    }
1968
1969    public void untrackSignificantWifiChange() {
1970        synchronized (mLock) {
1971            if (isHalStarted()) {
1972                if (sSignificantWifiChangeCmdId != 0) {
1973                    untrackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId);
1974                    sSignificantWifiChangeCmdId = 0;
1975                    sSignificantWifiChangeHandler = null;
1976                }
1977            }
1978        }
1979    }
1980
1981    // Callback from native
1982    private static void onSignificantWifiChange(int id, ScanResult[] results) {
1983        SignificantWifiChangeEventHandler handler = sSignificantWifiChangeHandler;
1984        if (handler != null) {
1985            handler.onChangesFound(results);
1986        } else {
1987            /* this can happen because of race conditions */
1988            Log.d(TAG, "Ignoring significant wifi change");
1989        }
1990    }
1991
1992    public WifiLinkLayerStats getWifiLinkLayerStats(String iface) {
1993        // TODO: use correct iface name to Index translation
1994        if (iface == null) return null;
1995        synchronized (mLock) {
1996            if (isHalStarted()) {
1997                return getWifiLinkLayerStatsNative(sWlan0Index);
1998            } else {
1999                return null;
2000            }
2001        }
2002    }
2003
2004    public void setWifiLinkLayerStats(String iface, int enable) {
2005        if (iface == null) return;
2006        synchronized (mLock) {
2007            if (isHalStarted()) {
2008                setWifiLinkLayerStatsNative(sWlan0Index, enable);
2009            }
2010        }
2011    }
2012
2013    public static native int getSupportedFeatureSetNative(int iface);
2014    public int getSupportedFeatureSet() {
2015        synchronized (mLock) {
2016            if (isHalStarted()) {
2017                return getSupportedFeatureSetNative(sWlan0Index);
2018            } else {
2019                Log.d(TAG, "Failing getSupportedFeatureset because HAL isn't started");
2020                return 0;
2021            }
2022        }
2023    }
2024
2025    /* Rtt related commands/events */
2026    public static interface RttEventHandler {
2027        void onRttResults(RttManager.RttResult[] result);
2028    }
2029
2030    private static RttEventHandler sRttEventHandler;
2031    private static int sRttCmdId;
2032
2033    // Callback from native
2034    private static void onRttResults(int id, RttManager.RttResult[] results) {
2035        RttEventHandler handler = sRttEventHandler;
2036        if (handler != null && id == sRttCmdId) {
2037            Log.d(TAG, "Received " + results.length + " rtt results");
2038            handler.onRttResults(results);
2039            sRttCmdId = 0;
2040        } else {
2041            Log.d(TAG, "RTT Received event for unknown cmd = " + id +
2042                    ", current id = " + sRttCmdId);
2043        }
2044    }
2045
2046    private static native boolean requestRangeNative(
2047            int iface, int id, RttManager.RttParams[] params);
2048    private static native boolean cancelRangeRequestNative(
2049            int iface, int id, RttManager.RttParams[] params);
2050
2051    public boolean requestRtt(
2052            RttManager.RttParams[] params, RttEventHandler handler) {
2053        synchronized (mLock) {
2054            if (isHalStarted()) {
2055                if (sRttCmdId != 0) {
2056                    Log.v("TAG", "Last one is still under measurement!");
2057                    return false;
2058                } else {
2059                    sRttCmdId = getNewCmdIdLocked();
2060                }
2061                sRttEventHandler = handler;
2062                Log.v(TAG, "native issue RTT request");
2063                return requestRangeNative(sWlan0Index, sRttCmdId, params);
2064            } else {
2065                return false;
2066            }
2067        }
2068    }
2069
2070    public boolean cancelRtt(RttManager.RttParams[] params) {
2071        synchronized (mLock) {
2072            if (isHalStarted()) {
2073                if (sRttCmdId == 0) {
2074                    return false;
2075                }
2076
2077                sRttCmdId = 0;
2078
2079                if (cancelRangeRequestNative(sWlan0Index, sRttCmdId, params)) {
2080                    sRttEventHandler = null;
2081                    Log.v(TAG, "RTT cancel Request Successfully");
2082                    return true;
2083                } else {
2084                    Log.e(TAG, "RTT cancel Request failed");
2085                    return false;
2086                }
2087            } else {
2088                return false;
2089            }
2090        }
2091    }
2092
2093    private static native boolean setScanningMacOuiNative(int iface, byte[] oui);
2094
2095    public boolean setScanningMacOui(byte[] oui) {
2096        synchronized (mLock) {
2097            if (isHalStarted()) {
2098                return setScanningMacOuiNative(sWlan0Index, oui);
2099            } else {
2100                return false;
2101            }
2102        }
2103    }
2104
2105    private static native int[] getChannelsForBandNative(
2106            int iface, int band);
2107
2108    public int [] getChannelsForBand(int band) {
2109        synchronized (mLock) {
2110            if (isHalStarted()) {
2111                return getChannelsForBandNative(sWlan0Index, band);
2112            } else {
2113                return null;
2114            }
2115        }
2116    }
2117
2118    private static native boolean isGetChannelsForBandSupportedNative();
2119    public boolean isGetChannelsForBandSupported(){
2120        synchronized (mLock) {
2121            if (isHalStarted()) {
2122                return isGetChannelsForBandSupportedNative();
2123            } else {
2124                return false;
2125            }
2126        }
2127    }
2128
2129    private static native boolean setDfsFlagNative(int iface, boolean dfsOn);
2130    public boolean setDfsFlag(boolean dfsOn) {
2131        synchronized (mLock) {
2132            if (isHalStarted()) {
2133                return setDfsFlagNative(sWlan0Index, dfsOn);
2134            } else {
2135                return false;
2136            }
2137        }
2138    }
2139
2140    private static native boolean toggleInterfaceNative(int on);
2141    public boolean toggleInterface(int on) {
2142        synchronized (mLock) {
2143            if (isHalStarted()) {
2144                return toggleInterfaceNative(on);
2145            } else {
2146                return false;
2147            }
2148        }
2149    }
2150
2151    private static native RttManager.RttCapabilities getRttCapabilitiesNative(int iface);
2152    public RttManager.RttCapabilities getRttCapabilities() {
2153        synchronized (mLock) {
2154            if (isHalStarted()) {
2155                return getRttCapabilitiesNative(sWlan0Index);
2156            } else {
2157                return null;
2158            }
2159        }
2160    }
2161
2162    private static native boolean setCountryCodeHalNative(int iface, String CountryCode);
2163    public boolean setCountryCodeHal(String CountryCode) {
2164        synchronized (mLock) {
2165            if (isHalStarted()) {
2166                return setCountryCodeHalNative(sWlan0Index, CountryCode);
2167            } else {
2168                return false;
2169            }
2170        }
2171    }
2172
2173    /* Rtt related commands/events */
2174    public abstract class TdlsEventHandler {
2175        abstract public void onTdlsStatus(String macAddr, int status, int reason);
2176    }
2177
2178    private static TdlsEventHandler sTdlsEventHandler;
2179
2180    private static native boolean enableDisableTdlsNative(int iface, boolean enable,
2181            String macAddr);
2182    public boolean enableDisableTdls(boolean enable, String macAdd, TdlsEventHandler tdlsCallBack) {
2183        synchronized (mLock) {
2184            sTdlsEventHandler = tdlsCallBack;
2185            return enableDisableTdlsNative(sWlan0Index, enable, macAdd);
2186        }
2187    }
2188
2189    // Once TDLS per mac and event feature is implemented, this class definition should be
2190    // moved to the right place, like WifiManager etc
2191    public static class TdlsStatus {
2192        int channel;
2193        int global_operating_class;
2194        int state;
2195        int reason;
2196    }
2197    private static native TdlsStatus getTdlsStatusNative(int iface, String macAddr);
2198    public TdlsStatus getTdlsStatus(String macAdd) {
2199        synchronized (mLock) {
2200            if (isHalStarted()) {
2201                return getTdlsStatusNative(sWlan0Index, macAdd);
2202            } else {
2203                return null;
2204            }
2205        }
2206    }
2207
2208    //ToFix: Once TDLS per mac and event feature is implemented, this class definition should be
2209    // moved to the right place, like WifiStateMachine etc
2210    public static class TdlsCapabilities {
2211        /* Maximum TDLS session number can be supported by the Firmware and hardware */
2212        int maxConcurrentTdlsSessionNumber;
2213        boolean isGlobalTdlsSupported;
2214        boolean isPerMacTdlsSupported;
2215        boolean isOffChannelTdlsSupported;
2216    }
2217
2218
2219
2220    private static native TdlsCapabilities getTdlsCapabilitiesNative(int iface);
2221    public TdlsCapabilities getTdlsCapabilities () {
2222        synchronized (mLock) {
2223            if (isHalStarted()) {
2224                return getTdlsCapabilitiesNative(sWlan0Index);
2225            } else {
2226                return null;
2227            }
2228        }
2229    }
2230
2231    private static boolean onTdlsStatus(String macAddr, int status, int reason) {
2232        TdlsEventHandler handler = sTdlsEventHandler;
2233        if (handler == null) {
2234            return false;
2235        } else {
2236            handler.onTdlsStatus(macAddr, status, reason);
2237            return true;
2238        }
2239    }
2240
2241    //---------------------------------------------------------------------------------
2242
2243    /* Wifi Logger commands/events */
2244
2245    public static interface WifiLoggerEventHandler {
2246        void onRingBufferData(RingBufferStatus status, byte[] buffer);
2247        void onWifiAlert(int errorCode, byte[] buffer);
2248    }
2249
2250    private static WifiLoggerEventHandler sWifiLoggerEventHandler = null;
2251
2252    // Callback from native
2253    private static void onRingBufferData(RingBufferStatus status, byte[] buffer) {
2254        WifiLoggerEventHandler handler = sWifiLoggerEventHandler;
2255        if (handler != null)
2256            handler.onRingBufferData(status, buffer);
2257    }
2258
2259    // Callback from native
2260    private static void onWifiAlert(byte[] buffer, int errorCode) {
2261        WifiLoggerEventHandler handler = sWifiLoggerEventHandler;
2262        if (handler != null)
2263            handler.onWifiAlert(errorCode, buffer);
2264    }
2265
2266    private static int sLogCmdId = -1;
2267    private static native boolean setLoggingEventHandlerNative(int iface, int id);
2268    public boolean setLoggingEventHandler(WifiLoggerEventHandler handler) {
2269        synchronized (mLock) {
2270            if (isHalStarted()) {
2271                int oldId =  sLogCmdId;
2272                sLogCmdId = getNewCmdIdLocked();
2273                if (!setLoggingEventHandlerNative(sWlan0Index, sLogCmdId)) {
2274                    sLogCmdId = oldId;
2275                    return false;
2276                }
2277                sWifiLoggerEventHandler = handler;
2278                return true;
2279            } else {
2280                return false;
2281            }
2282        }
2283    }
2284
2285    private static native boolean startLoggingRingBufferNative(int iface, int verboseLevel,
2286            int flags, int minIntervalSec ,int minDataSize, String ringName);
2287    public boolean startLoggingRingBuffer(int verboseLevel, int flags, int maxInterval,
2288            int minDataSize, String ringName){
2289        synchronized (mLock) {
2290            if (isHalStarted()) {
2291                return startLoggingRingBufferNative(sWlan0Index, verboseLevel, flags, maxInterval,
2292                        minDataSize, ringName);
2293            } else {
2294                return false;
2295            }
2296        }
2297    }
2298
2299    private static native int getSupportedLoggerFeatureSetNative(int iface);
2300    public int getSupportedLoggerFeatureSet() {
2301        synchronized (mLock) {
2302            if (isHalStarted()) {
2303                return getSupportedLoggerFeatureSetNative(sWlan0Index);
2304            } else {
2305                return 0;
2306            }
2307        }
2308    }
2309
2310    private static native boolean resetLogHandlerNative(int iface, int id);
2311    public boolean resetLogHandler() {
2312        synchronized (mLock) {
2313            if (isHalStarted()) {
2314                if (sLogCmdId == -1) {
2315                    Log.e(TAG,"Can not reset handler Before set any handler");
2316                    return false;
2317                }
2318                sWifiLoggerEventHandler = null;
2319                if (resetLogHandlerNative(sWlan0Index, sLogCmdId)) {
2320                    sLogCmdId = -1;
2321                    return true;
2322                } else {
2323                    return false;
2324                }
2325            } else {
2326                return false;
2327            }
2328        }
2329    }
2330
2331    private static native String getDriverVersionNative(int iface);
2332    public String getDriverVersion() {
2333        synchronized (mLock) {
2334            if (isHalStarted()) {
2335                return getDriverVersionNative(sWlan0Index);
2336            } else {
2337                return "";
2338            }
2339        }
2340    }
2341
2342
2343    private static native String getFirmwareVersionNative(int iface);
2344    public String getFirmwareVersion() {
2345        synchronized (mLock) {
2346            if (isHalStarted()) {
2347                return getFirmwareVersionNative(sWlan0Index);
2348            } else {
2349                return "";
2350            }
2351        }
2352    }
2353
2354    public static class RingBufferStatus{
2355        String name;
2356        int flag;
2357        int ringBufferId;
2358        int ringBufferByteSize;
2359        int verboseLevel;
2360        int writtenBytes;
2361        int readBytes;
2362        int writtenRecords;
2363
2364        @Override
2365        public String toString() {
2366            return "name: " + name + " flag: " + flag + " ringBufferId: " + ringBufferId +
2367                    " ringBufferByteSize: " +ringBufferByteSize + " verboseLevel: " +verboseLevel +
2368                    " writtenBytes: " + writtenBytes + " readBytes: " + readBytes +
2369                    " writtenRecords: " + writtenRecords;
2370        }
2371    }
2372
2373    private static native RingBufferStatus[] getRingBufferStatusNative(int iface);
2374    public RingBufferStatus[] getRingBufferStatus() {
2375        synchronized (mLock) {
2376            if (isHalStarted()) {
2377                return getRingBufferStatusNative(sWlan0Index);
2378            } else {
2379                return null;
2380            }
2381        }
2382    }
2383
2384    private static native boolean getRingBufferDataNative(int iface, String ringName);
2385    public boolean getRingBufferData(String ringName) {
2386        synchronized (mLock) {
2387            if (isHalStarted()) {
2388                return getRingBufferDataNative(sWlan0Index, ringName);
2389            } else {
2390                return false;
2391            }
2392        }
2393    }
2394
2395    private static byte[] mFwMemoryDump;
2396    // Callback from native
2397    private static void onWifiFwMemoryAvailable(byte[] buffer) {
2398        mFwMemoryDump = buffer;
2399        if (DBG) {
2400            Log.d(TAG, "onWifiFwMemoryAvailable is called and buffer length is: " +
2401                    (buffer == null ? 0 :  buffer.length));
2402        }
2403    }
2404
2405    private static native boolean getFwMemoryDumpNative(int iface);
2406    public byte[] getFwMemoryDump() {
2407        synchronized (mLock) {
2408            if (isHalStarted()) {
2409                if(getFwMemoryDumpNative(sWlan0Index)) {
2410                    byte[] fwMemoryDump = mFwMemoryDump;
2411                    mFwMemoryDump = null;
2412                    return fwMemoryDump;
2413                } else {
2414                    return null;
2415                }
2416            }
2417            return null;
2418        }
2419    }
2420
2421    //---------------------------------------------------------------------------------
2422    /* Configure ePNO */
2423
2424    /* pno flags, keep these values in sync with gscan.h */
2425    private static int WIFI_PNO_AUTH_CODE_OPEN  = 1; // open
2426    private static int WIFI_PNO_AUTH_CODE_PSK   = 2; // WPA_PSK or WPA2PSK
2427    private static int WIFI_PNO_AUTH_CODE_EAPOL = 4; // any EAPOL
2428
2429    // Whether directed scan needs to be performed (for hidden SSIDs)
2430    private static int WIFI_PNO_FLAG_DIRECTED_SCAN = 1;
2431    // Whether PNO event shall be triggered if the network is found on A band
2432    private static int WIFI_PNO_FLAG_A_BAND = 2;
2433    // Whether PNO event shall be triggered if the network is found on G band
2434    private static int WIFI_PNO_FLAG_G_BAND = 4;
2435    // Whether strict matching is required (i.e. firmware shall not match on the entire SSID)
2436    private static int WIFI_PNO_FLAG_STRICT_MATCH = 8;
2437
2438    public static class WifiPnoNetwork {
2439        String SSID;
2440        int rssi_threshold;
2441        int flags;
2442        int auth;
2443        String configKey; // kept for reference
2444
2445        WifiPnoNetwork(WifiConfiguration config, int threshold) {
2446            if (config.SSID == null) {
2447                this.SSID = "";
2448                this.flags = WIFI_PNO_FLAG_DIRECTED_SCAN;
2449            } else {
2450                this.SSID = config.SSID;
2451            }
2452            this.rssi_threshold = threshold;
2453            if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
2454                auth |= WIFI_PNO_AUTH_CODE_PSK;
2455            } else if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) ||
2456                    config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
2457                auth |= WIFI_PNO_AUTH_CODE_EAPOL;
2458            } else if (config.wepKeys[0] != null) {
2459                auth |= WIFI_PNO_AUTH_CODE_OPEN;
2460            } else {
2461                auth |= WIFI_PNO_AUTH_CODE_OPEN;
2462            }
2463
2464            flags |= WIFI_PNO_FLAG_A_BAND | WIFI_PNO_FLAG_G_BAND;
2465            configKey = config.configKey();
2466        }
2467
2468        @Override
2469        public String toString() {
2470            StringBuilder sbuf = new StringBuilder();
2471            sbuf.append(this.SSID);
2472            sbuf.append(" flags=").append(this.flags);
2473            sbuf.append(" rssi=").append(this.rssi_threshold);
2474            sbuf.append(" auth=").append(this.auth);
2475            return sbuf.toString();
2476        }
2477    }
2478
2479    public static interface WifiPnoEventHandler {
2480        void onPnoNetworkFound(ScanResult results[]);
2481    }
2482
2483    private static WifiPnoEventHandler sWifiPnoEventHandler;
2484
2485    private static int sPnoCmdId = 0;
2486
2487    private native static boolean setPnoListNative(int iface, int id, WifiPnoNetwork list[]);
2488
2489    public boolean setPnoList(WifiPnoNetwork list[],
2490                                                  WifiPnoEventHandler eventHandler) {
2491        Log.e(TAG, "setPnoList cmd " + sPnoCmdId);
2492
2493        synchronized (mLock) {
2494            if (isHalStarted()) {
2495
2496                sPnoCmdId = getNewCmdIdLocked();
2497
2498                sWifiPnoEventHandler = eventHandler;
2499                if (setPnoListNative(sWlan0Index, sPnoCmdId, list)) {
2500                    return true;
2501                }
2502            }
2503
2504            sWifiPnoEventHandler = null;
2505            return false;
2506        }
2507    }
2508
2509    // Callback from native
2510    private static void onPnoNetworkFound(int id, ScanResult[] results) {
2511        if (results == null) {
2512            Log.e(TAG, "onPnoNetworkFound null results");
2513            return;
2514
2515        }
2516        Log.d(TAG, "WifiNative.onPnoNetworkFound result " + results.length);
2517
2518        WifiPnoEventHandler handler = sWifiPnoEventHandler;
2519        if (sPnoCmdId != 0 && handler != null) {
2520            for (int i=0; i<results.length; i++) {
2521                Log.e(TAG, "onPnoNetworkFound SSID " + results[i].SSID
2522                        + " " + results[i].level + " " + results[i].frequency);
2523
2524                populateScanResult(results[i], results[i].bytes, "onPnoNetworkFound ");
2525                results[i].wifiSsid = WifiSsid.createFromAsciiEncoded(results[i].SSID);
2526            }
2527
2528            handler.onPnoNetworkFound(results);
2529        } else {
2530            /* this can happen because of race conditions */
2531            Log.d(TAG, "Ignoring Pno Network found event");
2532        }
2533    }
2534
2535    public static class WifiLazyRoamParams {
2536        int A_band_boost_threshold;
2537        int A_band_penalty_threshold;
2538        int A_band_boost_factor;
2539        int A_band_penalty_factor;
2540        int A_band_max_boost;
2541        int lazy_roam_hysteresis;
2542        int alert_roam_rssi_trigger;
2543
2544        WifiLazyRoamParams() {
2545        }
2546
2547        @Override
2548        public String toString() {
2549            StringBuilder sbuf = new StringBuilder();
2550            sbuf.append(" A_band_boost_threshold=").append(this.A_band_boost_threshold);
2551            sbuf.append(" A_band_penalty_threshold=").append(this.A_band_penalty_threshold);
2552            sbuf.append(" A_band_boost_factor=").append(this.A_band_boost_factor);
2553            sbuf.append(" A_band_penalty_factor=").append(this.A_band_penalty_factor);
2554            sbuf.append(" A_band_max_boost=").append(this.A_band_max_boost);
2555            sbuf.append(" lazy_roam_hysteresis=").append(this.lazy_roam_hysteresis);
2556            sbuf.append(" alert_roam_rssi_trigger=").append(this.alert_roam_rssi_trigger);
2557            return sbuf.toString();
2558        }
2559    }
2560
2561    private native static boolean setLazyRoamNative(int iface, int id,
2562                                              boolean enabled, WifiLazyRoamParams param);
2563
2564    public boolean setLazyRoam(boolean enabled, WifiLazyRoamParams params) {
2565        synchronized (mLock) {
2566            if (isHalStarted()) {
2567                sPnoCmdId = getNewCmdIdLocked();
2568                return setLazyRoamNative(sWlan0Index, sPnoCmdId, enabled, params);
2569            } else {
2570                return false;
2571            }
2572        }
2573    }
2574
2575    private native static boolean setBssidBlacklistNative(int iface, int id,
2576                                              String list[]);
2577
2578    public boolean setBssidBlacklist(String list[]) {
2579        int size = 0;
2580        if (list != null) {
2581            size = list.length;
2582        }
2583        Log.e(TAG, "setBssidBlacklist cmd " + sPnoCmdId + " size " + size);
2584
2585        synchronized (mLock) {
2586            if (isHalStarted()) {
2587                sPnoCmdId = getNewCmdIdLocked();
2588                return setBssidBlacklistNative(sWlan0Index, sPnoCmdId, list);
2589            } else {
2590                return false;
2591            }
2592        }
2593    }
2594
2595    private native static boolean setSsidWhitelistNative(int iface, int id, String list[]);
2596
2597    public boolean setSsidWhitelist(String list[]) {
2598        int size = 0;
2599        if (list != null) {
2600            size = list.length;
2601        }
2602        Log.e(TAG, "setSsidWhitelist cmd " + sPnoCmdId + " size " + size);
2603
2604        synchronized (mLock) {
2605            if (isHalStarted()) {
2606                sPnoCmdId = getNewCmdIdLocked();
2607
2608                return setSsidWhitelistNative(sWlan0Index, sPnoCmdId, list);
2609            } else {
2610                return false;
2611            }
2612        }
2613    }
2614
2615    private native static int startSendingOffloadedPacketNative(int iface, int idx,
2616                                    byte[] srcMac, byte[] dstMac, byte[] pktData, int period);
2617
2618    public int
2619    startSendingOffloadedPacket(int slot, KeepalivePacketData keepAlivePacket, int period) {
2620        Log.d(TAG, "startSendingOffloadedPacket slot=" + slot + " period=" + period);
2621
2622        String[] macAddrStr = getMacAddress().split(":");
2623        byte[] srcMac = new byte[6];
2624        for(int i = 0; i < 6; i++) {
2625            Integer hexVal = Integer.parseInt(macAddrStr[i], 16);
2626            srcMac[i] = hexVal.byteValue();
2627        }
2628        synchronized (mLock) {
2629            if (isHalStarted()) {
2630                return startSendingOffloadedPacketNative(sWlan0Index, slot, srcMac,
2631                        keepAlivePacket.dstMac, keepAlivePacket.data, period);
2632            } else {
2633                return -1;
2634            }
2635        }
2636    }
2637
2638    private native static int stopSendingOffloadedPacketNative(int iface, int idx);
2639
2640    public int
2641    stopSendingOffloadedPacket(int slot) {
2642        Log.d(TAG, "stopSendingOffloadedPacket " + slot);
2643        synchronized (mLock) {
2644            if (isHalStarted()) {
2645                return stopSendingOffloadedPacketNative(sWlan0Index, slot);
2646            } else {
2647                return -1;
2648            }
2649        }
2650    }
2651
2652    public static interface WifiRssiEventHandler {
2653        void onRssiThresholdBreached(byte curRssi);
2654    }
2655
2656    private static WifiRssiEventHandler sWifiRssiEventHandler;
2657
2658    // Callback from native
2659    private static void onRssiThresholdBreached(int id, byte curRssi) {
2660        WifiRssiEventHandler handler = sWifiRssiEventHandler;
2661        if (handler != null) {
2662            handler.onRssiThresholdBreached(curRssi);
2663        }
2664    }
2665
2666    private native static int startRssiMonitoringNative(int iface, int id,
2667                                        byte maxRssi, byte minRssi);
2668
2669    private static int sRssiMonitorCmdId = 0;
2670
2671    public int startRssiMonitoring(byte maxRssi, byte minRssi,
2672                                                WifiRssiEventHandler rssiEventHandler) {
2673        Log.d(TAG, "startRssiMonitoring: maxRssi=" + maxRssi + " minRssi=" + minRssi);
2674        synchronized (mLock) {
2675            sWifiRssiEventHandler = rssiEventHandler;
2676            if (isHalStarted()) {
2677                if (sRssiMonitorCmdId != 0) {
2678                    stopRssiMonitoring();
2679                }
2680
2681                sRssiMonitorCmdId = getNewCmdIdLocked();
2682                Log.d(TAG, "sRssiMonitorCmdId = " + sRssiMonitorCmdId);
2683                int ret = startRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId,
2684                        maxRssi, minRssi);
2685                if (ret != 0) { // if not success
2686                    sRssiMonitorCmdId = 0;
2687                }
2688                return ret;
2689            } else {
2690                return -1;
2691            }
2692        }
2693    }
2694
2695    private native static int stopRssiMonitoringNative(int iface, int idx);
2696
2697    public int stopRssiMonitoring() {
2698        Log.d(TAG, "stopRssiMonitoring, cmdId " + sRssiMonitorCmdId);
2699        synchronized (mLock) {
2700            if (isHalStarted()) {
2701                int ret = 0;
2702                if (sRssiMonitorCmdId != 0) {
2703                    ret = stopRssiMonitoringNative(sWlan0Index, sRssiMonitorCmdId);
2704                }
2705                sRssiMonitorCmdId = 0;
2706                return ret;
2707            } else {
2708                return -1;
2709            }
2710        }
2711    }
2712}
2713