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.hardware.SensorManager.HAL_BYPASS_REPLAY_DATA_INJECTION 21 import android.platform.test.rule.TestWatcher 22 import org.junit.Assume 23 import kotlin.properties.Delegates.notNull 24 25 /** 26 * Allows to inject values to a sensor. Assumes that sensor injection is supported. Note that 27 * currently injection is only supported on virtual devices. 28 */ 29 class SensorInjectionController(sensorType: Int) : TestWatcher() { 30 31 private val sensorManager = context.getSystemService(SensorManager::class.java)!! 32 private val sensor = sensorManager.getDefaultSensor(sensorType) 33 private var initialized = false 34 35 var injectionSupported by notNull<Boolean>() 36 private set 37 initnull38 fun init() { 39 executeShellCommand(SENSOR_SERVICE_ENABLE) 40 executeShellCommand(SENSOR_SERVICE_DATA_INJECTION + context.packageName) 41 injectionSupported = sensorManager.initDataInjection(true, 42 HAL_BYPASS_REPLAY_DATA_INJECTION) 43 initialized = true 44 } 45 uninitnull46 fun uninit() { 47 if (initialized && injectionSupported) { 48 sensorManager.initDataInjection(false) 49 } 50 initialized = false 51 } 52 setValuenull53 fun setValue(value: Float) { 54 check(initialized) { "Trying to set sensor value before initialization" } 55 Assume.assumeTrue("Skipping as data injection is not supported", injectionSupported) 56 check( 57 sensorManager.injectSensorData( 58 sensor, 59 floatArrayOf(value), 60 SensorManager.SENSOR_STATUS_ACCURACY_HIGH, 61 System.currentTimeMillis() 62 ) 63 ) { 64 "Error while injecting sensor data." 65 } 66 } 67 68 companion object { 69 private const val SENSOR_SERVICE_ENABLE = "dumpsys sensorservice enable" 70 private const val SENSOR_SERVICE_DATA_INJECTION = "dumpsys sensorservice hal_bypass_replay_data_injection " 71 } 72 } 73