Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 65c3d5b9 authored by Charlie Boutier's avatar Charlie Boutier Committed by Gerrit Code Review
Browse files

Merge changes Idefdf030,I3e48c7ca into main

* changes:
  BumbleBluetoothTests: refactor LeAdvertisingTest with new Spliterator.
  BumbleBluetoothTests: Enhance gRPC callbacks with Spliterator
parents 27dbfca6 c6850bea
Loading
Loading
Loading
Loading
+2 −19
Original line number Diff line number Diff line
@@ -30,14 +30,12 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;

import android.bluetooth.le.BluetoothLeScanner;
import android.content.Context;
import android.util.Log;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.runner.AndroidJUnit4;

import com.android.compatibility.common.util.AdoptShellPermissionsRule;

import io.grpc.stub.StreamObserver;

import org.junit.ClassRule;
import org.junit.Rule;
@@ -153,23 +151,8 @@ public class GattClientTest {
                        .setOwnAddressType(OwnAddressType.RANDOM)
                        .build();

        StreamObserver<AdvertiseResponse> responseObserver =
                new StreamObserver<>() {
                    @Override
                    public void onNext(AdvertiseResponse response) {
                        Log.i(TAG, "advertise observer: onNext");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "advertise observer: on error " + e);
                    }

                    @Override
                    public void onCompleted() {
                        Log.i(TAG, "advertise observer: on completed");
                    }
                };
        StreamObserverSpliterator<AdvertiseResponse> responseObserver =
                new StreamObserverSpliterator<>();

        mBumble.host().advertise(request, responseObserver);
    }
+29 −54
Original line number Diff line number Diff line
@@ -30,15 +30,14 @@ import androidx.test.core.app.ApplicationProvider;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;

