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