summaryrefslogtreecommitdiff
path: root/tests/tests/virtualdevice/src/android/virtualdevice/cts/sensor/VirtualSensorTest.java
blob: 005eab1e159fc318519f87019e283c9374cef482 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
/*
 * 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.virtualdevice.cts.sensor;

import static android.Manifest.permission.CREATE_VIRTUAL_DEVICE;
import static android.hardware.Sensor.TYPE_ACCELEROMETER;
import static android.hardware.SensorDirectChannel.RATE_NORMAL;
import static android.hardware.SensorDirectChannel.RATE_STOP;
import static android.hardware.SensorDirectChannel.TYPE_HARDWARE_BUFFER;
import static android.hardware.SensorDirectChannel.TYPE_MEMORY_FILE;

import static com.google.common.truth.Truth.assertThat;

import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import static java.util.concurrent.TimeUnit.MICROSECONDS;

import android.annotation.Nullable;
import android.companion.virtual.VirtualDeviceManager;
import android.companion.virtual.VirtualDeviceParams;
import android.companion.virtual.sensor.VirtualSensor;
import android.companion.virtual.sensor.VirtualSensorCallback;
import android.companion.virtual.sensor.VirtualSensorConfig;
import android.companion.virtual.sensor.VirtualSensorDirectChannelCallback;
import android.companion.virtual.sensor.VirtualSensorDirectChannelWriter;
import android.companion.virtual.sensor.VirtualSensorEvent;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.HardwareBuffer;
import android.hardware.Sensor;
import android.hardware.SensorDirectChannel;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.MemoryFile;
import android.os.SharedMemory;
import android.platform.test.annotations.AppModeFull;
import android.system.ErrnoException;
import android.virtualdevice.cts.common.FakeAssociationRule;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;

import com.android.compatibility.common.util.AdoptShellPermissionsRule;
import com.android.internal.os.BackgroundThread;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;

import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;


@RunWith(AndroidJUnit4.class)
@AppModeFull(reason = "VirtualDeviceManager cannot be accessed by instant apps")
public class VirtualSensorTest {

    private static final String VIRTUAL_SENSOR_NAME = "VirtualAccelerometer";
    private static final String VIRTUAL_SENSOR_VENDOR = "VirtualDeviceVendor";

    private static final int CUSTOM_SENSOR_TYPE = 9999;

    private static final int SENSOR_TIMEOUT_MILLIS = 1000;

    private static final int SENSOR_EVENT_SIZE = 104;
    private static final int SENSOR_EVENT_COUNT = 100;
    private static final int SHARED_MEMORY_SIZE = SENSOR_EVENT_COUNT * SENSOR_EVENT_SIZE;

    @Rule
    public AdoptShellPermissionsRule mAdoptShellPermissionsRule = new AdoptShellPermissionsRule(
            InstrumentationRegistry.getInstrumentation().getUiAutomation(),
            CREATE_VIRTUAL_DEVICE);

    @Rule
    public FakeAssociationRule mFakeAssociationRule = new FakeAssociationRule();

    private VirtualDeviceManager mVirtualDeviceManager;
    @Nullable
    private VirtualDeviceManager.VirtualDevice mVirtualDevice;

    private SensorManager mSensorManager;
    @Mock
    private SensorManager.DynamicSensorCallback mDynamicSensorCallback;

    private SensorManager mVirtualDeviceSensorManager;
    private VirtualSensor mVirtualSensor;
    private MemoryFile mMemoryFile;
    private SensorDirectChannel mDirectChannel;
    private VirtualSensorDirectChannelWriter mVirtualSensorDirectChannelWriter;
    @Mock
    private VirtualSensorCallback mVirtualSensorCallback;
    @Mock
    private VirtualSensorDirectChannelCallback mVirtualSensorDirectChannelCallback;
    private VirtualSensorEventListener mSensorEventListener = new VirtualSensorEventListener();

    // Listener for the default SensorManager used to ensure that there are real sensor events.
    private VirtualSensorEventListener mDefaultSensorEventListener =
            new VirtualSensorEventListener();

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        final PackageManager packageManager = context.getPackageManager();
        assumeTrue(packageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP));
        mSensorManager = context.getSystemService(SensorManager.class);

        mVirtualDeviceManager = context.getSystemService(VirtualDeviceManager.class);
    }

    private VirtualSensor setUpVirtualSensor(VirtualSensorConfig sensorConfig) {
        VirtualDeviceParams.Builder builder = new VirtualDeviceParams.Builder()
                .setDevicePolicy(VirtualDeviceParams.POLICY_TYPE_SENSORS,
                        VirtualDeviceParams.DEVICE_POLICY_CUSTOM);
        if (sensorConfig != null) {
            builder = builder
                    .addVirtualSensorConfig(sensorConfig)
                    .setVirtualSensorCallback(
                            BackgroundThread.getExecutor(), mVirtualSensorCallback);
            if (sensorConfig.getDirectChannelTypesSupported() > 0) {
                builder = builder.setVirtualSensorDirectChannelCallback(
                        BackgroundThread.getExecutor(), mVirtualSensorDirectChannelCallback);
            }
        }
        mVirtualDevice = mVirtualDeviceManager.createVirtualDevice(
                mFakeAssociationRule.getAssociationInfo().getId(), builder.build());
        Context deviceContext = InstrumentationRegistry.getInstrumentation().getContext()
                .createDeviceContext(mVirtualDevice.getDeviceId());
        mVirtualDeviceSensorManager = deviceContext.getSystemService(SensorManager.class);
        if (sensorConfig == null) {
            return null;
        } else {
            return mVirtualDevice.getVirtualSensorList().get(0);
        }
    }

    private void setUpDirectChannel() throws Exception {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME)
                        .setDirectChannelTypesSupported(TYPE_MEMORY_FILE)
                        .setHighestDirectReportRateLevel(RATE_NORMAL)
                        .build());

        mMemoryFile = new MemoryFile("Sensor Channel", SHARED_MEMORY_SIZE);
        mDirectChannel = mVirtualDeviceSensorManager.createDirectChannel(mMemoryFile);
    }

    @After
    public void tearDown() {
        mSensorManager.unregisterListener(mDefaultSensorEventListener);
        if (mVirtualDevice != null) {
            mVirtualDevice.close();
        }
        if (mMemoryFile != null) {
            mMemoryFile.close();
        }
        if (mDirectChannel != null) {
            mDirectChannel.close();
        }
    }

    @Test
    public void buildVirtualSensorConfig_hardwareBufferDirectChannel_throwsException() {
        assertThrows(
                IllegalArgumentException.class,
                () -> new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME)
                        .setDirectChannelTypesSupported(TYPE_HARDWARE_BUFFER | TYPE_MEMORY_FILE)
                        .build());
    }

    @Test
    public void getSensorList_noVirtualSensors_returnsEmptyList() {
        mVirtualSensor = setUpVirtualSensor(/* sensorConfig= */ null);
        assertThat(mVirtualSensor).isNull();
        assertThat(mVirtualDeviceSensorManager.getSensorList(TYPE_ACCELEROMETER)).isEmpty();
    }

    @Test
    public void getSensorList_returnsVirtualSensor() {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME)
                        .setVendor(VIRTUAL_SENSOR_VENDOR)
                        .setDirectChannelTypesSupported(TYPE_MEMORY_FILE)
                        .setHighestDirectReportRateLevel(RATE_NORMAL)
                        .setMaximumRange(1.2f)
                        .setResolution(3.4f)
                        .setPower(5.6f)
                        .setMinDelay(7)
                        .setMaxDelay(8)
                        .build());

        assertThat(mVirtualSensor.getType()).isEqualTo(TYPE_ACCELEROMETER);
        assertThat(mVirtualSensor.getName()).isEqualTo(VIRTUAL_SENSOR_NAME);
        assertThat(mVirtualSensor.getDeviceId()).isEqualTo(mVirtualDevice.getDeviceId());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        List<Sensor> sensors = mVirtualDeviceSensorManager.getSensorList(TYPE_ACCELEROMETER);
        Sensor defaultDeviceSensor = mSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);

        assertThat(sensors).containsExactly(sensor);
        assertThat(sensor).isNotEqualTo(defaultDeviceSensor);

        assertThat(sensor.getName()).isEqualTo(VIRTUAL_SENSOR_NAME);
        assertThat(sensor.getVendor()).isEqualTo(VIRTUAL_SENSOR_VENDOR);
        assertThat(sensor.getType()).isEqualTo(TYPE_ACCELEROMETER);
        assertThat(sensor.isDynamicSensor()).isFalse();
        assertThat(sensor.isDirectChannelTypeSupported(TYPE_MEMORY_FILE)).isTrue();
        assertThat(sensor.isDirectChannelTypeSupported(TYPE_HARDWARE_BUFFER)).isFalse();
        assertThat(sensor.getHighestDirectReportRateLevel()).isEqualTo(RATE_NORMAL);
        assertThat(sensor.getMaximumRange()).isEqualTo(1.2f);
        assertThat(sensor.getResolution()).isEqualTo(3.4f);
        assertThat(sensor.getPower()).isEqualTo(5.6f);
        assertThat(sensor.getMinDelay()).isEqualTo(7);
        assertThat(sensor.getMaxDelay()).isEqualTo(8);
        assertThat(sensor.getStringType()).isEqualTo(Sensor.STRING_TYPE_ACCELEROMETER);
        assertThat(sensor.getReportingMode()).isEqualTo(Sensor.REPORTING_MODE_CONTINUOUS);
    }

    @Test
    public void getSensorList_isCached() {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        final List<Sensor> allSensors = mVirtualDeviceSensorManager.getSensorList(Sensor.TYPE_ALL);
        assertThat(allSensors).isSameInstanceAs(
                mVirtualDeviceSensorManager.getSensorList(Sensor.TYPE_ALL));

        final List<Sensor> sensors = mVirtualDeviceSensorManager.getSensorList(TYPE_ACCELEROMETER);
        assertThat(sensors).isSameInstanceAs(
                mVirtualDeviceSensorManager.getSensorList(TYPE_ACCELEROMETER));
    }

    @Test
    public void createVirtualSensor_dynamicSensorCallback_notCalled() {
        mSensorManager.registerDynamicSensorCallback(mDynamicSensorCallback);

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        verify(mDynamicSensorCallback, after(SENSOR_TIMEOUT_MILLIS).never())
                .onDynamicSensorConnected(any());

        mSensorManager.unregisterDynamicSensorCallback(mDynamicSensorCallback);
    }

    @Test
    public void closeVirtualDevice_removesSensor() throws Exception {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());
        mVirtualDevice.close();
        mVirtualDevice = null;

        // The virtual device ID is no longer valid, SensorManager falls back to default device.
        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        Sensor defaultDeviceSensor = mSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);

        assertThat(sensor.getHandle()).isEqualTo(defaultDeviceSensor.getHandle());
        assertThat(sensor.getName()).isEqualTo(defaultDeviceSensor.getName());
    }

    @Test
    public void registerListener_triggersVirtualSensorCallback() {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);

        final int samplingPeriodMicros = 2345000;
        final int maxReportLatencyMicros = 678000;
        mVirtualDeviceSensorManager.registerListener(
                mSensorEventListener, sensor, samplingPeriodMicros, maxReportLatencyMicros);

        final Duration expectedSamplingPeriod =
                Duration.ofNanos(MICROSECONDS.toNanos(samplingPeriodMicros));
        final Duration expectedReportLatency =
                Duration.ofNanos(MICROSECONDS.toNanos(maxReportLatencyMicros));

        ArgumentCaptor<VirtualSensor> virtualSensor = ArgumentCaptor.forClass(VirtualSensor.class);
        verify(mVirtualSensorCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onConfigurationChanged(virtualSensor.capture(), eq(true),
                        eq(expectedSamplingPeriod), eq(expectedReportLatency));
        assertThat(virtualSensor.getValue().getHandle()).isEqualTo(mVirtualSensor.getHandle());

        mVirtualDeviceSensorManager.unregisterListener(mSensorEventListener);

        verify(mVirtualSensorCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onConfigurationChanged(virtualSensor.capture(), eq(false), any(Duration.class),
                        any(Duration.class));
        assertThat(virtualSensor.getValue().getHandle()).isEqualTo(mVirtualSensor.getHandle());

        verifyNoMoreInteractions(mVirtualSensorCallback);
    }

    @Test
    public void sendEvent_reachesRegisteredListeners() {
        assumeTrue(defaultAccelerometerEventsAreAvailable());

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);

        mVirtualDeviceSensorManager.registerListener(
                mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);

        final VirtualSensorEvent firstEvent =
                new VirtualSensorEvent.Builder(new float[] {0.1f, 2.3f, 4.5f}).build();
        mVirtualSensor.sendEvent(firstEvent);

        mSensorEventListener.assertReceivedSensorEvent(sensor, firstEvent);

        final VirtualSensorEvent secondEvent =
                new VirtualSensorEvent.Builder(new float[] {6.7f, 8.9f, 0.1f}).build();
        mVirtualSensor.sendEvent(secondEvent);

        mSensorEventListener.assertReceivedSensorEvent(sensor, secondEvent);

        mVirtualDeviceSensorManager.unregisterListener(mSensorEventListener);

        final VirtualSensorEvent thirdEvent =
                new VirtualSensorEvent.Builder(new float[] {2.3f, 4.5f, 6.7f}).build();
        mVirtualSensor.sendEvent(thirdEvent);

        mSensorEventListener.assertNoMoreEvents();
    }

    @Test
    public void sendEvent_explicitTimestampSpecified() {
        assumeTrue(defaultAccelerometerEventsAreAvailable());

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());
        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        mVirtualDeviceSensorManager.registerListener(
                mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);

        VirtualSensorEvent event =
                new VirtualSensorEvent.Builder(new float[] {0.1f, 2.3f, 4.5f})
                        .setTimestampNanos(System.nanoTime())
                        .build();
        mVirtualSensor.sendEvent(event);

        mSensorEventListener.assertReceivedSensorEvent(sensor, event);

        mVirtualDeviceSensorManager.unregisterListener(mSensorEventListener);

        mSensorEventListener.assertNoMoreEvents();
    }

    @Test
    public void sendEvent_invalidValues_eventIsDropped() {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);

        mVirtualDeviceSensorManager.registerListener(
                mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);

        final VirtualSensorEvent firstEvent =
                new VirtualSensorEvent.Builder(new float[] {0.1f}).build();
        mVirtualSensor.sendEvent(firstEvent);

        final VirtualSensorEvent secondEvent =
                new VirtualSensorEvent.Builder(new float[] {2.3f, 4.5f, 6.7f, 8.9f}).build();
        mVirtualSensor.sendEvent(secondEvent);

        final VirtualSensorEvent thirdEvent =
                new VirtualSensorEvent.Builder(new float[] {7.7f, 8.8f}).build();
        mVirtualSensor.sendEvent(thirdEvent);

        mSensorEventListener.assertNoMoreEvents();

        mVirtualDeviceSensorManager.unregisterListener(mSensorEventListener);
    }

    @Test
    public void virtualSensor_arbitrarySensorType() {
        assumeTrue(defaultAccelerometerEventsAreAvailable());

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(CUSTOM_SENSOR_TYPE, VIRTUAL_SENSOR_NAME).build());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(CUSTOM_SENSOR_TYPE);

        mVirtualDeviceSensorManager.registerListener(
                mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);

        float[] values = new float[16];
        Arrays.fill(values, 1.2f);

        final VirtualSensorEvent validEvent = new VirtualSensorEvent.Builder(values).build();
        mVirtualSensor.sendEvent(validEvent);

        mSensorEventListener.assertReceivedSensorEvent(sensor, validEvent);

        // Sensor events can have at most 16 values. Check that events with more values are dropped.
        float[] invalidValues = new float[17];
        Arrays.fill(values, 3.4f);
        final VirtualSensorEvent invalidEvent =
                new VirtualSensorEvent.Builder(invalidValues).build();
        mVirtualSensor.sendEvent(invalidEvent);

        mSensorEventListener.assertNoMoreEvents();

        mVirtualDeviceSensorManager.unregisterListener(mSensorEventListener);
    }

    @Test
    public void directConnection_memoryFile_notSupported() throws Exception {
        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        MemoryFile memoryFile = new MemoryFile("Sensor Channel", SHARED_MEMORY_SIZE);
        SensorDirectChannel channel = mVirtualDeviceSensorManager.createDirectChannel(memoryFile);

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        assertThat(channel.configure(sensor, RATE_NORMAL)).isEqualTo(0);
    }

    @Test
    public void directConnection_hardwareBuffer_throwsException() {
        // Skip this test if hardware buffer direct channel is generally not supported on the device
        assumeTrue(mSensorManager.getSensorList(Sensor.TYPE_ALL).stream().anyMatch(
                s -> s.isDirectChannelTypeSupported(TYPE_HARDWARE_BUFFER)));

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        HardwareBuffer hardwareBuffer = HardwareBuffer.create(
                /*width=*/SHARED_MEMORY_SIZE, /*height=*/1, HardwareBuffer.BLOB, /*layers=*/1,
                HardwareBuffer.USAGE_CPU_READ_OFTEN | HardwareBuffer.USAGE_GPU_DATA_BUFFER
                        | HardwareBuffer.USAGE_SENSOR_DIRECT_DATA);

        assertThrows(UncheckedIOException.class,
                () -> mVirtualDeviceSensorManager.createDirectChannel(hardwareBuffer));
    }

    @Test
    public void directConnection_memoryFile_onlyValidForVirtualDevice() throws Exception {
        setUpDirectChannel();

        // The channel is created for the virtual device ID, configuring it for a sensor of the
        // default device should not be allowed.
        Sensor defaultDeviceSensor = mSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        assertThat(mDirectChannel.configure(defaultDeviceSensor, RATE_NORMAL)).isEqualTo(0);
    }

    @Test
    public void directConnectionForDefaultDevice_memoryFile_notValidForVirtualDevice()
            throws Exception {
        // Skip this test if memory file direct channel is generally not supported on the device.
        assumeTrue(mSensorManager.getSensorList(Sensor.TYPE_ALL).stream().anyMatch(
                s -> s.isDirectChannelTypeSupported(TYPE_MEMORY_FILE)));

        MemoryFile memoryFile = new MemoryFile("Sensor Channel", SHARED_MEMORY_SIZE);
        SensorDirectChannel channel = mSensorManager.createDirectChannel(memoryFile);

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME)
                        .setDirectChannelTypesSupported(TYPE_MEMORY_FILE)
                        .setHighestDirectReportRateLevel(RATE_NORMAL)
                        .build());

        // The channel is created for the default device ID, configuring it for a sensor of the
        // virtual device should not be allowed.
        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        assertThat(channel.configure(sensor, RATE_NORMAL)).isEqualTo(0);
    }

    @Test
    public void directConnection_memoryFile_notValidForAnotherVirtualDevice() throws Exception {
        setUpDirectChannel();
        VirtualDeviceManager.VirtualDevice secondVirtualDevice = mVirtualDevice;

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME)
                        .setDirectChannelTypesSupported(TYPE_MEMORY_FILE)
                        .setHighestDirectReportRateLevel(RATE_NORMAL)
                        .build());

        // The channel is configured for the second device and the sensor does not belong to it.
        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        assertThat(mDirectChannel.configure(sensor, RATE_NORMAL)).isEqualTo(0);

        secondVirtualDevice.close();
    }

    @Test
    public void directConnectionForDefaultDevice_hardwareBuffer_notValidForVirtualDevice() {
        // Skip this test if hardware buffer direct channel is generally not supported on the device
        assumeTrue(mSensorManager.getSensorList(Sensor.TYPE_ALL).stream().anyMatch(
                s -> s.isDirectChannelTypeSupported(TYPE_HARDWARE_BUFFER)));

        HardwareBuffer hardwareBuffer = HardwareBuffer.create(
                /*width=*/SHARED_MEMORY_SIZE, /*height=*/1, HardwareBuffer.BLOB, /*layers=*/1,
                HardwareBuffer.USAGE_CPU_READ_OFTEN | HardwareBuffer.USAGE_GPU_DATA_BUFFER
                        | HardwareBuffer.USAGE_SENSOR_DIRECT_DATA);
        SensorDirectChannel channel = mSensorManager.createDirectChannel(hardwareBuffer);

        mVirtualSensor = setUpVirtualSensor(
                new VirtualSensorConfig.Builder(TYPE_ACCELEROMETER, VIRTUAL_SENSOR_NAME).build());

        // The channel is created for the default device ID, configuring it for a sensor of the
        // virtual device should not be allowed.
        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        assertThat(channel.configure(sensor, RATE_NORMAL)).isEqualTo(0);
    }

    @Test
    public void directConnection_memoryFile_triggersVirtualSensorCallback() throws Exception {
        setUpDirectChannel();

        ArgumentCaptor<Integer> channelHandle = ArgumentCaptor.forClass(Integer.class);
        ArgumentCaptor<SharedMemory> sharedMemory = ArgumentCaptor.forClass(SharedMemory.class);
        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelCreated(channelHandle.capture(), sharedMemory.capture());

        doAnswer((Answer<Void>) i -> {
            sharedMemory.getValue().close();
            return null;
        }).when(mVirtualSensorDirectChannelCallback)
                .onDirectChannelDestroyed(channelHandle.getValue());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        int reportToken = mDirectChannel.configure(sensor, RATE_NORMAL);
        assertThat(reportToken).isGreaterThan(0);

        ArgumentCaptor<VirtualSensor> virtualSensor = ArgumentCaptor.forClass(VirtualSensor.class);
        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelConfigured(eq(channelHandle.getValue()), virtualSensor.capture(),
                        eq(RATE_NORMAL), eq(reportToken));
        assertThat(virtualSensor.getValue().getHandle()).isEqualTo(mVirtualSensor.getHandle());

        assertThat(mDirectChannel.configure(sensor, RATE_STOP)).isEqualTo(1);

        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelConfigured(eq(channelHandle.getValue()), virtualSensor.capture(),
                        eq(RATE_STOP), eq(reportToken));
        assertThat(virtualSensor.getValue().getHandle()).isEqualTo(mVirtualSensor.getHandle());

        mDirectChannel.close();
        mDirectChannel = null;
        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelDestroyed(eq(channelHandle.getValue()));
    }

    @Test
    public void directConnection_memoryFile_stopAll_triggersVirtualSensorCallback()
            throws Exception {
        setUpDirectChannel();

        ArgumentCaptor<Integer> channelHandle = ArgumentCaptor.forClass(Integer.class);
        ArgumentCaptor<SharedMemory> sharedMemory = ArgumentCaptor.forClass(SharedMemory.class);
        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelCreated(channelHandle.capture(), sharedMemory.capture());

        doAnswer((Answer<Void>) i -> {
            sharedMemory.getValue().close();
            return null;
        }).when(mVirtualSensorDirectChannelCallback)
                .onDirectChannelDestroyed(channelHandle.getValue());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        int reportToken = mDirectChannel.configure(sensor, RATE_NORMAL);
        assertThat(reportToken).isGreaterThan(0);

        ArgumentCaptor<VirtualSensor> virtualSensor = ArgumentCaptor.forClass(VirtualSensor.class);
        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelConfigured(eq(channelHandle.getValue()), virtualSensor.capture(),
                        eq(RATE_NORMAL), eq(reportToken));
        assertThat(virtualSensor.getValue().getHandle()).isEqualTo(mVirtualSensor.getHandle());

        assertThat(mDirectChannel.configure(/*sensor=*/null, RATE_STOP)).isEqualTo(1);

        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelConfigured(eq(channelHandle.getValue()), virtualSensor.capture(),
                        eq(RATE_STOP), eq(reportToken));
        assertThat(virtualSensor.getValue().getHandle()).isEqualTo(mVirtualSensor.getHandle());
    }

    @Test
    public void directConnection_memoryFile_injectEvents() throws Exception {
        setUpDirectChannel();

        ArgumentCaptor<Integer> channelHandle = ArgumentCaptor.forClass(Integer.class);
        ArgumentCaptor<SharedMemory> sharedMemory = ArgumentCaptor.forClass(SharedMemory.class);
        verify(mVirtualSensorDirectChannelCallback, timeout(SENSOR_TIMEOUT_MILLIS).times(1))
                .onDirectChannelCreated(channelHandle.capture(), sharedMemory.capture());

        doAnswer((Answer<Void>) i -> {
            int reportToken = (int) i.getArguments()[3];
            writeDirectChannelEvents(reportToken, sharedMemory.getValue());
            return null;
        }).when(mVirtualSensorDirectChannelCallback)
                .onDirectChannelConfigured(eq(channelHandle.getValue()), any(), anyInt(), anyInt());

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        int reportToken = mDirectChannel.configure(sensor, RATE_NORMAL);
        verifyDirectChannelEvents(reportToken);

        doAnswer((Answer<Void>) i -> {
            sharedMemory.getValue().close();
            return null;
        }).when(mVirtualSensorDirectChannelCallback)
                .onDirectChannelDestroyed(channelHandle.getValue());
    }

    @Test
    public void directConnection_memoryFile_injectEvents_withHelperWriter() throws Exception {
        mVirtualSensorDirectChannelWriter = new VirtualSensorDirectChannelWriter();

        doAnswer((Answer<Void>) i -> {
            int channelHandle = (int) i.getArguments()[0];
            SharedMemory sharedMemory = (SharedMemory) i.getArguments()[1];
            mVirtualSensorDirectChannelWriter.addChannel(channelHandle, sharedMemory);
            return null;
        }).when(mVirtualSensorDirectChannelCallback).onDirectChannelCreated(anyInt(), any());

        doAnswer((Answer<Void>) i -> {
            int channelHandle = (int) i.getArguments()[0];
            mVirtualSensorDirectChannelWriter.removeChannel(channelHandle);
            return null;
        }).when(mVirtualSensorDirectChannelCallback).onDirectChannelDestroyed(anyInt());

        doAnswer((Answer<Void>) i -> {
            int channelHandle = (int) i.getArguments()[0];
            VirtualSensor sensor = (VirtualSensor) i.getArguments()[1];
            int rateLevel = (int) i.getArguments()[2];
            int reportToken = (int) i.getArguments()[3];
            assertThat(mVirtualSensorDirectChannelWriter.configureChannel(
                    channelHandle, sensor, rateLevel, reportToken)).isTrue();
            Random random = new Random();

            for (int eventCount = 0; eventCount < SENSOR_EVENT_COUNT * 2; ++eventCount) {
                float[] values = new float[] {
                        reportToken + eventCount * 0.01f,
                        reportToken + eventCount * 0.02f,
                        reportToken + eventCount * 0.03f,
                };
                assertThat(
                        mVirtualSensorDirectChannelWriter.writeSensorEvent(sensor,
                                new VirtualSensorEvent.Builder(values)
                                        .setTimestampNanos(System.nanoTime())
                                        .build()))
                        .isTrue();
                try {
                    Thread.sleep(random.nextInt(10));  // Sleep random time of 0-20ms.
                } catch (InterruptedException e) {
                    fail("Interrupted while writing sensor events: " + e);
                }
            }
            return null;
        }).when(mVirtualSensorDirectChannelCallback)
                .onDirectChannelConfigured(anyInt(), any(), anyInt(), anyInt());

        setUpDirectChannel();

        Sensor sensor = mVirtualDeviceSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        int reportToken = mDirectChannel.configure(sensor, RATE_NORMAL);
        verifyDirectChannelEvents(reportToken);
    }

    private class VirtualSensorEventListener implements SensorEventListener {
        private final BlockingQueue<SensorEvent> mEvents = new LinkedBlockingQueue<>();

        @Override
        public void onSensorChanged(SensorEvent event) {
            try {
                mEvents.put(new SensorEvent(event.sensor, event.accuracy, event.timestamp,
                        event.values));
            } catch (InterruptedException ex) {
                fail("Interrupted while adding a SensorEvent to the queue");
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        public void assertReceivedSensorEvent(Sensor sensor, VirtualSensorEvent expected) {
            SensorEvent event = waitForEvent();
            if (event == null) {
                fail("Did not receive SensorEvent with values "
                        + Arrays.toString(expected.getValues()));
            }

            assertThat(event.sensor).isEqualTo(sensor);
            assertThat(event.values).isEqualTo(expected.getValues());
            assertThat(event.timestamp).isEqualTo(expected.getTimestampNanos());
        }

        public void assertNoMoreEvents() {
            InstrumentationRegistry.getInstrumentation().waitForIdleSync();
            SensorEvent event = waitForEvent();
            if (event != null) {
                fail("Received extra SensorEvent with values: " + Arrays.toString(event.values));
            }
        }

        private SensorEvent waitForEvent() {
            try {
                return mEvents.poll(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                fail("Interrupted while waiting for SensorEvent");
                return null;
            }
        }
    }

    private void writeDirectChannelEvents(int reportToken, SharedMemory sharedMemory) {
        int offset = 0;
        int eventCount = 0;
        ByteBuffer event = ByteBuffer.allocate(SENSOR_EVENT_SIZE);
        event.order(ByteOrder.nativeOrder());
        Random random = new Random();
        ByteBuffer memoryMapping = null;
        try {
            memoryMapping = sharedMemory.mapReadWrite();
        } catch (ErrnoException e) {
            sharedMemory.close();
            fail("Could not map the shared memory for IO: " + e);
        }

        while (eventCount < SENSOR_EVENT_COUNT * 2) {
            event.position(0);
            event.putInt(SENSOR_EVENT_SIZE);
            event.putInt(reportToken);
            event.putInt(TYPE_ACCELEROMETER);
            event.putInt(++eventCount);
            event.putLong(System.nanoTime());
            // sensor values
            event.putFloat(reportToken + eventCount * 0.01f);
            event.putFloat(reportToken + eventCount * 0.02f);
            event.putFloat(reportToken + eventCount * 0.03f);

            memoryMapping.position(offset);
            memoryMapping.put(event.array(), 0, SENSOR_EVENT_SIZE);
            try {
                Thread.sleep(random.nextInt(10));  // Sleep random time of 0-20ms.
            } catch (InterruptedException e) {
                sharedMemory.close();
                fail("Interrupted while writing sensor events: " + e);
            }

            offset += SENSOR_EVENT_SIZE;
            if (offset + SENSOR_EVENT_SIZE >= sharedMemory.getSize()) {
                offset = 0;
            }
        }
    }

    // If there are no "real" events in general, then the virtual sensor events never reach the
    // registered listeners.
    // TODO(b/288383960): Remove this check and the relevant assumptions.
    private boolean defaultAccelerometerEventsAreAvailable() {
        final PackageManager packageManager =
                InstrumentationRegistry.getInstrumentation().getContext().getPackageManager();
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER)) {
            return false;
        }
        Sensor accelerometer = mSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        if (accelerometer == null) {
            return false;
        }
        if (!mSensorManager.registerListener(
                mDefaultSensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL)) {
            return false;
        }
        SensorEvent event = mDefaultSensorEventListener.waitForEvent();
        return event != null;
    }

    private void verifyDirectChannelEvents(int reportToken) throws Exception {
        int offset = 0;
        int eventCount = 0;
        ByteBuffer byteBuffer = ByteBuffer.allocate(SENSOR_EVENT_SIZE);
        byteBuffer.order(ByteOrder.nativeOrder());

        while (eventCount < SENSOR_EVENT_COUNT * 2) {
            assertThat(mMemoryFile.readBytes(byteBuffer.array(), offset, 0, SENSOR_EVENT_SIZE))
                    .isEqualTo(SENSOR_EVENT_SIZE);
            byteBuffer.position(0);
            int eventSize = byteBuffer.getInt();
            int actualReportToken = byteBuffer.getInt();
            if (reportToken != actualReportToken) {
                Thread.sleep(10);
                continue;
            }
            int sensorType = byteBuffer.getInt();
            int eventCounter = byteBuffer.getInt();

            if (eventCounter > 0) {
                if (eventCounter != eventCount + 1) {
                    Thread.sleep(10);
                    continue;
                }
                eventCount++;

                assertThat(eventSize).isEqualTo(SENSOR_EVENT_SIZE);
                assertThat(sensorType).isEqualTo(TYPE_ACCELEROMETER);

                byteBuffer.getLong();  // timestamp

                // verify the sensor values
                assertThat(byteBuffer.getFloat())
                        .isEqualTo(reportToken + eventCounter * 0.1f);
                assertThat(byteBuffer.getFloat())
                        .isEqualTo(reportToken + eventCounter * 0.2f);
                assertThat(byteBuffer.getFloat())
                        .isEqualTo(reportToken + eventCounter * 0.3f);

                offset += SENSOR_EVENT_SIZE;
                if (offset + SENSOR_EVENT_SIZE >= SHARED_MEMORY_SIZE) {
                    offset = 0;
                }
            }
        }
    }
}