1 package android.net.wifi;
2 
3 import android.Manifest;
4 import android.annotation.NonNull;
5 import android.annotation.RequiresPermission;
6 import android.annotation.SuppressLint;
7 import android.annotation.SystemApi;
8 import android.annotation.SystemService;
9 import android.content.Context;
10 import android.content.pm.PackageManager;
11 import android.net.wifi.rtt.RangingRequest;
12 import android.net.wifi.rtt.RangingResult;
13 import android.net.wifi.rtt.RangingResultCallback;
14 import android.net.wifi.rtt.WifiRttManager;
15 import android.os.Parcel;
16 import android.os.Parcelable;
17 import android.os.SystemClock;
18 import android.util.Log;
19 
20 import com.android.internal.annotations.VisibleForTesting;
21 import com.android.internal.util.Protocol;
22 
23 import java.util.List;
24 
25 /** @hide */
26 @SystemApi
27 @Deprecated
28 @SystemService(Context.WIFI_RTT_SERVICE)
29 public class RttManager {
30 
31     private static final boolean DBG = false;
32     private static final String TAG = "RttManager";
33 
34     /** @deprecated It is Not supported anymore. */
35     @Deprecated
36     public static final int RTT_TYPE_UNSPECIFIED        = 0;
37 
38     public static final int RTT_TYPE_ONE_SIDED          = 1;
39     public static final int RTT_TYPE_TWO_SIDED          = 2;
40 
41     /** @deprecated It is not supported anymore. */
42     @Deprecated
43     public static final int RTT_TYPE_11_V               = 2;
44 
45     /** @deprecated It is not supported anymore. */
46     @Deprecated
47     public static final int RTT_TYPE_11_MC              = 4;
48 
49     /** @deprecated It is not supported anymore. */
50     @Deprecated
51     public static final int RTT_PEER_TYPE_UNSPECIFIED    = 0;
52 
53     public static final int RTT_PEER_TYPE_AP             = 1;
54     public static final int RTT_PEER_TYPE_STA            = 2;       /* requires NAN */
55     public static final int RTT_PEER_P2P_GO              = 3;
56     public static final int RTT_PEER_P2P_CLIENT          = 4;
57     public static final int RTT_PEER_NAN                 = 5;
58 
59     /**
60      * @deprecated It is not supported anymore.
61      * Use {@link android.net.wifi.RttManager#RTT_BW_20_SUPPORT} API.
62      */
63     @Deprecated
64     public static final int RTT_CHANNEL_WIDTH_20      = 0;
65 
66     /**
67      * @deprecated It is not supported anymore.
68      * Use {@link android.net.wifi.RttManager#RTT_BW_40_SUPPORT} API.
69      */
70     @Deprecated
71     public static final int RTT_CHANNEL_WIDTH_40      = 1;
72 
73     /**
74      * @deprecated It is not supported anymore.
75      * Use {@link android.net.wifi.RttManager#RTT_BW_80_SUPPORT} API.
76      */
77     @Deprecated
78     public static final int RTT_CHANNEL_WIDTH_80      = 2;
79 
80     /**@deprecated It is not supported anymore.
81      * Use {@link android.net.wifi.RttManager#RTT_BW_160_SUPPORT} API.
82      */
83     @Deprecated
84     public static final int RTT_CHANNEL_WIDTH_160     = 3;
85 
86     /**@deprecated not supported anymore*/
87     @Deprecated
88     public static final int RTT_CHANNEL_WIDTH_80P80   = 4;
89 
90     /**@deprecated It is not supported anymore.
91      * Use {@link android.net.wifi.RttManager#RTT_BW_5_SUPPORT} API.
92      */
93     @Deprecated
94     public static final int RTT_CHANNEL_WIDTH_5       = 5;
95 
96     /**@deprecated It is not supported anymore.
97      * Use {@link android.net.wifi.RttManager#RTT_BW_10_SUPPORT} API.
98      */
99     @Deprecated
100     public static final int RTT_CHANNEL_WIDTH_10      = 6;
101 
102     /** @deprecated channel info must be specified. */
103     @Deprecated
104     public static final int RTT_CHANNEL_WIDTH_UNSPECIFIED = -1;
105 
106     public static final int RTT_STATUS_SUCCESS                  = 0;
107     /** General failure*/
108     public static final int RTT_STATUS_FAILURE                  = 1;
109     /** Destination does not respond to RTT request*/
110     public static final int RTT_STATUS_FAIL_NO_RSP              = 2;
111     /** RTT request is rejected by the destination. Double side RTT only*/
112     public static final int RTT_STATUS_FAIL_REJECTED            = 3;
113     /** */
114     public static final int RTT_STATUS_FAIL_NOT_SCHEDULED_YET   = 4;
115     /** Timing measurement timeout*/
116     public static final int RTT_STATUS_FAIL_TM_TIMEOUT          = 5;
117     /** Destination is on a different channel from the RTT Request*/
118     public static final int RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL  = 6;
119     /** This type of Ranging is not support by Hardware*/
120     public static final int RTT_STATUS_FAIL_NO_CAPABILITY       = 7;
121     /** Request abort fro uncertain reason*/
122     public static final int RTT_STATUS_ABORTED                  = 8;
123     /** The T1-T4 or TOD/TOA Timestamp is illegal*/
124     public static final int RTT_STATUS_FAIL_INVALID_TS          = 9;
125     /** 11mc protocol level failed, eg, unrecognized FTMR/FTM frame*/
126     public static final int RTT_STATUS_FAIL_PROTOCOL            = 10;
127     /** Request can not be scheduled by hardware*/
128     public static final int RTT_STATUS_FAIL_SCHEDULE            = 11;
129     /** destination is busy now, you can try after a specified time from destination*/
130     public static final int RTT_STATUS_FAIL_BUSY_TRY_LATER      = 12;
131     /** Bad Request argument*/
132     public static final int RTT_STATUS_INVALID_REQ              = 13;
133     /** Wifi is not enabled*/
134     public static final int RTT_STATUS_NO_WIFI                  = 14;
135     /** Responder overrides param info, cannot range with new params 2-side RTT only*/
136     public static final int RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE  = 15;
137 
138     public static final int REASON_UNSPECIFIED              = -1;
139     public static final int REASON_NOT_AVAILABLE            = -2;
140     public static final int REASON_INVALID_LISTENER         = -3;
141     public static final int REASON_INVALID_REQUEST          = -4;
142     /** Do not have required permission */
143     public static final int REASON_PERMISSION_DENIED        = -5;
144     /** Ranging failed because responder role is enabled in STA mode.*/
145     public static final int
146             REASON_INITIATOR_NOT_ALLOWED_WHEN_RESPONDER_ON  = -6;
147 
148     public static final String DESCRIPTION_KEY  = "android.net.wifi.RttManager.Description";
149 
150     /**
151      * RTT BW supported bit mask, used as RTT param bandWidth too
152      */
153     public static final int RTT_BW_5_SUPPORT   = 0x01;
154     public static final int RTT_BW_10_SUPPORT  = 0x02;
155     public static final int RTT_BW_20_SUPPORT  = 0x04;
156     public static final int RTT_BW_40_SUPPORT  = 0x08;
157     public static final int RTT_BW_80_SUPPORT  = 0x10;
158     public static final int RTT_BW_160_SUPPORT = 0x20;
159 
160     /**
161      * RTT Preamble Support bit mask
162      */
163     public static final int PREAMBLE_LEGACY  = 0x01;
164     public static final int PREAMBLE_HT      = 0x02;
165     public static final int PREAMBLE_VHT     = 0x04;
166 
167     /** @deprecated Use the new {@link android.net.wifi.RttManager.RttCapabilities} API */
168     @Deprecated
169     public class Capabilities {
170         public int supportedType;
171         public int supportedPeerType;
172     }
173 
174     /** @deprecated Use the new {@link android.net.wifi.RttManager#getRttCapabilities()} API.*/
175     @Deprecated
176     @SuppressLint("Doclava125")
getCapabilities()177     public Capabilities getCapabilities() {
178         throw new UnsupportedOperationException(
179                 "getCapabilities is not supported in the adaptation layer");
180     }
181 
182     /**
183      * This class describe the RTT capability of the Hardware
184      */
185     @Deprecated
186     public static class RttCapabilities implements Parcelable {
187         /** @deprecated It is not supported*/
188         @Deprecated
189         public boolean supportedType;
190         /** @deprecated It is not supported*/
191         @Deprecated
192         public boolean supportedPeerType;
193         //1-sided rtt measurement is supported
194         public boolean oneSidedRttSupported;
195         //11mc 2-sided rtt measurement is supported
196         public boolean twoSided11McRttSupported;
197         //location configuration information supported
198         public boolean lciSupported;
199         //location civic records supported
200         public boolean lcrSupported;
201         //preamble supported, see bit mask definition above
202         public int preambleSupported;
203         //RTT bandwidth supported
204         public int bwSupported;
205         // Whether STA responder role is supported.
206         public boolean responderSupported;
207 
208         /** Whether the secure RTT protocol is supported. */
209         public boolean secureRttSupported;
210 
211         /** Draft 11mc version supported, including major and minor version. e.g, draft 4.3 is 43 */
212         public int mcVersion;
213 
214         @Override
toString()215         public String toString() {
216             StringBuffer sb = new StringBuffer();
217             sb.append("oneSidedRtt ").
218             append(oneSidedRttSupported ? "is Supported. " : "is not supported. ").
219             append("twoSided11McRtt ").
220             append(twoSided11McRttSupported ? "is Supported. " : "is not supported. ").
221             append("lci ").
222             append(lciSupported ? "is Supported. " : "is not supported. ").
223             append("lcr ").
224             append(lcrSupported ? "is Supported. " : "is not supported. ");
225 
226             if ((preambleSupported & PREAMBLE_LEGACY) != 0) {
227                 sb.append("Legacy ");
228             }
229 
230             if ((preambleSupported & PREAMBLE_HT) != 0) {
231                 sb.append("HT ");
232             }
233 
234             if ((preambleSupported & PREAMBLE_VHT) != 0) {
235                 sb.append("VHT ");
236             }
237 
238             sb.append("is supported. ");
239 
240             if ((bwSupported & RTT_BW_5_SUPPORT) != 0) {
241                 sb.append("5 MHz ");
242             }
243 
244             if ((bwSupported & RTT_BW_10_SUPPORT) != 0) {
245                 sb.append("10 MHz ");
246             }
247 
248             if ((bwSupported & RTT_BW_20_SUPPORT) != 0) {
249                 sb.append("20 MHz ");
250             }
251 
252             if ((bwSupported & RTT_BW_40_SUPPORT) != 0) {
253                 sb.append("40 MHz ");
254             }
255 
256             if ((bwSupported & RTT_BW_80_SUPPORT) != 0) {
257                 sb.append("80 MHz ");
258             }
259 
260             if ((bwSupported & RTT_BW_160_SUPPORT) != 0) {
261                 sb.append("160 MHz ");
262             }
263 
264             sb.append("is supported.");
265 
266             sb.append(" STA responder role is ")
267                     .append(responderSupported ? "supported" : "not supported");
268             sb.append(" Secure RTT protocol is ")
269                     .append(secureRttSupported ? "supported" : "not supported");
270             sb.append(" 11mc version is " + mcVersion);
271 
272             return sb.toString();
273         }
274         /** Implement the Parcelable interface {@hide} */
275         @Override
describeContents()276         public int describeContents() {
277             return 0;
278         }
279 
280         /** Implement the Parcelable interface {@hide} */
281         @Override
writeToParcel(Parcel dest, int flags)282         public void writeToParcel(Parcel dest, int flags) {
283             dest.writeInt(oneSidedRttSupported ? 1 : 0);
284             dest.writeInt(twoSided11McRttSupported ? 1 : 0);
285             dest.writeInt(lciSupported ? 1 : 0);
286             dest.writeInt(lcrSupported ? 1 : 0);
287             dest.writeInt(preambleSupported);
288             dest.writeInt(bwSupported);
289             dest.writeInt(responderSupported ? 1 : 0);
290             dest.writeInt(secureRttSupported ? 1 : 0);
291             dest.writeInt(mcVersion);
292         }
293 
294         /** Implement the Parcelable interface {@hide} */
295         public static final @android.annotation.NonNull Creator<RttCapabilities> CREATOR =
296             new Creator<RttCapabilities>() {
297             @Override
298             public RttCapabilities createFromParcel(Parcel in) {
299                 RttCapabilities capabilities = new RttCapabilities();
300                 capabilities.oneSidedRttSupported = (in.readInt() == 1);
301                 capabilities.twoSided11McRttSupported = (in.readInt() == 1);
302                 capabilities.lciSupported = (in.readInt() == 1);
303                 capabilities.lcrSupported = (in.readInt() == 1);
304                 capabilities.preambleSupported = in.readInt();
305                 capabilities.bwSupported = in.readInt();
306                 capabilities.responderSupported = (in.readInt() == 1);
307                 capabilities.secureRttSupported = (in.readInt() == 1);
308                 capabilities.mcVersion = in.readInt();
309                 return capabilities;
310             }
311                 /** Implement the Parcelable interface {@hide} */
312                 @Override
313                 public RttCapabilities[] newArray(int size) {
314                     return new RttCapabilities[size];
315                 }
316              };
317     }
318 
319     /**
320      * This method is deprecated. Please use the {@link WifiRttManager} API.
321      */
322     @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
getRttCapabilities()323     public RttCapabilities getRttCapabilities() {
324         return mRttCapabilities;
325     }
326 
327     /** specifies parameters for RTT request */
328     @Deprecated
329     public static class RttParams {
330         /**
331          * type of destination device being ranged
332          * currently only support RTT_PEER_TYPE_AP
333          * Range:RTT_PEER_TYPE_xxxx Default value:RTT_PEER_TYPE_AP
334          */
335         public int deviceType;
336 
337         /**
338          * type of RTT measurement method. Need check scan result and RttCapabilities first
339          * Range: RTT_TYPE_ONE_SIDED or RTT_TYPE_TWO_SIDED
340          * Default value: RTT_TYPE_ONE_SIDED
341          */
342         public int requestType;
343 
344         /**
345          * Whether the secure RTT protocol needs to be used for ranging this peer device.
346          */
347         public boolean secure;
348 
349         /**
350          * mac address of the device being ranged
351          * Default value: null
352          */
353         public String bssid;
354 
355         /**
356          * The primary control channel over which the client is
357          * communicating with the AP.Same as ScanResult.frequency
358          * Default value: 0
359          */
360         public int frequency;
361 
362         /**
363          * channel width of the destination AP. Same as ScanResult.channelWidth
364          * Default value: 0
365          */
366         public int channelWidth;
367 
368         /**
369          * Not used if the AP bandwidth is 20 MHz
370          * If the AP use 40, 80 or 160 MHz, this is the center frequency
371          * if the AP use 80 + 80 MHz, this is the center frequency of the first segment
372          * same as ScanResult.centerFreq0
373          * Default value: 0
374          */
375          public int centerFreq0;
376 
377          /**
378           * Only used if the AP bandwidth is 80 + 80 MHz
379           * if the AP use 80 + 80 MHz, this is the center frequency of the second segment
380           * same as ScanResult.centerFreq1
381           * Default value: 0
382           */
383           public int centerFreq1;
384 
385         /**
386          * number of samples to be taken
387          * @deprecated Use the new {@link android.net.wifi.RttManager.RttParams#numSamplesPerBurst}
388          */
389         @Deprecated
390         public int num_samples;
391 
392         /**
393          * number of retries if a sample fails
394          * @deprecated
395          * Use {@link android.net.wifi.RttManager.RttParams#numRetriesPerMeasurementFrame} API.
396          */
397         @Deprecated
398         public int num_retries;
399 
400         /** Number of burst in exp , 2^x. 0 means single shot measurement, range 0-15
401          * Currently only single shot is supported
402          * Default value: 0
403          */
404         public int numberBurst;
405 
406         /**
407          * valid only if numberBurst > 1, interval between burst(100ms).
408          * Range : 0-31, 0--means no specific
409          * Default value: 0
410          */
411         public int interval;
412 
413         /**
414          * number of samples to be taken in one burst
415          * Range: 1-31
416          * Default value: 8
417          */
418         public int numSamplesPerBurst;
419 
420         /** number of retries for each measurement frame if a sample fails
421          *  Only used by single side RTT,
422          *  Range 0 - 3 Default value: 0
423          */
424         public int numRetriesPerMeasurementFrame;
425 
426         /**
427          * number of retries for FTMR frame (control frame) if it fails.
428          * Only used by 80211MC double side RTT
429          * Range: 0-3  Default Value : 0
430          */
431         public int numRetriesPerFTMR;
432 
433         /**
434          * Request LCI information, only available when choose double side RTT measurement
435          * need check RttCapabilties first.
436          * Default value: false
437          * */
438         public boolean LCIRequest;
439 
440         /**
441          * Request LCR information, only available when choose double side RTT measurement
442          * need check RttCapabilties first.
443          * Default value: false
444          * */
445         public boolean LCRRequest;
446 
447         /**
448          * Timeout for each burst, (250 * 2^x) us,
449          * Range 1-11 and 15. 15 means no control Default value: 15
450          * */
451         public int burstTimeout;
452 
453         /** preamble used for RTT measurement
454          *  Range: PREAMBLE_LEGACY, PREAMBLE_HT, PREAMBLE_VHT
455          *  Default value: PREAMBLE_HT
456          */
457         public int preamble;
458 
459         /** bandWidth used for RTT measurement.User need verify the highest BW the destination
460          * support (from scan result etc) before set this value. Wider channels result usually give
461          * better accuracy. However, the frame loss can increase too.
462          * should be one of RTT_BW_5_SUPPORT to RTT_BW_160_SUPPORT. However, need check
463          * RttCapabilities firstto verify HW support this bandwidth.
464          * Default value:RTT_BW_20_SUPPORT
465          */
466         public int bandwidth;
467 
RttParams()468         public RttParams() {
469             //provide initial value for RttParams
470             deviceType = RTT_PEER_TYPE_AP;
471             requestType = RTT_TYPE_ONE_SIDED;
472             numberBurst = 0;
473             numSamplesPerBurst = 8;
474             numRetriesPerMeasurementFrame  = 0;
475             numRetriesPerFTMR = 0;
476             burstTimeout = 15;
477             preamble = PREAMBLE_HT;
478             bandwidth = RTT_BW_20_SUPPORT;
479         }
480 
481         /**
482          * {@hide}
483          */
toString()484         public String toString() {
485             StringBuilder sb = new StringBuilder();
486             sb.append("deviceType=" + deviceType);
487             sb.append(", requestType=" + requestType);
488             sb.append(", secure=" + secure);
489             sb.append(", bssid=" + bssid);
490             sb.append(", frequency=" + frequency);
491             sb.append(", channelWidth=" + channelWidth);
492             sb.append(", centerFreq0=" + centerFreq0);
493             sb.append(", centerFreq1=" + centerFreq1);
494             sb.append(", num_samples=" + num_samples);
495             sb.append(", num_retries=" + num_retries);
496             sb.append(", numberBurst=" + numberBurst);
497             sb.append(", interval=" + interval);
498             sb.append(", numSamplesPerBurst=" + numSamplesPerBurst);
499             sb.append(", numRetriesPerMeasurementFrame=" + numRetriesPerMeasurementFrame);
500             sb.append(", numRetriesPerFTMR=" + numRetriesPerFTMR);
501             sb.append(", LCIRequest=" + LCIRequest);
502             sb.append(", LCRRequest=" + LCRRequest);
503             sb.append(", burstTimeout=" + burstTimeout);
504             sb.append(", preamble=" + preamble);
505             sb.append(", bandwidth=" + bandwidth);
506             return sb.toString();
507         }
508     }
509 
510     /** pseudo-private class used to parcel arguments */
511     @Deprecated
512     public static class ParcelableRttParams implements Parcelable {
513 
514         @NonNull
515         public RttParams mParams[];
516 
517         /**
518          * @hide
519          */
520         @VisibleForTesting
ParcelableRttParams(RttParams[] params)521         public ParcelableRttParams(RttParams[] params) {
522             mParams = (params == null ? new RttParams[0] : params);
523         }
524 
525         /** Implement the Parcelable interface {@hide} */
526         @Override
describeContents()527         public int describeContents() {
528             return 0;
529         }
530 
531         /** Implement the Parcelable interface {@hide} */
532         @Override
writeToParcel(Parcel dest, int flags)533         public void writeToParcel(Parcel dest, int flags) {
534             dest.writeInt(mParams.length);
535 
536             for (RttParams params : mParams) {
537                 dest.writeInt(params.deviceType);
538                 dest.writeInt(params.requestType);
539                 dest.writeByte(params.secure ? (byte) 1 : 0);
540                 dest.writeString(params.bssid);
541                 dest.writeInt(params.channelWidth);
542                 dest.writeInt(params.frequency);
543                 dest.writeInt(params.centerFreq0);
544                 dest.writeInt(params.centerFreq1);
545                 dest.writeInt(params.numberBurst);
546                 dest.writeInt(params.interval);
547                 dest.writeInt(params.numSamplesPerBurst);
548                 dest.writeInt(params.numRetriesPerMeasurementFrame);
549                 dest.writeInt(params.numRetriesPerFTMR);
550                 dest.writeInt(params.LCIRequest ? 1 : 0);
551                 dest.writeInt(params.LCRRequest ? 1 : 0);
552                 dest.writeInt(params.burstTimeout);
553                 dest.writeInt(params.preamble);
554                 dest.writeInt(params.bandwidth);
555             }
556         }
557 
558         /** Implement the Parcelable interface {@hide} */
559         public static final @android.annotation.NonNull Creator<ParcelableRttParams> CREATOR =
560                 new Creator<ParcelableRttParams>() {
561                     @Override
562                     public ParcelableRttParams createFromParcel(Parcel in) {
563 
564                         int num = in.readInt();
565                         RttParams params[] = new RttParams[num];
566                         for (int i = 0; i < num; i++) {
567                             params[i] = new RttParams();
568                             params[i].deviceType = in.readInt();
569                             params[i].requestType = in.readInt();
570                             params[i].secure = (in.readByte() != 0);
571                             params[i].bssid = in.readString();
572                             params[i].channelWidth = in.readInt();
573                             params[i].frequency = in.readInt();
574                             params[i].centerFreq0 = in.readInt();
575                             params[i].centerFreq1 = in.readInt();
576                             params[i].numberBurst = in.readInt();
577                             params[i].interval = in.readInt();
578                             params[i].numSamplesPerBurst = in.readInt();
579                             params[i].numRetriesPerMeasurementFrame = in.readInt();
580                             params[i].numRetriesPerFTMR = in.readInt();
581                             params[i].LCIRequest = (in.readInt() == 1);
582                             params[i].LCRRequest = (in.readInt() == 1);
583                             params[i].burstTimeout = in.readInt();
584                             params[i].preamble = in.readInt();
585                             params[i].bandwidth = in.readInt();
586                         }
587 
588                         ParcelableRttParams parcelableParams = new ParcelableRttParams(params);
589                         return parcelableParams;
590                     }
591 
592                     @Override
593                     public ParcelableRttParams[] newArray(int size) {
594                         return new ParcelableRttParams[size];
595                     }
596                 };
597     }
598 
599     @Deprecated
600     public static class WifiInformationElement {
601         /** Information Element ID 0xFF means element is invalid. */
602         public byte id;
603         public byte[] data;
604     }
605     /** specifies RTT results */
606     @Deprecated
607     public static class RttResult {
608         /** mac address of the device being ranged. */
609         public String bssid;
610 
611         /** # of burst for this measurement. */
612         public int burstNumber;
613 
614         /** total number of measurement frames attempted in this measurement. */
615         public int measurementFrameNumber;
616 
617         /** total successful number of measurement frames in this measurement. */
618         public int successMeasurementFrameNumber;
619 
620         /**
621          * Maximum number of frames per burst supported by peer. Two side RTT only
622          * Valid only if less than request
623          */
624         public int frameNumberPerBurstPeer;
625 
626         /** status of the request */
627         public int status;
628 
629         /**
630          * type of the request used
631          * @deprecated Use {@link android.net.wifi.RttManager.RttResult#measurementType}
632          */
633         @Deprecated
634         public int requestType;
635 
636         /** RTT measurement method type used, should be one of RTT_TYPE_ONE_SIDED or
637          *  RTT_TYPE_TWO_SIDED.
638          */
639         public int measurementType;
640 
641         /**
642          * only valid when status ==  RTT_STATUS_FAIL_BUSY_TRY_LATER
643          * please retry RTT measurement after this duration since peer indicate busy at ths moment
644          *  Unit S  Range:1-31
645          */
646         public int retryAfterDuration;
647 
648         /** timestamp of completion, in microsecond since boot. */
649         public long ts;
650 
651         /** average RSSI observed, unit of 0.5 dB. */
652         public int rssi;
653 
654         /**
655          * RSSI spread (i.e. max - min)
656          * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rssiSpread} API.
657          */
658         @Deprecated
659         public int rssi_spread;
660 
661         /**RSSI spread (i.e. max - min), unit of 0.5 dB. */
662         public int rssiSpread;
663 
664         /**
665          * average transmit rate
666          * @deprecated Use {@link android.net.wifi.RttManager.RttResult#txRate} API.
667          */
668         @Deprecated
669         public int tx_rate;
670 
671         /** average transmit rate. Unit (kbps). */
672         public int txRate;
673 
674         /** average receiving rate Unit (kbps). */
675         public int rxRate;
676 
677        /**
678         * average round trip time in nano second
679         * @deprecated  Use {@link android.net.wifi.RttManager.RttResult#rtt} API.
680         */
681         @Deprecated
682         public long rtt_ns;
683 
684         /** average round trip time in picoseconds. */
685         public long rtt;
686 
687         /**
688          * standard deviation observed in round trip time
689          * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rttStandardDeviation} API.
690          */
691         @Deprecated
692         public long rtt_sd_ns;
693 
694         /** standard deviation of RTT in picoseconds. */
695         public long rttStandardDeviation;
696 
697         /**
698          * spread (i.e. max - min) round trip time
699          * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rttSpread} API.
700          */
701         @Deprecated
702         public long rtt_spread_ns;
703 
704         /** spread (i.e. max - min) RTT in picoseconds. */
705         public long rttSpread;
706 
707         /**
708          * average distance in centimeter, computed based on rtt_ns
709          * @deprecated use {@link android.net.wifi.RttManager.RttResult#distance} API.
710          */
711         @Deprecated
712         public int distance_cm;
713 
714         /** average distance in cm, computed based on rtt. */
715         public int distance;
716 
717         /**
718          * standard deviation observed in distance
719          * @deprecated
720          * Use {@link .android.net.wifi.RttManager.RttResult#distanceStandardDeviation} API.
721          */
722         @Deprecated
723         public int distance_sd_cm;
724 
725         /** standard deviation observed in distance in cm. */
726         public int distanceStandardDeviation;
727 
728         /**
729          * spread (i.e. max - min) distance
730          * @deprecated Use {@link android.net.wifi.RttManager.RttResult#distanceSpread} API.
731          */
732         @Deprecated
733         public int distance_spread_cm;
734 
735         /** spread (i.e. max - min) distance in cm. */
736         public int distanceSpread;
737 
738         /** the duration of this measurement burst, unit ms. */
739         public int burstDuration;
740 
741         /** Burst number supported by peer after negotiation, 2side RTT only*/
742         public int negotiatedBurstNum;
743 
744         /** LCI information Element, only available for double side RTT. */
745         public WifiInformationElement LCI;
746 
747         /** LCR information Element, only available to double side RTT. */
748         public WifiInformationElement LCR;
749 
750         /**
751          * Whether the secure RTT protocol was used for ranging.
752          */
753         public boolean secure;
754     }
755 
756 
757     /** pseudo-private class used to parcel results. */
758     @Deprecated
759     public static class ParcelableRttResults implements Parcelable {
760 
761         public RttResult mResults[];
762 
ParcelableRttResults(RttResult[] results)763         public ParcelableRttResults(RttResult[] results) {
764             mResults = results;
765         }
766 
767         /**
768          * {@hide}
769          */
toString()770         public String toString() {
771             StringBuilder sb = new StringBuilder();
772             for (int i = 0; i < mResults.length; ++i) {
773                 sb.append("[" + i + "]: ");
774                 sb.append("bssid=" + mResults[i].bssid);
775                 sb.append(", burstNumber=" + mResults[i].burstNumber);
776                 sb.append(", measurementFrameNumber=" + mResults[i].measurementFrameNumber);
777                 sb.append(", successMeasurementFrameNumber="
778                         + mResults[i].successMeasurementFrameNumber);
779                 sb.append(", frameNumberPerBurstPeer=" + mResults[i].frameNumberPerBurstPeer);
780                 sb.append(", status=" + mResults[i].status);
781                 sb.append(", requestType=" + mResults[i].requestType);
782                 sb.append(", measurementType=" + mResults[i].measurementType);
783                 sb.append(", retryAfterDuration=" + mResults[i].retryAfterDuration);
784                 sb.append(", ts=" + mResults[i].ts);
785                 sb.append(", rssi=" + mResults[i].rssi);
786                 sb.append(", rssi_spread=" + mResults[i].rssi_spread);
787                 sb.append(", rssiSpread=" + mResults[i].rssiSpread);
788                 sb.append(", tx_rate=" + mResults[i].tx_rate);
789                 sb.append(", txRate=" + mResults[i].txRate);
790                 sb.append(", rxRate=" + mResults[i].rxRate);
791                 sb.append(", rtt_ns=" + mResults[i].rtt_ns);
792                 sb.append(", rtt=" + mResults[i].rtt);
793                 sb.append(", rtt_sd_ns=" + mResults[i].rtt_sd_ns);
794                 sb.append(", rttStandardDeviation=" + mResults[i].rttStandardDeviation);
795                 sb.append(", rtt_spread_ns=" + mResults[i].rtt_spread_ns);
796                 sb.append(", rttSpread=" + mResults[i].rttSpread);
797                 sb.append(", distance_cm=" + mResults[i].distance_cm);
798                 sb.append(", distance=" + mResults[i].distance);
799                 sb.append(", distance_sd_cm=" + mResults[i].distance_sd_cm);
800                 sb.append(", distanceStandardDeviation=" + mResults[i].distanceStandardDeviation);
801                 sb.append(", distance_spread_cm=" + mResults[i].distance_spread_cm);
802                 sb.append(", distanceSpread=" + mResults[i].distanceSpread);
803                 sb.append(", burstDuration=" + mResults[i].burstDuration);
804                 sb.append(", negotiatedBurstNum=" + mResults[i].negotiatedBurstNum);
805                 sb.append(", LCI=" + mResults[i].LCI);
806                 sb.append(", LCR=" + mResults[i].LCR);
807                 sb.append(", secure=" + mResults[i].secure);
808             }
809             return sb.toString();
810         }
811 
812         /** Implement the Parcelable interface {@hide} */
813         @Override
describeContents()814         public int describeContents() {
815             return 0;
816         }
817 
818         /** Implement the Parcelable interface {@hide} */
819         @Override
writeToParcel(Parcel dest, int flags)820         public void writeToParcel(Parcel dest, int flags) {
821             if (mResults != null) {
822                 dest.writeInt(mResults.length);
823                 for (RttResult result : mResults) {
824                     dest.writeString(result.bssid);
825                     dest.writeInt(result.burstNumber);
826                     dest.writeInt(result.measurementFrameNumber);
827                     dest.writeInt(result.successMeasurementFrameNumber);
828                     dest.writeInt(result.frameNumberPerBurstPeer);
829                     dest.writeInt(result.status);
830                     dest.writeInt(result.measurementType);
831                     dest.writeInt(result.retryAfterDuration);
832                     dest.writeLong(result.ts);
833                     dest.writeInt(result.rssi);
834                     dest.writeInt(result.rssiSpread);
835                     dest.writeInt(result.txRate);
836                     dest.writeLong(result.rtt);
837                     dest.writeLong(result.rttStandardDeviation);
838                     dest.writeLong(result.rttSpread);
839                     dest.writeInt(result.distance);
840                     dest.writeInt(result.distanceStandardDeviation);
841                     dest.writeInt(result.distanceSpread);
842                     dest.writeInt(result.burstDuration);
843                     dest.writeInt(result.negotiatedBurstNum);
844                     dest.writeByte(result.LCI.id);
845                     if (result.LCI.id != (byte) 0xFF) {
846                         dest.writeByte((byte)result.LCI.data.length);
847                         dest.writeByteArray(result.LCI.data);
848                     }
849                     dest.writeByte(result.LCR.id);
850                     if (result.LCR.id != (byte) 0xFF) {
851                         dest.writeByte((byte) result.LCR.data.length);
852                         dest.writeByteArray(result.LCR.data);
853                     }
854                     dest.writeByte(result.secure ? (byte) 1 : 0);
855                 }
856             } else {
857                 dest.writeInt(0);
858             }
859         }
860 
861         /** Implement the Parcelable interface {@hide} */
862         public static final @android.annotation.NonNull Creator<ParcelableRttResults> CREATOR =
863                 new Creator<ParcelableRttResults>() {
864                     @Override
865                     public ParcelableRttResults createFromParcel(Parcel in) {
866 
867                         int num = in.readInt();
868 
869                         if (num == 0) {
870                             return new ParcelableRttResults(null);
871                         }
872 
873                         RttResult results[] = new RttResult[num];
874                         for (int i = 0; i < num; i++) {
875                             results[i] = new RttResult();
876                             results[i].bssid = in.readString();
877                             results[i].burstNumber = in.readInt();
878                             results[i].measurementFrameNumber = in.readInt();
879                             results[i].successMeasurementFrameNumber = in.readInt();
880                             results[i].frameNumberPerBurstPeer = in.readInt();
881                             results[i].status = in.readInt();
882                             results[i].measurementType = in.readInt();
883                             results[i].retryAfterDuration = in.readInt();
884                             results[i].ts = in.readLong();
885                             results[i].rssi = in.readInt();
886                             results[i].rssiSpread = in.readInt();
887                             results[i].txRate = in.readInt();
888                             results[i].rtt = in.readLong();
889                             results[i].rttStandardDeviation = in.readLong();
890                             results[i].rttSpread = in.readLong();
891                             results[i].distance = in.readInt();
892                             results[i].distanceStandardDeviation = in.readInt();
893                             results[i].distanceSpread = in.readInt();
894                             results[i].burstDuration = in.readInt();
895                             results[i].negotiatedBurstNum = in.readInt();
896                             results[i].LCI = new WifiInformationElement();
897                             results[i].LCI.id = in.readByte();
898                             if (results[i].LCI.id != (byte) 0xFF) {
899                                 byte length = in.readByte();
900                                 results[i].LCI.data = new byte[length];
901                                 in.readByteArray(results[i].LCI.data);
902                             }
903                             results[i].LCR = new WifiInformationElement();
904                             results[i].LCR.id = in.readByte();
905                             if (results[i].LCR.id != (byte) 0xFF) {
906                                 byte length = in.readByte();
907                                 results[i].LCR.data = new byte[length];
908                                 in.readByteArray(results[i].LCR.data);
909                             }
910                             results[i].secure = (in.readByte() != 0);
911                         }
912 
913                         ParcelableRttResults parcelableResults = new ParcelableRttResults(results);
914                         return parcelableResults;
915                     }
916 
917                     @Override
918                     public ParcelableRttResults[] newArray(int size) {
919                         return new ParcelableRttResults[size];
920                     }
921                 };
922     }
923 
924     @Deprecated
925     public static interface RttListener {
onSuccess(RttResult[] results)926         public void onSuccess(RttResult[] results);
onFailure(int reason, String description)927         public void onFailure(int reason, String description);
onAborted()928         public void onAborted();
929     }
930 
931     /**
932      * Request to start an RTT ranging
933      * <p>
934      * This method is deprecated. Please use the
935      * {@link WifiRttManager#startRanging(RangingRequest, java.util.concurrent.Executor, RangingResultCallback)}
936      * API.
937      *
938      * @param params  -- RTT request Parameters
939      * @param listener -- Call back to inform RTT result
940      * @exception throw IllegalArgumentException when params are illegal
941      *            throw IllegalStateException when RttCapabilities do not exist
942      */
943     @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
startRanging(RttParams[] params, RttListener listener)944     public void startRanging(RttParams[] params, RttListener listener) {
945         Log.i(TAG, "Send RTT request to RTT Service");
946 
947         if (!mNewService.isAvailable()) {
948             listener.onFailure(REASON_NOT_AVAILABLE, "");
949             return;
950         }
951 
952         RangingRequest.Builder builder = new RangingRequest.Builder();
953         for (RttParams rttParams : params) {
954             if (rttParams.deviceType != RTT_PEER_TYPE_AP) {
955                 listener.onFailure(REASON_INVALID_REQUEST, "Only AP peers are supported");
956                 return;
957             }
958 
959             ScanResult reconstructed = new ScanResult();
960             reconstructed.BSSID = rttParams.bssid;
961             if (rttParams.requestType == RTT_TYPE_TWO_SIDED) {
962                 reconstructed.setFlag(ScanResult.FLAG_80211mc_RESPONDER);
963             }
964             reconstructed.channelWidth = rttParams.channelWidth;
965             reconstructed.frequency = rttParams.frequency;
966             reconstructed.centerFreq0 = rttParams.centerFreq0;
967             reconstructed.centerFreq1 = rttParams.centerFreq1;
968             builder.addResponder(
969                     android.net.wifi.rtt.ResponderConfig.fromScanResult(reconstructed));
970         }
971         try {
972             mNewService.startRanging(builder.build(),
973                     mContext.getMainExecutor(),
974                     new RangingResultCallback() {
975                 @Override
976                 public void onRangingFailure(int code) {
977                     int localCode = REASON_UNSPECIFIED;
978                     if (code == STATUS_CODE_FAIL_RTT_NOT_AVAILABLE) {
979                         localCode = REASON_NOT_AVAILABLE;
980                     }
981                     listener.onFailure(localCode, "");
982                 }
983 
984                 @Override
985                 public void onRangingResults(List<RangingResult> results) {
986                     RttResult[] legacyResults = new RttResult[results.size()];
987                     int i = 0;
988                     for (RangingResult result : results) {
989                         legacyResults[i] = new RttResult();
990                         legacyResults[i].status = result.getStatus();
991                         legacyResults[i].bssid = result.getMacAddress().toString();
992                         if (result.getStatus() == RangingResult.STATUS_SUCCESS) {
993                             legacyResults[i].distance = result.getDistanceMm() / 10;
994                             legacyResults[i].distanceStandardDeviation =
995                                     result.getDistanceStdDevMm() / 10;
996                             legacyResults[i].rssi = result.getRssi() * -2;
997                             legacyResults[i].ts = result.getRangingTimestampMillis() * 1000;
998                             legacyResults[i].measurementFrameNumber =
999                                     result.getNumAttemptedMeasurements();
1000                             legacyResults[i].successMeasurementFrameNumber =
1001                                     result.getNumSuccessfulMeasurements();
1002                         } else {
1003                             // just in case legacy API needed some relatively real timestamp
1004                             legacyResults[i].ts = SystemClock.elapsedRealtime() * 1000;
1005                         }
1006                         i++;
1007                     }
1008                     listener.onSuccess(legacyResults);
1009                 }
1010             });
1011         } catch (IllegalArgumentException e) {
1012             Log.e(TAG, "startRanging: invalid arguments - " + e);
1013             listener.onFailure(REASON_INVALID_REQUEST, e.getMessage());
1014         } catch (SecurityException e) {
1015             Log.e(TAG, "startRanging: security exception - " + e);
1016             listener.onFailure(REASON_PERMISSION_DENIED, e.getMessage());
1017         }
1018     }
1019 
1020     /**
1021      * This method is deprecated and performs no function. Please use the {@link WifiRttManager}
1022      * API.
1023      */
1024     @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
stopRanging(RttListener listener)1025     public void stopRanging(RttListener listener) {
1026         Log.e(TAG, "stopRanging: unsupported operation - nop");
1027     }
1028 
1029     /**
1030      * Callbacks for responder operations.
1031      * <p>
1032      * A {@link ResponderCallback} is the handle to the calling client. {@link RttManager} will keep
1033      * a reference to the callback for the entire period when responder is enabled. The same
1034      * callback as used in enabling responder needs to be passed for disabling responder.
1035      * The client can freely destroy or reuse the callback after {@link RttManager#disableResponder}
1036      * is called.
1037      */
1038     @Deprecated
1039     public abstract static class ResponderCallback {
1040         /** Callback when responder is enabled. */
onResponderEnabled(ResponderConfig config)1041         public abstract void onResponderEnabled(ResponderConfig config);
1042         /** Callback when enabling responder failed. */
onResponderEnableFailure(int reason)1043         public abstract void onResponderEnableFailure(int reason);
1044         // TODO: consider adding onResponderAborted once it's supported.
1045     }
1046 
1047     /**
1048      * Enable Wi-Fi RTT responder mode on the device. The enabling result will be delivered via
1049      * {@code callback}.
1050      * <p>
1051      * Note calling this method with the same callback when the responder is already enabled won't
1052      * change the responder state, a cached {@link ResponderConfig} from the last enabling will be
1053      * returned through the callback.
1054      * <p>
1055      * This method is deprecated and will throw an {@link UnsupportedOperationException}
1056      * exception. Please use the {@link WifiRttManager} API to perform a Wi-Fi Aware peer-to-peer
1057      * ranging.
1058      *
1059      * @param callback Callback for responder enabling/disabling result.
1060      * @throws IllegalArgumentException If {@code callback} is null.
1061      */
1062     @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
enableResponder(ResponderCallback callback)1063     public void enableResponder(ResponderCallback callback) {
1064         throw new UnsupportedOperationException(
1065                 "enableResponder is not supported in the adaptation layer");
1066     }
1067 
1068     /**
1069      * Disable Wi-Fi RTT responder mode on the device. The {@code callback} needs to be the
1070      * same one used in {@link #enableResponder(ResponderCallback)}.
1071      * <p>
1072      * Calling this method when responder isn't enabled won't have any effect. The callback can be
1073      * reused for enabling responder after this method is called.
1074      * <p>
1075      * This method is deprecated and will throw an {@link UnsupportedOperationException}
1076      * exception. Please use the {@link WifiRttManager} API to perform a Wi-Fi Aware peer-to-peer
1077      * ranging.
1078      *
1079      * @param callback The same callback used for enabling responder.
1080      * @throws IllegalArgumentException If {@code callback} is null.
1081      */
1082     @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
disableResponder(ResponderCallback callback)1083     public void disableResponder(ResponderCallback callback) {
1084         throw new UnsupportedOperationException(
1085                 "disableResponder is not supported in the adaptation layer");
1086     }
1087 
1088     /**
1089      * Configuration used for RTT responder mode. The configuration information can be used by a
1090      * peer device to range the responder.
1091      *
1092      * @see ScanResult
1093      */
1094     @Deprecated
1095     public static class ResponderConfig implements Parcelable {
1096 
1097         // TODO: make all fields final once we can get mac address from responder HAL APIs.
1098         /**
1099          * Wi-Fi mac address used for responder mode.
1100          */
1101         public String macAddress = "";
1102 
1103         /**
1104          * The primary 20 MHz frequency (in MHz) of the channel where responder is enabled.
1105          * @see ScanResult#frequency
1106          */
1107         public int frequency;
1108 
1109         /**
1110          * Center frequency of the channel where responder is enabled on. Only in use when channel
1111          * width is at least 40MHz.
1112          * @see ScanResult#centerFreq0
1113          */
1114         public int centerFreq0;
1115 
1116         /**
1117          * Center frequency of the second segment when channel width is 80 + 80 MHz.
1118          * @see ScanResult#centerFreq1
1119          */
1120         public int centerFreq1;
1121 
1122         /**
1123          * Width of the channel where responder is enabled on.
1124          * @see ScanResult#channelWidth
1125          */
1126         public int channelWidth;
1127 
1128         /**
1129          * Preamble supported by responder.
1130          */
1131         public int preamble;
1132 
1133         @Override
toString()1134         public String toString() {
1135             StringBuilder builder = new StringBuilder();
1136             builder.append("macAddress = ").append(macAddress)
1137                     .append(" frequency = ").append(frequency)
1138                     .append(" centerFreq0 = ").append(centerFreq0)
1139                     .append(" centerFreq1 = ").append(centerFreq1)
1140                     .append(" channelWidth = ").append(channelWidth)
1141                     .append(" preamble = ").append(preamble);
1142             return builder.toString();
1143         }
1144 
1145         @Override
describeContents()1146         public int describeContents() {
1147             return 0;
1148         }
1149 
1150         @Override
writeToParcel(Parcel dest, int flags)1151         public void writeToParcel(Parcel dest, int flags) {
1152             dest.writeString(macAddress);
1153             dest.writeInt(frequency);
1154             dest.writeInt(centerFreq0);
1155             dest.writeInt(centerFreq1);
1156             dest.writeInt(channelWidth);
1157             dest.writeInt(preamble);
1158         }
1159 
1160         /** Implement {@link Parcelable} interface */
1161         public static final @android.annotation.NonNull Parcelable.Creator<ResponderConfig> CREATOR =
1162                 new Parcelable.Creator<ResponderConfig>() {
1163             @Override
1164             public ResponderConfig createFromParcel(Parcel in) {
1165                 ResponderConfig config = new ResponderConfig();
1166                 config.macAddress = in.readString();
1167                 config.frequency = in.readInt();
1168                 config.centerFreq0 = in.readInt();
1169                 config.centerFreq1 = in.readInt();
1170                 config.channelWidth = in.readInt();
1171                 config.preamble = in.readInt();
1172                 return config;
1173             }
1174 
1175             @Override
1176             public ResponderConfig[] newArray(int size) {
1177                 return new ResponderConfig[size];
1178             }
1179         };
1180 
1181     }
1182 
1183     /* private methods */
1184     public static final int BASE = Protocol.BASE_WIFI_RTT_MANAGER;
1185 
1186     public static final int CMD_OP_START_RANGING        = BASE + 0;
1187     public static final int CMD_OP_STOP_RANGING         = BASE + 1;
1188     public static final int CMD_OP_FAILED               = BASE + 2;
1189     public static final int CMD_OP_SUCCEEDED            = BASE + 3;
1190     public static final int CMD_OP_ABORTED              = BASE + 4;
1191     public static final int CMD_OP_ENABLE_RESPONDER     = BASE + 5;
1192     public static final int CMD_OP_DISABLE_RESPONDER    = BASE + 6;
1193     public static final int
1194             CMD_OP_ENALBE_RESPONDER_SUCCEEDED           = BASE + 7;
1195     public static final int
1196             CMD_OP_ENALBE_RESPONDER_FAILED              = BASE + 8;
1197     /** @hide */
1198     public static final int CMD_OP_REG_BINDER           = BASE + 9;
1199 
1200     private final WifiRttManager mNewService;
1201     private final Context mContext;
1202     private RttCapabilities mRttCapabilities;
1203 
1204     /**
1205      * Create a new WifiScanner instance.
1206      * Applications will almost always want to use
1207      * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
1208      * the standard {@link android.content.Context#WIFI_RTT_SERVICE Context.WIFI_RTT_SERVICE}.
1209      * @param service the new WifiRttManager service
1210      *
1211      * @hide
1212      */
RttManager(Context context, WifiRttManager service)1213     public RttManager(Context context, WifiRttManager service) {
1214         mNewService = service;
1215         mContext = context;
1216 
1217         boolean rttSupported = context.getPackageManager().hasSystemFeature(
1218                 PackageManager.FEATURE_WIFI_RTT);
1219 
1220         mRttCapabilities = new RttCapabilities();
1221         mRttCapabilities.oneSidedRttSupported = rttSupported;
1222         mRttCapabilities.twoSided11McRttSupported = rttSupported;
1223         mRttCapabilities.lciSupported = false;
1224         mRttCapabilities.lcrSupported = false;
1225         mRttCapabilities.preambleSupported = PREAMBLE_HT | PREAMBLE_VHT;
1226         mRttCapabilities.bwSupported = RTT_BW_40_SUPPORT | RTT_BW_80_SUPPORT;
1227         mRttCapabilities.responderSupported = false;
1228         mRttCapabilities.secureRttSupported = false;
1229     }
1230 }
1231 
1232