import io.grpc.Context.CancellableContext;
import io.grpc.Deadline;
import io.grpc.stub.StreamObserver;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@@ -63,15 +62,39 @@ public class LeAdvertisingTest {

    @Test
    public void advertisingSet() throws Exception {
        ScanningResponse response =
                startAdvertising()
                        .thenCompose(advAddressPair -> scanWithBumble(advAddressPair))
                        .join();
        Pair<String, Integer> addressPair = startAdvertising().join();
        ScanningResponse response = scanWithBumble(addressPair);

        Log.i(TAG, "scan response: " + response);
        assertThat(response).isNotNull();
    }

    private ScanningResponse scanWithBumble(Pair<String, Integer> addressPair) {
        Log.d(TAG, "scanWithBumble");
        String address = addressPair.first;
        int addressType = addressPair.second;

        StreamObserverSpliterator<ScanningResponse> responseObserver =
                new StreamObserverSpliterator<>();
        Deadline deadline = Deadline.after(TIMEOUT_ADVERTISING_MS, TimeUnit.MILLISECONDS);
        mBumble.host()
                .withDeadline(deadline)
                .scan(ScanRequest.newBuilder().build(), responseObserver);
        Iterator<ScanningResponse> responseObserverIterator = responseObserver.iterator();
        while (true) {
            ScanningResponse scanningResponse = responseObserverIterator.next();
            String addr =
                    Utils.addressStringFromByteString(
                            addressType == AdvertisingSetParameters.ADDRESS_TYPE_PUBLIC
                                    ? scanningResponse.getPublic()
                                    : scanningResponse.getRandom());

            if (addr.equals(address)) {
                return scanningResponse;
            }
        }
    }

    private CompletableFuture<Pair<String, Integer>> startAdvertising() {
        CompletableFuture<Pair<String, Integer>> future =
                new CompletableFuture<Pair<String, Integer>>();
@@ -134,52 +157,4 @@ public class LeAdvertisingTest {

        return future;
    }

    private CompletableFuture<ScanningResponse> scanWithBumble(Pair<String, Integer> addressPair) {
        final CompletableFuture<ScanningResponse> future =
                new CompletableFuture<ScanningResponse>();
        CancellableContext withCancellation = io.grpc.Context.current().withCancellation();

        String address = addressPair.first;
        int addressType = addressPair.second;

        ScanRequest request = ScanRequest.newBuilder().build();
        StreamObserver<ScanningResponse> responseObserver =
                new StreamObserver<ScanningResponse>() {
                    public void onNext(ScanningResponse response) {
                        String addr = "";
                        if (addressType == AdvertisingSetParameters.ADDRESS_TYPE_PUBLIC) {
                            addr = Utils.addressStringFromByteString(response.getPublic());
                        } else {
                            addr = Utils.addressStringFromByteString(response.getRandom());
                        }
                        Log.i(TAG, "scan observer: scan response address: " + addr);

                        if (addr.equals(address)) {
                            future.complete(response);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "scan observer: on error " + e);
                        future.completeExceptionally(e);
                    }

                    @Override
                    public void onCompleted() {
                        Log.i(TAG, "scan observer: on completed");
                        future.complete(null);
                    }
                };

        Deadline initialDeadline = Deadline.after(TIMEOUT_ADVERTISING_MS, TimeUnit.MILLISECONDS);
        withCancellation.run(
                () -> mBumble.host().withDeadline(initialDeadline).scan(request, responseObserver));

        return future.whenComplete(
                (input, exception) -> {
                    withCancellation.cancel(null);
                });
    }
}
+2 −18
Original line number Diff line number Diff line
@@ -30,7 +30,6 @@ import androidx.test.core.app.ApplicationProvider;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;

import io.grpc.stub.StreamObserver;

import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -146,23 +145,8 @@ public class LeScanningTest {
        AdvertiseRequest request =
                AdvertiseRequest.newBuilder().setLegacy(true).setData(dataType).build();

        StreamObserver<AdvertiseResponse> responseObserver =
                new StreamObserver<>() {
                    @Override
                    public void onNext(AdvertiseResponse response) {
                        Log.i(TAG, "advertise observer: onNext");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "advertise observer: on error " + e);
                    }

                    @Override
                    public void onCompleted() {
                        Log.i(TAG, "advertise observer: on completed");
                    }
                };
        StreamObserverSpliterator<AdvertiseResponse> responseObserver =
                new StreamObserverSpliterator<>();

        mBumble.host().advertise(request, responseObserver);
    }
+95 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.bluetooth;

import io.grpc.stub.StreamObserver;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;

public class StreamObserverSpliterator<T> implements Spliterator<T>, StreamObserver<T> {
    private BlockingQueue<Object> mQueue = new LinkedBlockingQueue<>();
    private static final Object COMPLETED_INDICATOR = new Object();

    /**
     * Creates and returns an iterator over the elements contained in the internal blocking queue.
     *
     * <p>The iterator is based on this class's Spliterator implementation. As elements are consumed
     * from the iterator, they are removed from the queue. The iterator continues to provide
     * elements as long as new items are added to the queue via the onNext method or until the
     * onCompleted method is called.
     *
     * <p>If the onError method was called previously and the corresponding Throwable is retrieved
     * by the iterator, it will throw a RuntimeException wrapping the original Throwable.
     *
     * @return an iterator over the elements contained in the internal blocking queue
     */
    public Iterator<T> iterator() {
        return Spliterators.iterator(this);
    }

    @Override
    public int characteristics() {
        return ORDERED | NONNULL;
    }

    @Override
    public long estimateSize() {
        return Long.MAX_VALUE;
    }

    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            Object item = mQueue.take();
            if (item == COMPLETED_INDICATOR) {
                return false;
            }
            if (item instanceof Throwable) {
                throw new RuntimeException((Throwable) item);
            }
            action.accept((T) item);
            return true;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Spliterator<T> trySplit() {
        return null;
    }

    @Override
    public void onNext(T value) {
        mQueue.add(value);
    }

    @Override
    public void onError(Throwable t) {
        mQueue.add(t);
    }

    @Override
    public void onCompleted() {
        mQueue.add(COMPLETED_INDICATOR);
    }
}