android.hardware.cts.helpers.TestSensorEnvironment

Here are the examples of the java api class android.hardware.cts.helpers.TestSensorEnvironment taken from open source projects.

1. MagneticFieldMeasurementTestActivity#testCalibratedAndUncalibrated()

Project: CtsVerifier
File: MagneticFieldMeasurementTestActivity.java
/**
     * Verifies that the relationship between readings from calibrated and their corresponding
     * uncalibrated sensors comply to the following equation:
     *      calibrated = uncalibrated - bias
     */
@SuppressWarnings("unused")
public String testCalibratedAndUncalibrated() throws Throwable {
    getTestLogger().logMessage(R.string.snsr_mag_verify_calibrated_uncalibrated);
    TestSensorEnvironment calibratedEnvironment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_MAGNETIC_FIELD, SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorEnvironment uncalibratedEnvironment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED, SensorManager.SENSOR_DELAY_FASTEST);
    SensorCalibratedUncalibratedVerifier verifier = new SensorCalibratedUncalibratedVerifier(calibratedEnvironment, uncalibratedEnvironment, THRESHOLD_CALIBRATED_UNCALIBRATED_UT);
    try {
        verifier.execute();
    } finally {
        playSound();
    }
    return null;
}

2. MagneticFieldMeasurementTestActivity#testStandardDeviation()

Project: CtsVerifier
File: MagneticFieldMeasurementTestActivity.java
/**
     * This test verifies that the standard deviation of a set of sampled data from a particular
     * sensor falls into the expectations defined in the CDD. The verification applies to each axis
     * of the sampled data reported by the Sensor under test.
     * This test is used to validate the requirement imposed by the CDD to Sensors in Android. And
     * characterizes how the Sensor behaves while static.
     *
     * The test takes a set of samples from the sensor under test, and calculates the Standard
     * Deviation for each of the axes the Sensor reports data for. The StdDev is compared against
     * the expected value documented in the CDD.
     *
     * The test is susceptible to errors if the device is moving while the test is running, or if
     * the Sensor's sampled data indeed falls into a large StdDev.
     *
     * The assertion associated with the test provides the required data to identify any possible
     * issue. It provides:
     * - the thread id on which the failure occurred
     * - the sensor type and sensor handle that caused the failure
     * - the expectation of the test
     * - the std dev calculated and the axis it applies to
     * Additionally, the device's debug output (adb logcat) dumps the set of values associated with
     * the failure to help track down the issue.
     */
@SuppressWarnings("unused")
public String testStandardDeviation() throws Throwable {
    getTestLogger().logMessage(R.string.snsr_mag_verify_std_dev);
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_MAGNETIC_FIELD, SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorOperation verifyStdDev = TestSensorOperation.createOperation(environment, 100);
    verifyStdDev.addVerification(new StandardDeviationVerification(new float[] { 2f, 2f, 2f }));
    verifyStdDev.execute(getCurrentTestNode());
    return null;
}

3. MagneticFieldMeasurementTestActivity#testNorm()

Project: CtsVerifier
File: MagneticFieldMeasurementTestActivity.java
/**
     * This test verifies that the Norm of the sensor data is close to the expected reference value.
     * The units of the reference value are dependent on the type of sensor.
     * This test is used to verify that the data reported by the sensor is close to the expected
     * range and scale.
     *
     * The test takes a sample from the sensor under test and calculates the Euclidean Norm of the
     * vector represented by the sampled data. It then compares it against the test expectations
     * that are represented by a reference value and a threshold.
     *
     * The test is susceptible to errors when the Sensor under test is uncalibrated, or the units in
     * which the data are reported and the expectations are set are different.
     *
     * The assertion associated with the test provides the required data needed to identify any
     * possible issue. It provides:
     * - the thread id on which the failure occurred
     * - the sensor type and sensor handle that caused the failure
     * - the values representing the expectation of the test
     * - the values sampled from the sensor
     */
