下面列出了怎么用android.net.wifi.rtt.RangingResult的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onCreate() {
super.onCreate();
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiScanReceiver = new WifiScanReceiver();
mWifiRttManager = (WifiRttManager) getSystemService(Context.WIFI_RTT_RANGING_SERVICE);
mRttRangingResultCallback = new RttRangingResultCallback();
configuration = new Configuration(Configuration.CONFIGURATION_TYPE.TESTING_3);
//configuration = new Configuration(Configuration.CONFIGURATION_TYPE.TWO_DIMENSIONAL_2);
buildingMap = configuration.getConfiguration();
Collections.sort(buildingMap);
historicalDistances = new HashMap<String, ArrayList<RangingResult>>();
for (int i = 0; i < buildingMap.size(); i++)
{
historicalDistances.put(buildingMap.get(i).getBssid().toString(), new ArrayList<RangingResult>());
}
}
public Single<List<RangingResult>> startRanging(
@NonNull final ScanResult scanResult) {
return Single.create(emitter -> {
final RangingRequest request = new RangingRequest.Builder()
.addAccessPoint(scanResult)
.build();
final RangingResultCallback callback = new RangingResultCallback() {
@Override
public void onRangingFailure(final int i) {
emitter.onError(new RuntimeException("The WiFi-Ranging failed with error code: " + i));
}
@Override
public void onRangingResults(final List<RangingResult> list) {
emitter.onSuccess(list);
}
};
rttManager.startRanging(request, mainExecutor, callback);
});
}
private double weighted_average(List<RangingResult> rangingResults) {
// https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Variance_weights
double weighted_numerator = 0.0;
double weighted_demoninator = 0.0;
for (int i = 0; i < rangingResults.size(); i++)
{
weighted_numerator += (rangingResults.get(i).getDistanceMm() * (1.0 / (rangingResults.get(i).getDistanceStdDevMm() ^ 2)));
weighted_demoninator += (1.0 / (rangingResults.get(i).getDistanceStdDevMm() ^ 2));
}
return weighted_numerator / weighted_demoninator;
}
private String buildLogString(final RangingResult result) {
String resultString = getString(R.string.log, result.getRangingTimestampMillis(), result.getRssi(), result
.getDistanceMm(), logView.getText()
.toString());
if (resultString.length() > 5000) {
return resultString.substring(0, 5000);
}
return resultString;
}
private void writeOutput(@NonNull final List<RangingResult> result) {
if (result.isEmpty()) {
Timber.d("EMPTY ranging result received.");
return;
}
for (RangingResult res : result) {
logView.setText(buildLogString(res));
Timber.d("Result: %d RSSI: %d Distance: %d mm", res.getRangingTimestampMillis(), res.getRssi(), res
.getDistanceMm());
}
}
@Override
public void onRangingResults(@NonNull List<RangingResult> list) {
Log.d(TAG, "onRangingResults(): " + list);
// Because we are only requesting RangingResult for one access point (not multiple
// access points), this will only ever be one. (Use loops when requesting RangingResults
// for multiple access points.)
if (list.size() == 1) {
RangingResult rangingResult = list.get(0);
if (mMAC.equals(rangingResult.getMacAddress().toString())) {
if (rangingResult.getStatus() == RangingResult.STATUS_SUCCESS) {
mNumberOfSuccessfulRangeRequests++;
mRangeTextView.setText((rangingResult.getDistanceMm() / 1000f) + "");
addDistanceToHistory(rangingResult.getDistanceMm());
mRangeMeanTextView.setText((getDistanceMean() / 1000f) + "");
mRangeSDTextView.setText(
(rangingResult.getDistanceStdDevMm() / 1000f) + "");
addStandardDeviationOfDistanceToHistory(
rangingResult.getDistanceStdDevMm());
mRangeSDMeanTextView.setText(
(getStandardDeviationOfDistanceMean() / 1000f) + "");
mRssiTextView.setText(rangingResult.getRssi() + "");
mSuccessesInBurstTextView.setText(
rangingResult.getNumSuccessfulMeasurements()
+ "/"
+ rangingResult.getNumAttemptedMeasurements());
float successRatio =
((float) mNumberOfSuccessfulRangeRequests
/ (float) mNumberOfRangeRequests)
* 100;
mSuccessRatioTextView.setText(successRatio + "%");
mNumberOfRequestsTextView.setText(mNumberOfRangeRequests + "");
} else if (rangingResult.getStatus()
== RangingResult.STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC) {
Log.d(TAG, "RangingResult failed (AP doesn't support IEEE80211 MC.");
} else {
Log.d(TAG, "RangingResult failed.");
}
} else {
Toast.makeText(
getApplicationContext(),
R.string
.mac_mismatch_message_activity_access_point_ranging_results,
Toast.LENGTH_LONG)
.show();
}
}
queueNextRangingRequest();
}
@Override
public void onRangingResults(@NonNull List<RangingResult> rangingResultsList) {
Log.d(TAG, "onRangingResults(): " + rangingResultsList);
// Ensure we have more APs in the list of ranging results than were present in the configuration
if (rangingResultsList.size() >= configuration.getConfiguration().size()) {
// Sort the received ranging results by MAC address
// (order needs to match the order in the config, previously sorted by MAC address)
Collections.sort(rangingResultsList, new Comparator<RangingResult>() {
@Override
public int compare(RangingResult o1, RangingResult o2) {
return o1.getMacAddress().toString().compareTo(o2.getMacAddress().toString());
}
});
// Check that the received ranging results are valid and appropriate
List<RangingResult> rangingResultsOfInterest = new ArrayList<>();
rangingResultsOfInterest.clear();
for (int i = 0; i < rangingResultsList.size(); i++) {
RangingResult rangingResult = rangingResultsList.get(i);
if (!configuration.getMacAddresses().contains(rangingResult.getMacAddress().toString())) {
// The Mac address found is not in our configuration
showMessage("Unrecognised MAC address: " + rangingResult.getMacAddress().toString() + ", ignoring");
} else {
if (rangingResult.getStatus() == RangingResult.STATUS_SUCCESS) {
rangingResultsOfInterest.add(rangingResult);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
ResponderLocation responderLocation = rangingResultsList.get(0).getUnverifiedResponderLocation();
if (responderLocation == null)
Log.d(TAG, "ResponderLocation is null (not supported)");
else
Log.d(TAG, "ResponderLocation is " + responderLocation.toString());
}
} else if (rangingResult.getStatus() == RangingResult.STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC) {
showMessage("RangingResult failed (AP doesn't support IEEE80211 MC.");
} else {
showMessage("RangingResult failed. (" + rangingResult.getMacAddress().toString() + ")");
}
}
}
// rangingResultsOfInterest now contains the list of APs from whom we have received valid ranging results
// Check that every AP in our configuration returned a valid ranging result
// Potential enhancement: could remove any APs from the building map that we couldn't range to (need at least 2)
if (rangingResultsOfInterest.size() != configuration.getConfiguration().size())
{
showMessage("Could not find all the APs defined in the configuration to range off of");
if (!bStop)
queueNextRangingRequest();
return;
}
for (int i = 0; i < rangingResultsOfInterest.size(); i++)
{
ArrayList temp = historicalDistances.get(rangingResultsOfInterest.get(i).getMacAddress().toString());
temp.add(rangingResultsOfInterest.get(i));
if (temp.size() == Configuration.NUM_HISTORICAL_POINTS + 1)
temp.remove(0);
showMessage("Distance to " + rangingResultsOfInterest.get(i).getMacAddress().toString() +
" [Ave]: " + (int)weighted_average(historicalDistances.get(rangingResultsOfInterest.get(i).getMacAddress().toString())) + "mm");
showMessage("Distance to " + rangingResultsOfInterest.get(i).getMacAddress().toString() +
" : " + rangingResultsOfInterest.get(i).getMacAddress().toString() + "mm");
}
// historicalDistances now contains an arraylist of historic distances for each AP
// because of an earlier check, we know that every AP in the building map has an associated
// entry in the history of observed ranging results
// Create the positions and distances arrays required by the multilateration algorithm
double[][] positions = new double[buildingMap.size()][3]; // 3 dimensions
double[] distances = new double[buildingMap.size()];
for (int i = 0; i < buildingMap.size(); i++)
{
positions[i] = buildingMap.get(i).getPosition();
distances[i] = weighted_average(historicalDistances.get(rangingResultsOfInterest.get(i).getMacAddress().toString()));
}
try {
NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(new TrilaterationFunction(positions, distances), new LevenbergMarquardtOptimizer());
LeastSquaresOptimizer.Optimum optimum = solver.solve();
double[] centroid = optimum.getPoint().toArray();
Intent centroidIntent = new Intent(Constants.SERVICE_COMMS.LOCATION_COORDS);
centroidIntent.putExtra(Constants.SERVICE_COMMS.LOCATION_COORDS, centroid);
sendBroadcast(centroidIntent);
}
catch (Exception e)
{
showMessage("Error during trilateration: " + e.getMessage());
}
}
else
{
showMessage("Could not find enough Ranging Results");
}
if (!bStop)
queueNextRangingRequest();
}
@Override
public void onRangingResults(@NonNull List<RangingResult> list) {
Log.d(TAG, "onRangingResults(): " + list);
// Because we are only requesting RangingResult for one access point (not multiple
// access points), this will only ever be one. (Use loops when requesting RangingResults
// for multiple access points.)
if (list.size() == 1) {
RangingResult rangingResult = list.get(0);
if (mMAC.equals(rangingResult.getMacAddress().toString())) {
if (rangingResult.getStatus() == RangingResult.STATUS_SUCCESS) {
mNumberOfSuccessfulRangeRequests++;
mRangeTextView.setText((rangingResult.getDistanceMm() / 1000f) + "");
addDistanceToHistory(rangingResult.getDistanceMm());
mRangeMeanTextView.setText((getDistanceMean() / 1000f) + "");
mRangeSDTextView.setText(
(rangingResult.getDistanceStdDevMm() / 1000f) + "");
addStandardDeviationOfDistanceToHistory(
rangingResult.getDistanceStdDevMm());
mRangeSDMeanTextView.setText(
(getStandardDeviationOfDistanceMean() / 1000f) + "");
mRssiTextView.setText(rangingResult.getRssi() + "");
mSuccessesInBurstTextView.setText(
rangingResult.getNumSuccessfulMeasurements()
+ "/"
+ rangingResult.getNumAttemptedMeasurements());
float successRatio =
((float) mNumberOfSuccessfulRangeRequests
/ (float) mNumberOfRangeRequests)
* 100;
mSuccessRatioTextView.setText(successRatio + "%");
mNumberOfRequestsTextView.setText(mNumberOfRangeRequests + "");
} else if (rangingResult.getStatus()
== RangingResult.STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC) {
Log.d(TAG, "RangingResult failed (AP doesn't support IEEE80211 MC.");
} else {
Log.d(TAG, "RangingResult failed.");
}
} else {
Toast.makeText(
getApplicationContext(),
R.string
.mac_mismatch_message_activity_access_point_ranging_results,
Toast.LENGTH_LONG)
.show();
}
}
queueNextRangingRequest();
}