1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.platform.helpers.foldable 18 19 import android.hardware.SensorManager 20 import android.platform.test.rule.TestWatcher 21 import kotlin.properties.Delegates.notNull 22 import org.junit.Assume 23 24 /** 25 * Allows to inject values to a sensor. Assumes that sensor injection is supported. Note that 26 * currently injection is only supported on virtual devices. 27 */ 28 class SensorInjectionController(sensorType: Int) : TestWatcher() { 29 30 private val sensorManager = context.getSystemService(SensorManager::class.java)!! 31 private val sensor = sensorManager.getDefaultSensor(sensorType) 32 private var initialized = false 33 34 var injectionSupported by notNull<Boolean>() 35 private set 36 initnull37 fun init() { 38 executeShellCommand(SENSOR_SERVICE_ENABLE) 39 executeShellCommand(SENSOR_SERVICE_DATA_INJECTION + context.packageName) 40 injectionSupported = sensorManager.initDataInjection(true) 41 initialized = true 42 } 43 uninitnull44 fun uninit() { 45 if (initialized && injectionSupported) { 46 sensorManager.initDataInjection(false) 47 } 48 initialized = false 49 } 50 setValuenull51 fun setValue(value: Float) { 52 check(initialized) { "Trying to set sensor value before initialization" } 53 Assume.assumeTrue("Skipping as data injection is not supported", injectionSupported) 54 check( 55 sensorManager.injectSensorData( 56 sensor, 57 floatArrayOf(value), 58 SensorManager.SENSOR_STATUS_ACCURACY_HIGH, 59 System.currentTimeMillis() 60 ) 61 ) { 62 "Error while injecting sensor data." 63 } 64 } 65 66 companion object { 67 private const val SENSOR_SERVICE_ENABLE = "dumpsys sensorservice enable" 68 private const val SENSOR_SERVICE_DATA_INJECTION = "dumpsys sensorservice data_injection " 69 } 70 } 71