@SuppressWarnings("unused")
public String testNorm() throws Throwable {
    getTestLogger().logMessage(R.string.snsr_mag_verify_norm);
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_MAGNETIC_FIELD, SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorOperation verifyNorm = TestSensorOperation.createOperation(environment, 100);
    float expectedMagneticFieldEarth = (SensorManager.MAGNETIC_FIELD_EARTH_MAX + SensorManager.MAGNETIC_FIELD_EARTH_MIN) / 2;
    float magneticFieldEarthThreshold = expectedMagneticFieldEarth - SensorManager.MAGNETIC_FIELD_EARTH_MIN;
    verifyNorm.addVerification(new MagnitudeVerification(expectedMagneticFieldEarth, magneticFieldEarthThreshold));
    verifyNorm.execute(getCurrentTestNode());
    return null;
}

4. BatchingTestActivity#runFlushTest()

Project: CtsVerifier
File: BatchingTestActivity.java
private String runFlushTest(int sensorType, int maxBatchReportLatencySec, int instructionsResId) throws Throwable {
    getTestLogger().logInstructions(instructionsResId);
    waitForUserToBegin();
    int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), sensorType, SENSOR_BATCHING_RATE_US, maxBatchReportLatencyUs);
    int flushDurationSec = maxBatchReportLatencySec / 2;
    TestSensorOperation operation = TestSensorOperation.createFlushOperation(environment, flushDurationSec, TimeUnit.SECONDS);
    return executeTest(operation);
}

5. BatchingTestActivity#runBatchTest()

Project: CtsVerifier
File: BatchingTestActivity.java
private String runBatchTest(int sensorType, int maxBatchReportLatencySec, int instructionsResId) throws Throwable {
    getTestLogger().logInstructions(instructionsResId);
    waitForUserToBegin();
    int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), sensorType, SENSOR_BATCHING_RATE_US, maxBatchReportLatencyUs);
    int testDurationSec = maxBatchReportLatencySec + BATCHING_PADDING_TIME_S;
    TestSensorOperation operation = TestSensorOperation.createOperation(environment, testDurationSec, TimeUnit.SECONDS);
    return executeTest(operation);
}

6. AccelerometerMeasurementTestActivity#verifyMeasurements()

Project: CtsVerifier
File: AccelerometerMeasurementTestActivity.java
/**
     * This test verifies that the Accelerometer measurements are close to the expected reference
     * values (range and scale).
     *
     * The test takes a set of samples from the sensor under test and calculates the mean of each
     * axis that the sensor data collects. It then compares it against the test expectations that
     * are represented by reference values and a threshold.

     * The reference values are coupled to the orientation of the device. The test is susceptible to
     * errors when the device is not oriented properly, or the units in which the data are reported
     * and the expectations are set are different.
     *
     * The error message associated with the test provides the required data needed to identify any
     * possible issue. It provides:
     * - the thread id on which the failure occurred
     * - the sensor type and sensor handle that caused the failure
     * - the values representing the expectation of the test
     * - the mean of values sampled from the sensor
     */
private String verifyMeasurements(float... expectations) throws Throwable {
    Thread.sleep(500);
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_ACCELEROMETER, SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorOperation verifyMeasurements = TestSensorOperation.createOperation(environment, 100);
    verifyMeasurements.addVerification(new MeanVerification(expectations, new float[] { 1.95f, 1.95f, 1.95f }));
    verifyMeasurements.execute(getCurrentTestNode());
    return null;
}

7. SingleSensorTests#runSensorTest()

Project: CtsVerifier
File: SingleSensorTests.java
private void runSensorTest(int sensorType, int rateUs) throws Throwable {
    TestSensorEnvironment environment = new TestSensorEnvironment(getContext(), sensorType, shouldEmulateSensorUnderLoad(), rateUs);
    TestSensorOperation op = TestSensorOperation.createOperation(environment, 5, TimeUnit.SECONDS);
    op.addDefaultVerifications();
    try {
        op.execute(getCurrentTestNode());
    } finally {
        SensorStats stats = op.getStats();
        stats.log(TAG);
        String fileName = String.format("single_%s_%s.txt", SensorStats.getSanitizedSensorName(environment.getSensor()), environment.getFrequencyString());
        stats.logToFile(fileName);
    }
}

