WifiNative.java revision d4762401ec14be6bdd2d27aff2478ddbf8d6ce2a
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.wifi; 18 19import android.net.wifi.BatchedScanSettings; 20import android.net.wifi.RttManager; 21import android.net.wifi.ScanResult; 22import android.net.wifi.WifiLinkLayerStats; 23import android.net.wifi.WifiManager; 24import android.net.wifi.WifiScanner; 25import android.net.wifi.WpsInfo; 26import android.net.wifi.p2p.WifiP2pConfig; 27import android.net.wifi.p2p.WifiP2pGroup; 28import android.net.wifi.p2p.nsd.WifiP2pServiceInfo; 29import android.os.SystemClock; 30import android.text.TextUtils; 31import android.util.LocalLog; 32import android.util.Log; 33 34import java.util.ArrayList; 35import java.util.List; 36import java.util.Locale; 37 38/** 39 * Native calls for bring up/shut down of the supplicant daemon and for 40 * sending requests to the supplicant daemon 41 * 42 * waitForEvent() is called on the monitor thread for events. All other methods 43 * must be serialized from the framework. 44 * 45 * {@hide} 46 */ 47public class WifiNative { 48 49 private static boolean DBG = false; 50 private final String mTAG; 51 private static final int DEFAULT_GROUP_OWNER_INTENT = 6; 52 53 static final int BLUETOOTH_COEXISTENCE_MODE_ENABLED = 0; 54 static final int BLUETOOTH_COEXISTENCE_MODE_DISABLED = 1; 55 static final int BLUETOOTH_COEXISTENCE_MODE_SENSE = 2; 56 57 static final int SCAN_WITHOUT_CONNECTION_SETUP = 1; 58 static final int SCAN_WITH_CONNECTION_SETUP = 2; 59 60 // Hold this lock before calling supplicant - it is required to 61 // mutually exclude access from Wifi and P2p state machines 62 static final Object mLock = new Object(); 63 64 public final String mInterfaceName; 65 public final String mInterfacePrefix; 66 67 private boolean mSuspendOptEnabled = false; 68 69 /* Register native functions */ 70 71 static { 72 /* Native functions are defined in libwifi-service.so */ 73 System.loadLibrary("wifi-service"); 74 registerNatives(); 75 } 76 77 private static native int registerNatives(); 78 79 public native static boolean loadDriver(); 80 81 public native static boolean isDriverLoaded(); 82 83 public native static boolean unloadDriver(); 84 85 public native static boolean startSupplicant(boolean p2pSupported); 86 87 /* Sends a kill signal to supplicant. To be used when we have lost connection 88 or when the supplicant is hung */ 89 public native static boolean killSupplicant(boolean p2pSupported); 90 91 private native boolean connectToSupplicantNative(); 92 93 private native void closeSupplicantConnectionNative(); 94 95 /** 96 * Wait for the supplicant to send an event, returning the event string. 97 * @return the event string sent by the supplicant. 98 */ 99 private native String waitForEventNative(); 100 101 private native boolean doBooleanCommandNative(String command); 102 103 private native int doIntCommandNative(String command); 104 105 private native String doStringCommandNative(String command); 106 107 public WifiNative(String interfaceName) { 108 mInterfaceName = interfaceName; 109 mTAG = "WifiNative-" + interfaceName; 110 if (!interfaceName.equals("p2p0")) { 111 mInterfacePrefix = "IFNAME=" + interfaceName + " "; 112 } else { 113 // commands for p2p0 interface don't need prefix 114 mInterfacePrefix = ""; 115 } 116 } 117 118 void enableVerboseLogging(int verbose) { 119 if (verbose > 0) { 120 DBG = true; 121 } else { 122 DBG = false; 123 } 124 } 125 126 private static final LocalLog mLocalLog = new LocalLog(1024); 127 128 // hold mLock before accessing mCmdIdLock 129 private static int sCmdId; 130 131 public LocalLog getLocalLog() { 132 return mLocalLog; 133 } 134 135 private static int getNewCmdIdLocked() { 136 return sCmdId++; 137 } 138 139 private void localLog(String s) { 140 if (mLocalLog != null) 141 mLocalLog.log(mInterfaceName + ": " + s); 142 } 143 144 public boolean connectToSupplicant() { 145 // No synchronization necessary .. it is implemented in WifiMonitor 146 localLog(mInterfacePrefix + "connectToSupplicant"); 147 return connectToSupplicantNative(); 148 } 149 150 public void closeSupplicantConnection() { 151 localLog(mInterfacePrefix + "closeSupplicantConnection"); 152 closeSupplicantConnectionNative(); 153 } 154 155 public String waitForEvent() { 156 // No synchronization necessary .. it is implemented in WifiMonitor 157 return waitForEventNative(); 158 } 159 160 private boolean doBooleanCommand(String command) { 161 if (DBG) Log.d(mTAG, "doBoolean: " + command); 162 synchronized (mLock) { 163 int cmdId = getNewCmdIdLocked(); 164 String toLog = Integer.toString(cmdId) + ":" + mInterfacePrefix + command; 165 boolean result = doBooleanCommandNative(mInterfacePrefix + command); 166 localLog(toLog + " -> " + result); 167 if (DBG) Log.d(mTAG, command + ": returned " + result); 168 return result; 169 } 170 } 171 172 private int doIntCommand(String command) { 173 if (DBG) Log.d(mTAG, "doInt: " + command); 174 synchronized (mLock) { 175 int cmdId = getNewCmdIdLocked(); 176 String toLog = Integer.toString(cmdId) + ":" + mInterfacePrefix + command; 177 int result = doIntCommandNative(mInterfacePrefix + command); 178 localLog(toLog + " -> " + result); 179 if (DBG) Log.d(mTAG, " returned " + result); 180 return result; 181 } 182 } 183 184 private String doStringCommand(String command) { 185 if (DBG) { 186 //GET_NETWORK commands flood the logs 187 if (!command.startsWith("GET_NETWORK")) { 188 Log.d(mTAG, "doString: [" + command + "]"); 189 } 190 } 191 synchronized (mLock) { 192 int cmdId = getNewCmdIdLocked(); 193 String toLog = Integer.toString(cmdId) + ":" + mInterfacePrefix + command; 194 String result = doStringCommandNative(mInterfacePrefix + command); 195 if (result == null) { 196 if (DBG) Log.d(mTAG, "doStringCommandNative no result"); 197 } else { 198 if (!command.startsWith("STATUS-")) { 199 localLog(toLog + " -> " + result); 200 } 201 if (DBG) Log.d(mTAG, " returned " + result.replace("\n", " ")); 202 } 203 return result; 204 } 205 } 206 207 private String doStringCommandWithoutLogging(String command) { 208 if (DBG) { 209 //GET_NETWORK commands flood the logs 210 if (!command.startsWith("GET_NETWORK")) { 211 Log.d(mTAG, "doString: [" + command + "]"); 212 } 213 } 214 synchronized (mLock) { 215 return doStringCommandNative(mInterfacePrefix + command); 216 } 217 } 218 219 public boolean ping() { 220 String pong = doStringCommand("PING"); 221 return (pong != null && pong.equals("PONG")); 222 } 223 224 public void setSupplicantLogLevel(String level) { 225 doStringCommand("LOG_LEVEL " + level); 226 } 227 228 public String getFreqCapability() { 229 return doStringCommand("GET_CAPABILITY freq"); 230 } 231 232 public boolean scan(int type, String freqList) { 233 if (type == SCAN_WITHOUT_CONNECTION_SETUP) { 234 if (freqList == null) return doBooleanCommand("SCAN TYPE=ONLY"); 235 else return doBooleanCommand("SCAN TYPE=ONLY freq=" + freqList); 236 } else if (type == SCAN_WITH_CONNECTION_SETUP) { 237 if (freqList == null) return doBooleanCommand("SCAN"); 238 else return doBooleanCommand("SCAN freq=" + freqList); 239 } else { 240 throw new IllegalArgumentException("Invalid scan type"); 241 } 242 } 243 244 /* Does a graceful shutdown of supplicant. Is a common stop function for both p2p and sta. 245 * 246 * Note that underneath we use a harsh-sounding "terminate" supplicant command 247 * for a graceful stop and a mild-sounding "stop" interface 248 * to kill the process 249 */ 250 public boolean stopSupplicant() { 251 return doBooleanCommand("TERMINATE"); 252 } 253 254 public String listNetworks() { 255 return doStringCommand("LIST_NETWORKS"); 256 } 257 258 public String listNetworks(int last_id) { 259 return doStringCommand("LIST_NETWORKS LAST_ID=" + last_id); 260 } 261 262 public int addNetwork() { 263 return doIntCommand("ADD_NETWORK"); 264 } 265 266 public boolean setNetworkVariable(int netId, String name, String value) { 267 if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) return false; 268 return doBooleanCommand("SET_NETWORK " + netId + " " + name + " " + value); 269 } 270 271 public String getNetworkVariable(int netId, String name) { 272 if (TextUtils.isEmpty(name)) return null; 273 274 // GET_NETWORK will likely flood the logs ... 275 return doStringCommandWithoutLogging("GET_NETWORK " + netId + " " + name); 276 } 277 278 public boolean removeNetwork(int netId) { 279 return doBooleanCommand("REMOVE_NETWORK " + netId); 280 } 281 282 283 private void logDbg(String debug) { 284 long now = SystemClock.elapsedRealtimeNanos(); 285 String ts = String.format("[%,d us] ", now/1000); 286 Log.e("WifiNative: ", ts+debug+ " stack:" 287 + Thread.currentThread().getStackTrace()[2].getMethodName() +" - " 288 + Thread.currentThread().getStackTrace()[3].getMethodName() +" - " 289 + Thread.currentThread().getStackTrace()[4].getMethodName() +" - " 290 + Thread.currentThread().getStackTrace()[5].getMethodName()+" - " 291 + Thread.currentThread().getStackTrace()[6].getMethodName()); 292 293 } 294 public boolean enableNetwork(int netId, boolean disableOthers) { 295 if (DBG) logDbg("enableNetwork nid=" + Integer.toString(netId) 296 + " disableOthers=" + disableOthers); 297 if (disableOthers) { 298 return doBooleanCommand("SELECT_NETWORK " + netId); 299 } else { 300 return doBooleanCommand("ENABLE_NETWORK " + netId); 301 } 302 } 303 304 public boolean disableNetwork(int netId) { 305 if (DBG) logDbg("disableNetwork nid=" + Integer.toString(netId)); 306 return doBooleanCommand("DISABLE_NETWORK " + netId); 307 } 308 309 public boolean reconnect() { 310 if (DBG) logDbg("RECONNECT "); 311 return doBooleanCommand("RECONNECT"); 312 } 313 314 public boolean reassociate() { 315 if (DBG) logDbg("REASSOCIATE "); 316 return doBooleanCommand("REASSOCIATE"); 317 } 318 319 public boolean disconnect() { 320 if (DBG) logDbg("DISCONNECT "); 321 return doBooleanCommand("DISCONNECT"); 322 } 323 324 public String status() { 325 return status(false); 326 } 327 328 public String status(boolean noEvents) { 329 if (noEvents) { 330 return doStringCommand("STATUS-NO_EVENTS"); 331 } else { 332 return doStringCommand("STATUS"); 333 } 334 } 335 336 public String getMacAddress() { 337 //Macaddr = XX.XX.XX.XX.XX.XX 338 String ret = doStringCommand("DRIVER MACADDR"); 339 if (!TextUtils.isEmpty(ret)) { 340 String[] tokens = ret.split(" = "); 341 if (tokens.length == 2) return tokens[1]; 342 } 343 return null; 344 } 345 346 /** 347 * Format of results: 348 * ================= 349 * id=1 350 * bssid=68:7f:74:d7:1b:6e 351 * freq=2412 352 * level=-43 353 * tsf=1344621975160944 354 * age=2623 355 * flags=[WPA2-PSK-CCMP][WPS][ESS] 356 * ssid=zubyb 357 * ==== 358 * 359 * RANGE=ALL gets all scan results 360 * RANGE=ID- gets results from ID 361 * MASK=<N> see wpa_supplicant/src/common/wpa_ctrl.h for details 362 */ 363 public String scanResults(int sid) { 364 return doStringCommandWithoutLogging("BSS RANGE=" + sid + "- MASK=0x21987"); 365 } 366 367 /** 368 * Format of result: 369 * id=1016 370 * bssid=00:03:7f:40:84:10 371 * freq=2462 372 * beacon_int=200 373 * capabilities=0x0431 374 * qual=0 375 * noise=0 376 * level=-46 377 * tsf=0000002669008476 378 * age=5 379 * ie=00105143412d485332302d52322d54455354010882848b960c12182403010b0706555... 380 * flags=[WPA2-EAP-CCMP][ESS][P2P][HS20] 381 * ssid=QCA-HS20-R2-TEST 382 * p2p_device_name= 383 * p2p_config_methods=0x0SET_NE 384 * anqp_venue_name=02083d656e6757692d466920416c6c69616e63650a3239383920436f... 385 * anqp_network_auth_type=010000 386 * anqp_roaming_consortium=03506f9a05001bc504bd 387 * anqp_ip_addr_type_availability=0c 388 * anqp_nai_realm=0200300000246d61696c2e6578616d706c652e636f6d3b636973636f2... 389 * anqp_3gpp=000600040132f465 390 * anqp_domain_name=0b65786d61706c652e636f6d 391 * hs20_operator_friendly_name=11656e6757692d466920416c6c69616e63650e636869... 392 * hs20_wan_metrics=01c40900008001000000000a00 393 * hs20_connection_capability=0100000006140001061600000650000106bb010106bb0... 394 * hs20_osu_providers_list=0b5143412d4f53552d425353010901310015656e6757692d... 395 */ 396 public String scanResult(String bssid) { 397 return doStringCommand("BSS " + bssid); 398 } 399 400 /** 401 * Format of command 402 * DRIVER WLS_BATCHING SET SCANFREQ=x MSCAN=r BESTN=y CHANNEL=<z, w, t> RTT=s 403 * where x is an ascii representation of an integer number of seconds between scans 404 * r is an ascii representation of an integer number of scans per batch 405 * y is an ascii representation of an integer number of the max AP to remember per scan 406 * z, w, t represent a 1..n size list of channel numbers and/or 'A', 'B' values 407 * indicating entire ranges of channels 408 * s is an ascii representation of an integer number of highest-strength AP 409 * for which we'd like approximate distance reported 410 * 411 * The return value is an ascii integer representing a guess of the number of scans 412 * the firmware can remember before it runs out of buffer space or -1 on error 413 */ 414 public String setBatchedScanSettings(BatchedScanSettings settings) { 415 if (settings == null) { 416 return doStringCommand("DRIVER WLS_BATCHING STOP"); 417 } 418 String cmd = "DRIVER WLS_BATCHING SET SCANFREQ=" + settings.scanIntervalSec; 419 cmd += " MSCAN=" + settings.maxScansPerBatch; 420 if (settings.maxApPerScan != BatchedScanSettings.UNSPECIFIED) { 421 cmd += " BESTN=" + settings.maxApPerScan; 422 } 423 if (settings.channelSet != null && !settings.channelSet.isEmpty()) { 424 cmd += " CHANNEL=<"; 425 int i = 0; 426 for (String channel : settings.channelSet) { 427 cmd += (i > 0 ? "," : "") + channel; 428 ++i; 429 } 430 cmd += ">"; 431 } 432 if (settings.maxApForDistance != BatchedScanSettings.UNSPECIFIED) { 433 cmd += " RTT=" + settings.maxApForDistance; 434 } 435 return doStringCommand(cmd); 436 } 437 438 public String getBatchedScanResults() { 439 return doStringCommand("DRIVER WLS_BATCHING GET"); 440 } 441 442 public boolean startDriver() { 443 return doBooleanCommand("DRIVER START"); 444 } 445 446 public boolean stopDriver() { 447 return doBooleanCommand("DRIVER STOP"); 448 } 449 450 451 /** 452 * Start filtering out Multicast V4 packets 453 * @return {@code true} if the operation succeeded, {@code false} otherwise 454 * 455 * Multicast filtering rules work as follows: 456 * 457 * The driver can filter multicast (v4 and/or v6) and broadcast packets when in 458 * a power optimized mode (typically when screen goes off). 459 * 460 * In order to prevent the driver from filtering the multicast/broadcast packets, we have to 461 * add a DRIVER RXFILTER-ADD rule followed by DRIVER RXFILTER-START to make the rule effective 462 * 463 * DRIVER RXFILTER-ADD Num 464 * where Num = 0 - Unicast, 1 - Broadcast, 2 - Mutil4 or 3 - Multi6 465 * 466 * and DRIVER RXFILTER-START 467 * In order to stop the usage of these rules, we do 468 * 469 * DRIVER RXFILTER-STOP 470 * DRIVER RXFILTER-REMOVE Num 471 * where Num is as described for RXFILTER-ADD 472 * 473 * The SETSUSPENDOPT driver command overrides the filtering rules 474 */ 475 public boolean startFilteringMulticastV4Packets() { 476 return doBooleanCommand("DRIVER RXFILTER-STOP") 477 && doBooleanCommand("DRIVER RXFILTER-REMOVE 2") 478 && doBooleanCommand("DRIVER RXFILTER-START"); 479 } 480 481 /** 482 * Stop filtering out Multicast V4 packets. 483 * @return {@code true} if the operation succeeded, {@code false} otherwise 484 */ 485 public boolean stopFilteringMulticastV4Packets() { 486 return doBooleanCommand("DRIVER RXFILTER-STOP") 487 && doBooleanCommand("DRIVER RXFILTER-ADD 2") 488 && doBooleanCommand("DRIVER RXFILTER-START"); 489 } 490 491 /** 492 * Start filtering out Multicast V6 packets 493 * @return {@code true} if the operation succeeded, {@code false} otherwise 494 */ 495 public boolean startFilteringMulticastV6Packets() { 496 return doBooleanCommand("DRIVER RXFILTER-STOP") 497 && doBooleanCommand("DRIVER RXFILTER-REMOVE 3") 498 && doBooleanCommand("DRIVER RXFILTER-START"); 499 } 500 501 /** 502 * Stop filtering out Multicast V6 packets. 503 * @return {@code true} if the operation succeeded, {@code false} otherwise 504 */ 505 public boolean stopFilteringMulticastV6Packets() { 506 return doBooleanCommand("DRIVER RXFILTER-STOP") 507 && doBooleanCommand("DRIVER RXFILTER-ADD 3") 508 && doBooleanCommand("DRIVER RXFILTER-START"); 509 } 510 511 /** 512 * Set the operational frequency band 513 * @param band One of 514 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO}, 515 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ}, 516 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ}, 517 * @return {@code true} if the operation succeeded, {@code false} otherwise 518 */ 519 public boolean setBand(int band) { 520 String bandstr; 521 522 if (band == WifiManager.WIFI_FREQUENCY_BAND_5GHZ) 523 bandstr = "5G"; 524 else if (band == WifiManager.WIFI_FREQUENCY_BAND_2GHZ) 525 bandstr = "2G"; 526 else 527 bandstr = "AUTO"; 528 return doBooleanCommand("SET SETBAND " + bandstr); 529 } 530 531 /** 532 * Sets the bluetooth coexistence mode. 533 * 534 * @param mode One of {@link #BLUETOOTH_COEXISTENCE_MODE_DISABLED}, 535 * {@link #BLUETOOTH_COEXISTENCE_MODE_ENABLED}, or 536 * {@link #BLUETOOTH_COEXISTENCE_MODE_SENSE}. 537 * @return Whether the mode was successfully set. 538 */ 539 public boolean setBluetoothCoexistenceMode(int mode) { 540 return doBooleanCommand("DRIVER BTCOEXMODE " + mode); 541 } 542 543 /** 544 * Enable or disable Bluetooth coexistence scan mode. When this mode is on, 545 * some of the low-level scan parameters used by the driver are changed to 546 * reduce interference with A2DP streaming. 547 * 548 * @param isSet whether to enable or disable this mode 549 * @return {@code true} if the command succeeded, {@code false} otherwise. 550 */ 551 public boolean setBluetoothCoexistenceScanMode(boolean setCoexScanMode) { 552 if (setCoexScanMode) { 553 return doBooleanCommand("DRIVER BTCOEXSCAN-START"); 554 } else { 555 return doBooleanCommand("DRIVER BTCOEXSCAN-STOP"); 556 } 557 } 558 559 public void enableSaveConfig() { 560 doBooleanCommand("SET update_config 1"); 561 } 562 563 public boolean saveConfig() { 564 return doBooleanCommand("SAVE_CONFIG"); 565 } 566 567 public boolean addToBlacklist(String bssid) { 568 if (TextUtils.isEmpty(bssid)) return false; 569 return doBooleanCommand("BLACKLIST " + bssid); 570 } 571 572 public boolean clearBlacklist() { 573 return doBooleanCommand("BLACKLIST clear"); 574 } 575 576 public boolean setSuspendOptimizations(boolean enabled) { 577 // if (mSuspendOptEnabled == enabled) return true; 578 mSuspendOptEnabled = enabled; 579 580 Log.e("native", "do suspend " + enabled); 581 if (enabled) { 582 return doBooleanCommand("DRIVER SETSUSPENDMODE 1"); 583 } else { 584 return doBooleanCommand("DRIVER SETSUSPENDMODE 0"); 585 } 586 } 587 588 public boolean setCountryCode(String countryCode) { 589 if (countryCode != null) 590 return doBooleanCommand("DRIVER COUNTRY " + countryCode.toUpperCase(Locale.ROOT)); 591 else 592 return doBooleanCommand("DRIVER COUNTRY"); 593 } 594 595 public void enableBackgroundScan(boolean enable) { 596 if (enable) { 597 doBooleanCommand("SET pno 1"); 598 } else { 599 doBooleanCommand("SET pno 0"); 600 } 601 } 602 603 public void enableAutoConnect(boolean enable) { 604 if (enable) { 605 doBooleanCommand("STA_AUTOCONNECT 1"); 606 } else { 607 doBooleanCommand("STA_AUTOCONNECT 0"); 608 } 609 } 610 611 public void setScanInterval(int scanInterval) { 612 doBooleanCommand("SCAN_INTERVAL " + scanInterval); 613 } 614 615 public void startTdls(String macAddr, boolean enable) { 616 if (enable) { 617 doBooleanCommand("TDLS_DISCOVER " + macAddr); 618 doBooleanCommand("TDLS_SETUP " + macAddr); 619 } else { 620 doBooleanCommand("TDLS_TEARDOWN " + macAddr); 621 } 622 } 623 624 /** Example output: 625 * RSSI=-65 626 * LINKSPEED=48 627 * NOISE=9999 628 * FREQUENCY=0 629 */ 630 public String signalPoll() { 631 return doStringCommandWithoutLogging("SIGNAL_POLL"); 632 } 633 634 /** Example outout: 635 * TXGOOD=396 636 * TXBAD=1 637 */ 638 public String pktcntPoll() { 639 return doStringCommand("PKTCNT_POLL"); 640 } 641 642 public void bssFlush() { 643 doBooleanCommand("BSS_FLUSH 0"); 644 } 645 646 public boolean startWpsPbc(String bssid) { 647 if (TextUtils.isEmpty(bssid)) { 648 return doBooleanCommand("WPS_PBC"); 649 } else { 650 return doBooleanCommand("WPS_PBC " + bssid); 651 } 652 } 653 654 public boolean startWpsPbc(String iface, String bssid) { 655 synchronized (mLock) { 656 if (TextUtils.isEmpty(bssid)) { 657 return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC"); 658 } else { 659 return doBooleanCommandNative("IFNAME=" + iface + " WPS_PBC " + bssid); 660 } 661 } 662 } 663 664 public boolean startWpsPinKeypad(String pin) { 665 if (TextUtils.isEmpty(pin)) return false; 666 return doBooleanCommand("WPS_PIN any " + pin); 667 } 668 669 public boolean startWpsPinKeypad(String iface, String pin) { 670 if (TextUtils.isEmpty(pin)) return false; 671 synchronized (mLock) { 672 return doBooleanCommandNative("IFNAME=" + iface + " WPS_PIN any " + pin); 673 } 674 } 675 676 677 public String startWpsPinDisplay(String bssid) { 678 if (TextUtils.isEmpty(bssid)) { 679 return doStringCommand("WPS_PIN any"); 680 } else { 681 return doStringCommand("WPS_PIN " + bssid); 682 } 683 } 684 685 public String startWpsPinDisplay(String iface, String bssid) { 686 synchronized (mLock) { 687 if (TextUtils.isEmpty(bssid)) { 688 return doStringCommandNative("IFNAME=" + iface + " WPS_PIN any"); 689 } else { 690 return doStringCommandNative("IFNAME=" + iface + " WPS_PIN " + bssid); 691 } 692 } 693 } 694 695 public boolean setExternalSim(boolean external) { 696 synchronized (mLock) { 697 String value = external ? "1" : "0"; 698 Log.d(TAG, "Setting external_sim to " + value); 699 return doBooleanCommand("SET external_sim " + value); 700 } 701 } 702 703 public boolean simAuthResponse(int id, String response) { 704 synchronized (mLock) { 705 return doBooleanCommand("CTRL-RSP-SIM-" + id + ":GSM-AUTH" + response); 706 } 707 } 708 709 /* Configures an access point connection */ 710 public boolean startWpsRegistrar(String bssid, String pin) { 711 if (TextUtils.isEmpty(bssid) || TextUtils.isEmpty(pin)) return false; 712 return doBooleanCommand("WPS_REG " + bssid + " " + pin); 713 } 714 715 public boolean cancelWps() { 716 return doBooleanCommand("WPS_CANCEL"); 717 } 718 719 public boolean setPersistentReconnect(boolean enabled) { 720 int value = (enabled == true) ? 1 : 0; 721 return doBooleanCommand("SET persistent_reconnect " + value); 722 } 723 724 public boolean setDeviceName(String name) { 725 return doBooleanCommand("SET device_name " + name); 726 } 727 728 public boolean setDeviceType(String type) { 729 return doBooleanCommand("SET device_type " + type); 730 } 731 732 public boolean setConfigMethods(String cfg) { 733 return doBooleanCommand("SET config_methods " + cfg); 734 } 735 736 public boolean setManufacturer(String value) { 737 return doBooleanCommand("SET manufacturer " + value); 738 } 739 740 public boolean setModelName(String value) { 741 return doBooleanCommand("SET model_name " + value); 742 } 743 744 public boolean setModelNumber(String value) { 745 return doBooleanCommand("SET model_number " + value); 746 } 747 748 public boolean setSerialNumber(String value) { 749 return doBooleanCommand("SET serial_number " + value); 750 } 751 752 public boolean setP2pSsidPostfix(String postfix) { 753 return doBooleanCommand("SET p2p_ssid_postfix " + postfix); 754 } 755 756 public boolean setP2pGroupIdle(String iface, int time) { 757 synchronized (mLock) { 758 return doBooleanCommandNative("IFNAME=" + iface + " SET p2p_group_idle " + time); 759 } 760 } 761 762 public void setPowerSave(boolean enabled) { 763 if (enabled) { 764 doBooleanCommand("SET ps 1"); 765 } else { 766 doBooleanCommand("SET ps 0"); 767 } 768 } 769 770 public boolean setP2pPowerSave(String iface, boolean enabled) { 771 synchronized (mLock) { 772 if (enabled) { 773 return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 1"); 774 } else { 775 return doBooleanCommandNative("IFNAME=" + iface + " P2P_SET ps 0"); 776 } 777 } 778 } 779 780 public boolean setWfdEnable(boolean enable) { 781 return doBooleanCommand("SET wifi_display " + (enable ? "1" : "0")); 782 } 783 784 public boolean setWfdDeviceInfo(String hex) { 785 return doBooleanCommand("WFD_SUBELEM_SET 0 " + hex); 786 } 787 788 /** 789 * "sta" prioritizes STA connection over P2P and "p2p" prioritizes 790 * P2P connection over STA 791 */ 792 public boolean setConcurrencyPriority(String s) { 793 return doBooleanCommand("P2P_SET conc_pref " + s); 794 } 795 796 public boolean p2pFind() { 797 return doBooleanCommand("P2P_FIND"); 798 } 799 800 public boolean p2pFind(int timeout) { 801 if (timeout <= 0) { 802 return p2pFind(); 803 } 804 return doBooleanCommand("P2P_FIND " + timeout); 805 } 806 807 public boolean p2pStopFind() { 808 return doBooleanCommand("P2P_STOP_FIND"); 809 } 810 811 public boolean p2pListen() { 812 return doBooleanCommand("P2P_LISTEN"); 813 } 814 815 public boolean p2pListen(int timeout) { 816 if (timeout <= 0) { 817 return p2pListen(); 818 } 819 return doBooleanCommand("P2P_LISTEN " + timeout); 820 } 821 822 public boolean p2pExtListen(boolean enable, int period, int interval) { 823 if (enable && interval < period) { 824 return false; 825 } 826 return doBooleanCommand("P2P_EXT_LISTEN" 827 + (enable ? (" " + period + " " + interval) : "")); 828 } 829 830 public boolean p2pSetChannel(int lc, int oc) { 831 if (DBG) Log.d(mTAG, "p2pSetChannel: lc="+lc+", oc="+oc); 832 833 if (lc >=1 && lc <= 11) { 834 if (!doBooleanCommand("P2P_SET listen_channel " + lc)) { 835 return false; 836 } 837 } else if (lc != 0) { 838 return false; 839 } 840 841 if (oc >= 1 && oc <= 165 ) { 842 int freq = (oc <= 14 ? 2407 : 5000) + oc * 5; 843 return doBooleanCommand("P2P_SET disallow_freq 1000-" 844 + (freq - 5) + "," + (freq + 5) + "-6000"); 845 } else if (oc == 0) { 846 /* oc==0 disables "P2P_SET disallow_freq" (enables all freqs) */ 847 return doBooleanCommand("P2P_SET disallow_freq \"\""); 848 } 849 850 return false; 851 } 852 853 public boolean p2pFlush() { 854 return doBooleanCommand("P2P_FLUSH"); 855 } 856 857 /* p2p_connect <peer device address> <pbc|pin|PIN#> [label|display|keypad] 858 [persistent] [join|auth] [go_intent=<0..15>] [freq=<in MHz>] */ 859 public String p2pConnect(WifiP2pConfig config, boolean joinExistingGroup) { 860 if (config == null) return null; 861 List<String> args = new ArrayList<String>(); 862 WpsInfo wps = config.wps; 863 args.add(config.deviceAddress); 864 865 switch (wps.setup) { 866 case WpsInfo.PBC: 867 args.add("pbc"); 868 break; 869 case WpsInfo.DISPLAY: 870 if (TextUtils.isEmpty(wps.pin)) { 871 args.add("pin"); 872 } else { 873 args.add(wps.pin); 874 } 875 args.add("display"); 876 break; 877 case WpsInfo.KEYPAD: 878 args.add(wps.pin); 879 args.add("keypad"); 880 break; 881 case WpsInfo.LABEL: 882 args.add(wps.pin); 883 args.add("label"); 884 default: 885 break; 886 } 887 888 if (config.netId == WifiP2pGroup.PERSISTENT_NET_ID) { 889 args.add("persistent"); 890 } 891 892 if (joinExistingGroup) { 893 args.add("join"); 894 } else { 895 //TODO: This can be adapted based on device plugged in state and 896 //device battery state 897 int groupOwnerIntent = config.groupOwnerIntent; 898 if (groupOwnerIntent < 0 || groupOwnerIntent > 15) { 899 groupOwnerIntent = DEFAULT_GROUP_OWNER_INTENT; 900 } 901 args.add("go_intent=" + groupOwnerIntent); 902 } 903 904 String command = "P2P_CONNECT "; 905 for (String s : args) command += s + " "; 906 907 return doStringCommand(command); 908 } 909 910 public boolean p2pCancelConnect() { 911 return doBooleanCommand("P2P_CANCEL"); 912 } 913 914 public boolean p2pProvisionDiscovery(WifiP2pConfig config) { 915 if (config == null) return false; 916 917 switch (config.wps.setup) { 918 case WpsInfo.PBC: 919 return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " pbc"); 920 case WpsInfo.DISPLAY: 921 //We are doing display, so provision discovery is keypad 922 return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " keypad"); 923 case WpsInfo.KEYPAD: 924 //We are doing keypad, so provision discovery is display 925 return doBooleanCommand("P2P_PROV_DISC " + config.deviceAddress + " display"); 926 default: 927 break; 928 } 929 return false; 930 } 931 932 public boolean p2pGroupAdd(boolean persistent) { 933 if (persistent) { 934 return doBooleanCommand("P2P_GROUP_ADD persistent"); 935 } 936 return doBooleanCommand("P2P_GROUP_ADD"); 937 } 938 939 public boolean p2pGroupAdd(int netId) { 940 return doBooleanCommand("P2P_GROUP_ADD persistent=" + netId); 941 } 942 943 public boolean p2pGroupRemove(String iface) { 944 if (TextUtils.isEmpty(iface)) return false; 945 synchronized (mLock) { 946 return doBooleanCommandNative("IFNAME=" + iface + " P2P_GROUP_REMOVE " + iface); 947 } 948 } 949 950 public boolean p2pReject(String deviceAddress) { 951 return doBooleanCommand("P2P_REJECT " + deviceAddress); 952 } 953 954 /* Invite a peer to a group */ 955 public boolean p2pInvite(WifiP2pGroup group, String deviceAddress) { 956 if (TextUtils.isEmpty(deviceAddress)) return false; 957 958 if (group == null) { 959 return doBooleanCommand("P2P_INVITE peer=" + deviceAddress); 960 } else { 961 return doBooleanCommand("P2P_INVITE group=" + group.getInterface() 962 + " peer=" + deviceAddress + " go_dev_addr=" + group.getOwner().deviceAddress); 963 } 964 } 965 966 /* Reinvoke a persistent connection */ 967 public boolean p2pReinvoke(int netId, String deviceAddress) { 968 if (TextUtils.isEmpty(deviceAddress) || netId < 0) return false; 969 970 return doBooleanCommand("P2P_INVITE persistent=" + netId + " peer=" + deviceAddress); 971 } 972 973 public String p2pGetSsid(String deviceAddress) { 974 return p2pGetParam(deviceAddress, "oper_ssid"); 975 } 976 977 public String p2pGetDeviceAddress() { 978 979 Log.d(TAG, "p2pGetDeviceAddress"); 980 981 String status = null; 982 983 /* Explicitly calling the API without IFNAME= prefix to take care of the devices that 984 don't have p2p0 interface. Supplicant seems to be returning the correct address anyway. */ 985 986 synchronized (mLock) { 987 status = doStringCommandNative("STATUS"); 988 } 989 990 String result = ""; 991 if (status != null) { 992 String[] tokens = status.split("\n"); 993 for (String token : tokens) { 994 if (token.startsWith("p2p_device_address=")) { 995 String[] nameValue = token.split("="); 996 if (nameValue.length != 2) 997 break; 998 result = nameValue[1]; 999 } 1000 } 1001 } 1002 1003 Log.d(TAG, "p2pGetDeviceAddress returning " + result); 1004 return result; 1005 } 1006 1007 public int getGroupCapability(String deviceAddress) { 1008 int gc = 0; 1009 if (TextUtils.isEmpty(deviceAddress)) return gc; 1010 String peerInfo = p2pPeer(deviceAddress); 1011 if (TextUtils.isEmpty(peerInfo)) return gc; 1012 1013 String[] tokens = peerInfo.split("\n"); 1014 for (String token : tokens) { 1015 if (token.startsWith("group_capab=")) { 1016 String[] nameValue = token.split("="); 1017 if (nameValue.length != 2) break; 1018 try { 1019 return Integer.decode(nameValue[1]); 1020 } catch(NumberFormatException e) { 1021 return gc; 1022 } 1023 } 1024 } 1025 return gc; 1026 } 1027 1028 public String p2pPeer(String deviceAddress) { 1029 return doStringCommand("P2P_PEER " + deviceAddress); 1030 } 1031 1032 private String p2pGetParam(String deviceAddress, String key) { 1033 if (deviceAddress == null) return null; 1034 1035 String peerInfo = p2pPeer(deviceAddress); 1036 if (peerInfo == null) return null; 1037 String[] tokens= peerInfo.split("\n"); 1038 1039 key += "="; 1040 for (String token : tokens) { 1041 if (token.startsWith(key)) { 1042 String[] nameValue = token.split("="); 1043 if (nameValue.length != 2) break; 1044 return nameValue[1]; 1045 } 1046 } 1047 return null; 1048 } 1049 1050 public boolean p2pServiceAdd(WifiP2pServiceInfo servInfo) { 1051 /* 1052 * P2P_SERVICE_ADD bonjour <query hexdump> <RDATA hexdump> 1053 * P2P_SERVICE_ADD upnp <version hex> <service> 1054 * 1055 * e.g) 1056 * [Bonjour] 1057 * # IP Printing over TCP (PTR) (RDATA=MyPrinter._ipp._tcp.local.) 1058 * P2P_SERVICE_ADD bonjour 045f697070c00c000c01 094d795072696e746572c027 1059 * # IP Printing over TCP (TXT) (RDATA=txtvers=1,pdl=application/postscript) 1060 * P2P_SERVICE_ADD bonjour 096d797072696e746572045f697070c00c001001 1061 * 09747874766572733d311a70646c3d6170706c69636174696f6e2f706f7374736372797074 1062 * 1063 * [UPnP] 1064 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012 1065 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice 1066 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp 1067 * -org:device:InternetGatewayDevice:1 1068 * P2P_SERVICE_ADD upnp 10 uuid:6859dede-8574-59ab-9322-123456789012::urn:schemas-upnp 1069 * -org:service:ContentDirectory:2 1070 */ 1071 for (String s : servInfo.getSupplicantQueryList()) { 1072 String command = "P2P_SERVICE_ADD"; 1073 command += (" " + s); 1074 if (!doBooleanCommand(command)) { 1075 return false; 1076 } 1077 } 1078 return true; 1079 } 1080 1081 public boolean p2pServiceDel(WifiP2pServiceInfo servInfo) { 1082 /* 1083 * P2P_SERVICE_DEL bonjour <query hexdump> 1084 * P2P_SERVICE_DEL upnp <version hex> <service> 1085 */ 1086 for (String s : servInfo.getSupplicantQueryList()) { 1087 String command = "P2P_SERVICE_DEL "; 1088 1089 String[] data = s.split(" "); 1090 if (data.length < 2) { 1091 return false; 1092 } 1093 if ("upnp".equals(data[0])) { 1094 command += s; 1095 } else if ("bonjour".equals(data[0])) { 1096 command += data[0]; 1097 command += (" " + data[1]); 1098 } else { 1099 return false; 1100 } 1101 if (!doBooleanCommand(command)) { 1102 return false; 1103 } 1104 } 1105 return true; 1106 } 1107 1108 public boolean p2pServiceFlush() { 1109 return doBooleanCommand("P2P_SERVICE_FLUSH"); 1110 } 1111 1112 public String p2pServDiscReq(String addr, String query) { 1113 String command = "P2P_SERV_DISC_REQ"; 1114 command += (" " + addr); 1115 command += (" " + query); 1116 1117 return doStringCommand(command); 1118 } 1119 1120 public boolean p2pServDiscCancelReq(String id) { 1121 return doBooleanCommand("P2P_SERV_DISC_CANCEL_REQ " + id); 1122 } 1123 1124 /* Set the current mode of miracast operation. 1125 * 0 = disabled 1126 * 1 = operating as source 1127 * 2 = operating as sink 1128 */ 1129 public void setMiracastMode(int mode) { 1130 // Note: optional feature on the driver. It is ok for this to fail. 1131 doBooleanCommand("DRIVER MIRACAST " + mode); 1132 } 1133 1134 public boolean fetchAnqp(String bssid, String subtypes) { 1135 return doBooleanCommand("ANQP_GET " + bssid + " " + subtypes); 1136 } 1137 1138 /* WIFI HAL support */ 1139 1140 private static final String TAG = "WifiNative-HAL"; 1141 private static long sWifiHalHandle = 0; /* used by JNI to save wifi_handle */ 1142 private static long[] sWifiIfaceHandles = null; /* used by JNI to save interface handles */ 1143 private static int sWlan0Index = -1; 1144 private static int sP2p0Index = -1; 1145 1146 private static boolean sHalIsStarted = false; 1147 private static boolean sHalFailed = false; 1148 1149 private static native boolean startHalNative(); 1150 private static native void stopHalNative(); 1151 private static native void waitForHalEventNative(); 1152 1153 private static class MonitorThread extends Thread { 1154 public void run() { 1155 Log.i(TAG, "Waiting for HAL events mWifiHalHandle=" + Long.toString(sWifiHalHandle)); 1156 waitForHalEventNative(); 1157 } 1158 } 1159 1160 synchronized public static boolean startHal() { 1161 Log.i(TAG, "startHal"); 1162 synchronized (mLock) { 1163 if (sHalFailed) 1164 return false; 1165 if (startHalNative() && (getInterfaces() != 0) && (sWlan0Index != -1)) { 1166 new MonitorThread().start(); 1167 sHalIsStarted = true; 1168 return true; 1169 } else { 1170 Log.i(TAG, "Could not start hal"); 1171 sHalIsStarted = false; 1172 sHalFailed = true; 1173 return false; 1174 } 1175 } 1176 } 1177 1178 synchronized public static void stopHal() { 1179 stopHalNative(); 1180 } 1181 1182 private static native int getInterfacesNative(); 1183 1184 synchronized public static int getInterfaces() { 1185 synchronized (mLock) { 1186 if (sWifiIfaceHandles == null) { 1187 int num = getInterfacesNative(); 1188 int wifi_num = 0; 1189 for (int i = 0; i < num; i++) { 1190 String name = getInterfaceNameNative(i); 1191 Log.i(TAG, "interface[" + i + "] = " + name); 1192 if (name.equals("wlan0")) { 1193 sWlan0Index = i; 1194 wifi_num++; 1195 } else if (name.equals("p2p0")) { 1196 sP2p0Index = i; 1197 wifi_num++; 1198 } 1199 } 1200 return wifi_num; 1201 } else { 1202 return sWifiIfaceHandles.length; 1203 } 1204 } 1205 } 1206 1207 private static native String getInterfaceNameNative(int index); 1208 synchronized public static String getInterfaceName(int index) { 1209 return getInterfaceNameNative(index); 1210 } 1211 1212 public static class ScanCapabilities { 1213 public int max_scan_cache_size; // in number of scan results?? 1214 public int max_scan_buckets; 1215 public int max_ap_cache_per_scan; 1216 public int max_rssi_sample_size; 1217 public int max_scan_reporting_threshold; // in number of scan results?? 1218 public int max_hotlist_aps; 1219 public int max_significant_wifi_change_aps; 1220 } 1221 1222 public static boolean getScanCapabilities(ScanCapabilities capabilities) { 1223 return getScanCapabilitiesNative(sWlan0Index, capabilities); 1224 } 1225 1226 private static native boolean getScanCapabilitiesNative( 1227 int iface, ScanCapabilities capabilities); 1228 1229 private static native boolean startScanNative(int iface, int id, ScanSettings settings); 1230 private static native boolean stopScanNative(int iface, int id); 1231 private static native WifiScanner.ScanData[] getScanResultsNative(int iface, boolean flush); 1232 private static native WifiLinkLayerStats getWifiLinkLayerStatsNative(int iface); 1233 1234 public static class ChannelSettings { 1235 int frequency; 1236 int dwell_time_ms; 1237 boolean passive; 1238 } 1239 1240 public static class BucketSettings { 1241 int bucket; 1242 int band; 1243 int period_ms; 1244 int report_events; 1245 int num_channels; 1246 ChannelSettings channels[]; 1247 } 1248 1249 public static class ScanSettings { 1250 int base_period_ms; 1251 int max_ap_per_scan; 1252 int report_threshold_percent; 1253 int report_threshold_num_scans; 1254 int num_buckets; 1255 BucketSettings buckets[]; 1256 } 1257 1258 public static interface ScanEventHandler { 1259 void onScanResultsAvailable(); 1260 void onFullScanResult(ScanResult fullScanResult); 1261 void onScanStatus(); 1262 void onScanPaused(WifiScanner.ScanData[] data); 1263 void onScanRestarted(); 1264 } 1265 1266 synchronized static void onScanResultsAvailable(int id) { 1267 if (sScanEventHandler != null) { 1268 sScanEventHandler.onScanResultsAvailable(); 1269 } 1270 } 1271 1272 /* scan status, keep these values in sync with gscan.h */ 1273 private static int WIFI_SCAN_BUFFER_FULL = 0; 1274 private static int WIFI_SCAN_COMPLETE = 1; 1275 1276 synchronized static void onScanStatus(int status) { 1277 Log.i(TAG, "Got a scan status changed event, status = " + status); 1278 1279 if (status == WIFI_SCAN_BUFFER_FULL) { 1280 /* we have a separate event to take care of this */ 1281 } else if (status == WIFI_SCAN_COMPLETE) { 1282 if (sScanEventHandler != null) { 1283 sScanEventHandler.onScanStatus(); 1284 } 1285 } 1286 } 1287 1288 synchronized static void onFullScanResult(int id, ScanResult result, byte bytes[]) { 1289 if (DBG) Log.i(TAG, "Got a full scan results event, ssid = " + result.SSID + ", " + 1290 "num = " + bytes.length); 1291 1292 if (sScanEventHandler == null) { 1293 return; 1294 } 1295 1296 int num = 0; 1297 for (int i = 0; i < bytes.length; ) { 1298 int type = bytes[i] & 0xFF; 1299 int len = bytes[i + 1] & 0xFF; 1300 1301 if (i + len + 2 > bytes.length) { 1302 Log.w(TAG, "bad length " + len + " of IE " + type + " from " + result.BSSID); 1303 Log.w(TAG, "ignoring the rest of the IEs"); 1304 break; 1305 } 1306 num++; 1307 i += len + 2; 1308 if (DBG) Log.i(TAG, "bytes[" + i + "] = [" + type + ", " + len + "]" + ", " + 1309 "next = " + i); 1310 } 1311 1312 ScanResult.InformationElement elements[] = new ScanResult.InformationElement[num]; 1313 for (int i = 0, index = 0; i < num; i++) { 1314 int type = bytes[index] & 0xFF; 1315 int len = bytes[index + 1] & 0xFF; 1316 if (DBG) Log.i(TAG, "index = " + index + ", type = " + type + ", len = " + len); 1317 ScanResult.InformationElement elem = new ScanResult.InformationElement(); 1318 elem.id = type; 1319 elem.bytes = new byte[len]; 1320 for (int j = 0; j < len; j++) { 1321 elem.bytes[j] = bytes[index + j + 2]; 1322 } 1323 elements[i] = elem; 1324 index += (len + 2); 1325 } 1326 1327 result.informationElements = elements; 1328 sScanEventHandler.onFullScanResult(result); 1329 } 1330 1331 private static int sScanCmdId = 0; 1332 private static ScanEventHandler sScanEventHandler; 1333 private static ScanSettings sScanSettings; 1334 1335 synchronized public static boolean startScan( 1336 ScanSettings settings, ScanEventHandler eventHandler) { 1337 synchronized (mLock) { 1338 1339 if (sScanCmdId != 0) { 1340 stopScan(); 1341 } else if (sScanSettings != null || sScanEventHandler != null) { 1342 /* current scan is paused; no need to stop it */ 1343 } 1344 1345 sScanCmdId = getNewCmdIdLocked(); 1346 1347 sScanSettings = settings; 1348 sScanEventHandler = eventHandler; 1349 1350 if (startScanNative(sWlan0Index, sScanCmdId, settings) == false) { 1351 sScanEventHandler = null; 1352 sScanSettings = null; 1353 sScanCmdId = 0; 1354 return false; 1355 } 1356 1357 return true; 1358 } 1359 } 1360 1361 synchronized public static void stopScan() { 1362 synchronized (mLock) { 1363 stopScanNative(sWlan0Index, sScanCmdId); 1364 sScanSettings = null; 1365 sScanEventHandler = null; 1366 sScanCmdId = 0; 1367 } 1368 } 1369 1370 synchronized public static void pauseScan() { 1371 synchronized (mLock) { 1372 if (sScanCmdId != 0 && sScanSettings != null && sScanEventHandler != null) { 1373 Log.d(TAG, "Pausing scan"); 1374 WifiScanner.ScanData scanData[] = getScanResultsNative(sWlan0Index, true); 1375 stopScanNative(sWlan0Index, sScanCmdId); 1376 sScanCmdId = 0; 1377 sScanEventHandler.onScanPaused(scanData); 1378 } 1379 } 1380 } 1381 1382 synchronized public static void restartScan() { 1383 synchronized (mLock) { 1384 if (sScanCmdId == 0 && sScanSettings != null && sScanEventHandler != null) { 1385 Log.d(TAG, "Restarting scan"); 1386 ScanEventHandler handler = sScanEventHandler; 1387 ScanSettings settings = sScanSettings; 1388 if (startScan(sScanSettings, sScanEventHandler)) { 1389 sScanEventHandler.onScanRestarted(); 1390 } else { 1391 /* we are still paused; don't change state */ 1392 sScanEventHandler = handler; 1393 sScanSettings = settings; 1394 } 1395 } 1396 } 1397 } 1398 1399 synchronized public static WifiScanner.ScanData[] getScanResults(boolean flush) { 1400 synchronized (mLock) { 1401 return getScanResultsNative(sWlan0Index, flush); 1402 } 1403 } 1404 1405 public static interface HotlistEventHandler { 1406 void onHotlistApFound (ScanResult[] result); 1407 void onHotlistApLost (ScanResult[] result); 1408 } 1409 1410 private static int sHotlistCmdId = 0; 1411 private static HotlistEventHandler sHotlistEventHandler; 1412 1413 private native static boolean setHotlistNative(int iface, int id, 1414 WifiScanner.HotlistSettings settings); 1415 private native static boolean resetHotlistNative(int iface, int id); 1416 1417 synchronized public static boolean setHotlist(WifiScanner.HotlistSettings settings, 1418 HotlistEventHandler eventHandler) { 1419 synchronized (mLock) { 1420 if (sHotlistCmdId != 0) { 1421 return false; 1422 } else { 1423 sHotlistCmdId = getNewCmdIdLocked(); 1424 } 1425 1426 sHotlistEventHandler = eventHandler; 1427 if (setHotlistNative(sWlan0Index, sScanCmdId, settings) == false) { 1428 sHotlistEventHandler = null; 1429 return false; 1430 } 1431 1432 return true; 1433 } 1434 } 1435 1436 synchronized public static void resetHotlist() { 1437 synchronized (mLock) { 1438 if (sHotlistCmdId != 0) { 1439 resetHotlistNative(sWlan0Index, sHotlistCmdId); 1440 sHotlistCmdId = 0; 1441 sHotlistEventHandler = null; 1442 } 1443 } 1444 } 1445 1446 synchronized public static void onHotlistApFound(int id, ScanResult[] results) { 1447 synchronized (mLock) { 1448 if (sHotlistCmdId != 0) { 1449 sHotlistEventHandler.onHotlistApFound(results); 1450 } else { 1451 /* this can happen because of race conditions */ 1452 Log.d(TAG, "Ignoring hotlist AP found event"); 1453 } 1454 } 1455 } 1456 1457 synchronized public static void onHotlistApLost(int id, ScanResult[] results) { 1458 synchronized (mLock) { 1459 if (sHotlistCmdId != 0) { 1460 sHotlistEventHandler.onHotlistApLost(results); 1461 } else { 1462 /* this can happen because of race conditions */ 1463 Log.d(TAG, "Ignoring hotlist AP lost event"); 1464 } 1465 } 1466 } 1467 1468 public static interface SignificantWifiChangeEventHandler { 1469 void onChangesFound(ScanResult[] result); 1470 } 1471 1472 private static SignificantWifiChangeEventHandler sSignificantWifiChangeHandler; 1473 private static int sSignificantWifiChangeCmdId; 1474 1475 private static native boolean trackSignificantWifiChangeNative( 1476 int iface, int id, WifiScanner.WifiChangeSettings settings); 1477 private static native boolean untrackSignificantWifiChangeNative(int iface, int id); 1478 1479 synchronized public static boolean trackSignificantWifiChange( 1480 WifiScanner.WifiChangeSettings settings, SignificantWifiChangeEventHandler handler) { 1481 synchronized (mLock) { 1482 if (sSignificantWifiChangeCmdId != 0) { 1483 return false; 1484 } else { 1485 sSignificantWifiChangeCmdId = getNewCmdIdLocked(); 1486 } 1487 1488 sSignificantWifiChangeHandler = handler; 1489 if (trackSignificantWifiChangeNative(sWlan0Index, sScanCmdId, settings) == false) { 1490 sSignificantWifiChangeHandler = null; 1491 return false; 1492 } 1493 1494 return true; 1495 } 1496 } 1497 1498 synchronized static void untrackSignificantWifiChange() { 1499 synchronized (mLock) { 1500 if (sSignificantWifiChangeCmdId != 0) { 1501 untrackSignificantWifiChangeNative(sWlan0Index, sSignificantWifiChangeCmdId); 1502 sSignificantWifiChangeCmdId = 0; 1503 sSignificantWifiChangeHandler = null; 1504 } 1505 } 1506 } 1507 1508 synchronized static void onSignificantWifiChange(int id, ScanResult[] results) { 1509 synchronized (mLock) { 1510 if (sSignificantWifiChangeCmdId != 0) { 1511 sSignificantWifiChangeHandler.onChangesFound(results); 1512 } else { 1513 /* this can happen because of race conditions */ 1514 Log.d(TAG, "Ignoring significant wifi change"); 1515 } 1516 } 1517 } 1518 1519 synchronized public static WifiLinkLayerStats getWifiLinkLayerStats(String iface) { 1520 // TODO: use correct iface name to Index translation 1521 if (iface == null) return null; 1522 synchronized (mLock) { 1523 if (!sHalIsStarted) 1524 startHal(); 1525 if (sHalIsStarted) 1526 return getWifiLinkLayerStatsNative(sWlan0Index); 1527 } 1528 return null; 1529 } 1530 1531 /* 1532 * NFC-related calls 1533 */ 1534 public String getNfcWpsConfigurationToken(int netId) { 1535 return doStringCommand("WPS_NFC_CONFIG_TOKEN WPS " + netId); 1536 } 1537 1538 public String getNfcHandoverRequest() { 1539 return doStringCommand("NFC_GET_HANDOVER_REQ NDEF P2P-CR"); 1540 } 1541 1542 public String getNfcHandoverSelect() { 1543 return doStringCommand("NFC_GET_HANDOVER_SEL NDEF P2P-CR"); 1544 } 1545 1546 public boolean initiatorReportNfcHandover(String selectMessage) { 1547 return doBooleanCommand("NFC_REPORT_HANDOVER INIT P2P 00 " + selectMessage); 1548 } 1549 1550 public boolean responderReportNfcHandover(String requestMessage) { 1551 return doBooleanCommand("NFC_REPORT_HANDOVER RESP P2P " + requestMessage + " 00"); 1552 } 1553 1554 public static native int getSupportedFeatureSetNative(int iface); 1555 synchronized public static int getSupportedFeatureSet() { 1556 return getSupportedFeatureSetNative(sWlan0Index); 1557 } 1558 1559 /* Rtt related commands/events */ 1560 public static interface RttEventHandler { 1561 void onRttResults(RttManager.RttResult[] result); 1562 } 1563 1564 private static RttEventHandler sRttEventHandler; 1565 private static int sRttCmdId; 1566 1567 synchronized private static void onRttResults(int id, RttManager.RttResult[] results) { 1568 if (id == sRttCmdId) { 1569 Log.d(TAG, "Received " + results.length + " rtt results"); 1570 sRttEventHandler.onRttResults(results); 1571 sRttCmdId = 0; 1572 } else { 1573 Log.d(TAG, "Received event for unknown cmd = " + id + ", current id = " + sRttCmdId); 1574 } 1575 } 1576 1577 private static native boolean requestRangeNative( 1578 int iface, int id, RttManager.RttParams[] params); 1579 private static native boolean cancelRangeRequestNative( 1580 int iface, int id, RttManager.RttParams[] params); 1581 1582 synchronized public static boolean requestRtt( 1583 RttManager.RttParams[] params, RttEventHandler handler) { 1584 synchronized (mLock) { 1585 if (sRttCmdId != 0) { 1586 return false; 1587 } else { 1588 sRttCmdId = getNewCmdIdLocked(); 1589 } 1590 sRttEventHandler = handler; 1591 return requestRangeNative(sWlan0Index, sRttCmdId, params); 1592 } 1593 } 1594 1595 synchronized public static boolean cancelRtt(RttManager.RttParams[] params) { 1596 synchronized(mLock) { 1597 if (sRttCmdId == 0) { 1598 return false; 1599 } 1600 1601 if (cancelRangeRequestNative(sWlan0Index, sRttCmdId, params)) { 1602 sRttEventHandler = null; 1603 return true; 1604 } else { 1605 return false; 1606 } 1607 } 1608 } 1609 1610 private static native boolean setScanningMacOuiNative(int iface, byte[] oui); 1611 1612 synchronized public static boolean setScanningMacOui(byte[] oui) { 1613 synchronized (mLock) { 1614 if (startHal()) { 1615 return setScanningMacOuiNative(sWlan0Index, oui); 1616 } else { 1617 return false; 1618 } 1619 } 1620 } 1621 1622 private static native int[] getChannelsForBandNative( 1623 int iface, int band); 1624 1625 synchronized public static int [] getChannelsForBand(int band) { 1626 synchronized (mLock) { 1627 if (startHal()) { 1628 return getChannelsForBandNative(sWlan0Index, band); 1629 } else { 1630 return null; 1631 } 1632 } 1633 } 1634 1635 1636 private static native boolean setDfsFlagNative(int iface, boolean dfsOn); 1637 synchronized public static boolean setDfsFlag(boolean dfsOn) { 1638 synchronized (mLock) { 1639 if (startHal()) { 1640 return setDfsFlagNative(sWlan0Index, dfsOn); 1641 } else { 1642 return false; 1643 } 1644 } 1645 } 1646 1647 private static native boolean toggleInterfaceNative(int on); 1648 synchronized public static boolean toggleInterface(int on) { 1649 synchronized (mLock) { 1650 if (startHal()) { 1651 return toggleInterfaceNative(0); 1652 } else { 1653 1654 return false; 1655 } 1656 } 1657 } 1658} 1659