8. SensorBatchingTests#runFlushSensorTest()

Project: CtsVerifier
File: SensorBatchingTests.java
private void runFlushSensorTest(int sensorType, int rateUs, int maxBatchReportLatencySec) throws Throwable {
    int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
    int flushDurationSec = maxBatchReportLatencySec / 2;
    TestSensorEnvironment environment = new TestSensorEnvironment(getContext(), sensorType, shouldEmulateSensorUnderLoad(), rateUs, maxBatchReportLatencyUs);
    TestSensorOperation operation = TestSensorOperation.createFlushOperation(environment, flushDurationSec, TimeUnit.SECONDS);
    executeTest(environment, operation, true);
}

9. SensorBatchingTests#runBatchingSensorTest()

Project: CtsVerifier
File: SensorBatchingTests.java
private void runBatchingSensorTest(int sensorType, int rateUs, int maxBatchReportLatencySec) throws Throwable {
    int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
    int testDurationSec = maxBatchReportLatencySec + BATCHING_PADDING_TIME_S;
    TestSensorEnvironment environment = new TestSensorEnvironment(getContext(), sensorType, shouldEmulateSensorUnderLoad(), rateUs, maxBatchReportLatencyUs);
    TestSensorOperation operation = TestSensorOperation.createOperation(environment, testDurationSec, TimeUnit.SECONDS);
    executeTest(environment, operation, false);
}

10. GyroscopeMeasurementTestActivity#testCalibratedAndUncalibrated()

Project: CtsVerifier
File: GyroscopeMeasurementTestActivity.java
/**
     * Verifies that the relationship between readings from calibrated and their corresponding
     * uncalibrated sensors comply to the following equation:
     *      calibrated = uncalibrated - bias
     */
@SuppressWarnings("unused")
public String testCalibratedAndUncalibrated() throws Throwable {
    setRendererRotation(Z_AXIS, false);
    SensorTestLogger logger = getTestLogger();
    logger.logInstructions(R.string.snsr_keep_device_rotating_clockwise);
    waitForUserToBegin();
    logger.logWaitForSound();
    TestSensorEnvironment calibratedEnvironment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_GYROSCOPE, SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorEnvironment uncalibratedEnvironment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_GYROSCOPE_UNCALIBRATED, SensorManager.SENSOR_DELAY_FASTEST);
    SensorCalibratedUncalibratedVerifier verifier = new SensorCalibratedUncalibratedVerifier(calibratedEnvironment, uncalibratedEnvironment, THRESHOLD_CALIBRATED_UNCALIBRATED_RAD_SEC);
    try {
        verifier.execute();
    } finally {
        playSound();
    }
    return null;
}

11. SensorIntegrationTests#verifySensorStoppingInteraction()

Project: CtsVerifier
File: SensorIntegrationTests.java
/**
     * This test verifies that starting/stopping a particular Sensor client in the System does not
     * affect other sensor clients.
     * the test is used to validate that starting/stopping operations are independent on several
     * sensor clients.
     *
     * The test verifies for each client that the a set of sampled data arrives in order. However
     * each client in the test has different set of parameters that represent different types of
     * clients in the real world.
     *
     * The test can be susceptible to issues when several clients interacting with the system
     * actually affect the operation of other clients.
     *
     * The assertion associated with the test failure provides:
     * - the thread id on which the failure occurred
     * - the sensor type and sensor handle that caused the failure
     * - the event that caused the issue
     * It is important to look at the internals of the Sensor HAL to identify how the interaction
     * of several clients can lead to the failing state.
     */
public void verifySensorStoppingInteraction(int sensorTypeTestee, int sensorTypeTester) throws Throwable {
    Context context = getContext();
    TestSensorEnvironment testerEnvironment = new TestSensorEnvironment(context, sensorTypeTester, shouldEmulateSensorUnderLoad(), SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorOperation tester = TestSensorOperation.createOperation(testerEnvironment, 100);
    tester.addVerification(new EventOrderingVerification());
    TestSensorEnvironment testeeEnvironment = new TestSensorEnvironment(context, sensorTypeTestee, shouldEmulateSensorUnderLoad(), SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorOperation testee = TestSensorOperation.createOperation(testeeEnvironment, 100);
    testee.addVerification(new EventOrderingVerification());
    ParallelSensorOperation operation = new ParallelSensorOperation();
    operation.add(tester, testee);
    operation.execute(getCurrentTestNode());
    operation.getStats().log(TAG);
    testee = testee.clone();
    testee.execute(getCurrentTestNode());
    testee.getStats().log(TAG);
}

12. MagneticFieldMeasurementTestActivity#calibrateMagnetometer()

Project: CtsVerifier
File: MagneticFieldMeasurementTestActivity.java
/**
     * A routine to help operators calibrate the magnetometer.
     */
private void calibrateMagnetometer() throws InterruptedException {
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_MAGNETIC_FIELD, SensorManager.SENSOR_DELAY_NORMAL);
    TestSensorEventListener listener = new TestSensorEventListener(environment) {

        @Override
        public void onSensorChanged(SensorEvent event) {
            clearText();
            float values[] = event.values;
            SensorTestLogger logger = getTestLogger();
            logger.logInstructions(R.string.snsr_mag_calibration_description);
            logger.logMessage(R.string.snsr_mag_measurement, values[0], values[1], values[2], SensorCtsHelper.getMagnitude(values));
            // TODO: automate finding out when the magnetometer is calibrated
            logger.logInstructions(R.string.snsr_mag_calibration_complete);
        }
    };
    TestSensorManager magnetometer = new TestSensorManager(environment);
    try {
        magnetometer.registerListener(listener);
        waitForUserToContinue();
    } finally {
        magnetometer.unregisterListener();
    }
}

13. GyroscopeMeasurementTestActivity#verifyMeasurements()

Project: CtsVerifier
File: GyroscopeMeasurementTestActivity.java
/**
     * This test verifies that the Gyroscope measures the appropriate angular position.
     *
     * The test takes a set of samples from the sensor under test and calculates the angular
     * position for each axis that the sensor data collects. It then compares it against the test
     * expectations that are represented by signed values. It verifies that the readings have the
     * right magnitude.
     */
private String verifyMeasurements(int instructionsResId, int rotationAxis, int expectationDeg) throws Throwable {
    setRendererRotation(rotationAxis, expectationDeg >= 0);
    SensorTestLogger logger = getTestLogger();
    logger.logInstructions(instructionsResId);
    waitForUserToBegin();
    logger.logWaitForSound();
    TestSensorEnvironment environment = new TestSensorEnvironment(getApplicationContext(), Sensor.TYPE_GYROSCOPE, SensorManager.SENSOR_DELAY_FASTEST);
    TestSensorOperation sensorOperation = TestSensorOperation.createOperation(environment, ROTATION_COLLECTION_SEC, TimeUnit.SECONDS);
    int gyroscopeAxes = environment.getSensorAxesCount();
    int[] expectationsDeg = getExpectationsDeg(gyroscopeAxes, rotationAxis, expectationDeg);
    float[] thresholdsDeg = getThresholdsDeg(gyroscopeAxes, rotationAxis);
    GyroscopeIntegrationVerification integrationVerification = new GyroscopeIntegrationVerification(expectationsDeg, thresholdsDeg);
    sensorOperation.addVerification(integrationVerification);
    try {
        sensorOperation.execute(getCurrentTestNode());
    } finally {
        playSound();
    }
    return null;
}

14. SensorTest#testBatchAndFlushWithHandler()

Project: CtsVerifier
File: SensorTest.java
/**
     * Verifies that sensor events arrive in the given message queue (Handler).
     */
@TimeoutReq(minutes = 10)
public void testBatchAndFlushWithHandler() throws Exception {
    Sensor sensor = null;
    for (Sensor s : mSensorList) {
        if (s.getReportingMode() == Sensor.REPORTING_MODE_CONTINUOUS) {
            sensor = s;
            break;
        }
    }
    if (sensor == null) {
        throw new SensorTestStateNotSupportedException("There are no Continuous sensors in the device.");
    }
    TestSensorEnvironment environment = new TestSensorEnvironment(getContext(), sensor, SensorManager.SENSOR_DELAY_FASTEST, (int) TimeUnit.SECONDS.toMicros(5));
    TestSensorManager sensorManager = new TestSensorManager(environment);
    HandlerThread handlerThread = new HandlerThread("sensorThread");
    handlerThread.start();
    Handler handler = new Handler(handlerThread.getLooper());
    TestSensorEventListener listener = new TestSensorEventListener(environment, handler);
    CountDownLatch eventLatch = sensorManager.registerListener(listener, 1);
    listener.waitForEvents(eventLatch, 1);
    CountDownLatch flushLatch = sensorManager.requestFlush();
    listener.waitForFlushComplete(flushLatch);
    listener.assertEventsReceivedInHandler();
}

15. JitterVerificationTest#testVerify()

Project: CtsVerifier
File: JitterVerificationTest.java
public void testVerify() {
    final int SAMPLE_SIZE = 100;
    // for unit testing the verification, only the parameter 'sensorMightHaveMoreListeners' is
    // required
    TestSensorEnvironment environment = new TestSensorEnvironment(null, /* context */
    null, /* sensor */
    false, /* sensorMightHaveMoreListeners */
    0, /*samplingPeriodUs */
    0);
    // 100 samples at 1000Hz
    long[] timestamps = new long[SAMPLE_SIZE];
    for (int i = 0; i < SAMPLE_SIZE; i++) {
        timestamps[i] = i * 100000;
    }
    SensorStats stats = new SensorStats();
    ISensorVerification verification = getVerification(1, timestamps);
    verification.verify(environment, stats);
    verifyStats(stats, true, 0.0);
    // 90 samples at 1000Hz, 10 samples at 2000Hz
    long timestamp = 0;
    for (int i = 0; i < SAMPLE_SIZE; i++) {
        timestamps[i] = timestamp;
        timestamp += (i % 10 == 0) ? 500000 : 1000000;
    }
    stats = new SensorStats();
    verification = getVerification(1, timestamps);
    try {
        verification.verify(environment, stats);
        fail("Expected an AssertionError");
    } catch (AssertionError e) {
    }
    verifyStats(stats, false, 47.34);
}

16. EventGapVerificationTest#runVerification()

Project: CtsVerifier
File: EventGapVerificationTest.java
private void runVerification(int expected, long[] timestamps, boolean pass, int[] indices) {
    SensorStats stats = new SensorStats();
    ISensorVerification verification = getVerification(expected, timestamps);
    TestSensorEnvironment environment = new TestSensorEnvironment(null, null, false, 0, 0);
    if (pass) {
        verification.verify(environment, stats);
    } else {
        boolean failed = false;
        try {
            verification.verify(environment, stats);
        } catch (AssertionError e) {
            failed = true;
        }
        assertTrue("Expected an AssertionError", failed);
    }
    assertEquals(pass, stats.getValue(EventGapVerification.PASSED_KEY));
    assertEquals(indices.length, stats.getValue(SensorStats.EVENT_GAP_COUNT_KEY));
    assertNotNull(stats.getValue(SensorStats.EVENT_GAP_POSITIONS_KEY));
    int[] actualIndices = (int[]) stats.getValue(SensorStats.EVENT_GAP_POSITIONS_KEY);
    assertEquals(indices.length, actualIndices.length);
    for (int i = 0; i < indices.length; i++) {
        assertEquals(indices[i], actualIndices[i]);
    }
}