package com.example.myapplication.ui.yemian
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.io.File
import java.io.FileReader
import java.io.IOException
@Composable
fun otgscreen(
onBack: () -> Unit,
activity: ComponentActivity
) {
val context = LocalContext.current
var otgConnected by remember { mutableStateOf(false) }
var deviceInfo by remember { mutableStateOf("") }
var usbSupported by remember { mutableStateOf(false) }
var ccOrientation by remember { mutableStateOf("") }
var ccOrientationText by remember { mutableStateOf("") }
// 新增:三次检测相关状态
var isTesting by remember { mutableStateOf(false) }
var testStep by remember { mutableStateOf(0) } // 0:未开始, 1:第一次, 2:第二次, 3:第三次
var firstOrientation by remember { mutableStateOf("") }
var secondOrientation by remember { mutableStateOf("") }
var thirdOrientation by remember { mutableStateOf("") }
var testResult by remember { mutableStateOf("") }
// 检查设备是否支持USB主机模式
LaunchedEffect(Unit) {
usbSupported = context.packageManager.hasSystemFeature("android.hardware.usb.host")
if (!usbSupported) {
deviceInfo = "设备不支持USB主机模式"
} else {
checkOtgStatus(context) { connected, info ->
otgConnected = connected
deviceInfo = info
}
}
// 初始读取CC引脚状态
if (usbSupported) {
val ccValue = readCcOrientation()
ccOrientation = ccValue
ccOrientationText = parseCcOrientation(ccValue)
}
}
// 在 DisposableEffect 之后添加这个监听器
// 注册USB状态变化监听器
DisposableEffect(Unit) {
if (usbSupported) {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
otgConnected = true
deviceInfo = "USB设备已连接"
// USB连接时读取CC引脚状态
val ccValue = readCcOrientation()
ccOrientation = ccValue
ccOrientationText = parseCcOrientation(ccValue)
// 三次检测逻辑
when (testStep) {
0 -> {
// 第一次插入
firstOrientation = ccValue
testStep = 1
testResult = "第一次插入: ${parseCcOrientation(ccValue)}\n请拔出后反插"
}
1 -> {
// 第二次插入 - 确保与第一次不同
if (ccValue != firstOrientation) {
secondOrientation = ccValue
testStep = 2
testResult = "第二次插入: ${parseCcOrientation(ccValue)}\n请拔出后再次正插"
} else {
testResult = "插入方向与第一次相同,请反插!\n当前: ${parseCcOrientation(ccValue)}"
}
}
2 -> {
// 第三次插入 - 确保与第一次相同
if (ccValue == firstOrientation) {
thirdOrientation = ccValue
testStep = 3
testResult = "测试通过! ✓\n第一次和第三次一致: ${parseCcOrientation(ccValue)}"
isTesting = false
} else {
testResult = "测试失败! ✗\n第一次和第三次不一致\n请重新插入第一次的方向: ${parseCcOrientation(firstOrientation)}"
// 保持testStep=2,等待正确插入
}
}
}
}
UsbManager.ACTION_USB_DEVICE_DETACHED -> {
otgConnected = false
deviceInfo = "USB设备已断开"
ccOrientation = ""
ccOrientationText = ""
// 在拔出时更新提示
if (isTesting) {
when (testStep) {
1 -> testResult = "设备已拔出,请反插USB设备"
2 -> testResult = "设备已拔出,请再次正插USB设备"
}
}
}
}
}
}
val filter = IntentFilter().apply {
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
}
context.registerReceiver(receiver, filter)
onDispose {
context.unregisterReceiver(receiver)
}
} else {
onDispose {}
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// 显示OTG连接状态
Text(
text = "OTG状态: ${if (otgConnected) "已连接" else "未连接"}",
fontSize = 24.sp,
color = if (otgConnected) Color.Green else Color.Red,
modifier = Modifier.padding(16.dp)
)
// 显示正反插状态
if (otgConnected) {
Text(
text = "插口方向: $ccOrientationText",
fontSize = 20.sp,
color = when (ccOrientation) {
"2" -> Color.Green // 正插显示绿色
"1" -> Color.Yellow // 反插显示黄色
else -> Color.Gray
},
modifier = Modifier.padding(8.dp)
)
// 显示原始CC引脚值(用于调试)
Text(
text = "CC引脚值: $ccOrientation",
fontSize = 14.sp,
color = Color.Gray,
modifier = Modifier.padding(4.dp)
)
}
// 显示设备信息
Text(
text = deviceInfo,
fontSize = 18.sp,
modifier = Modifier.padding(16.dp)
)
// 新增:显示三次检测结果
if (isTesting || testResult.isNotEmpty()) {
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "三次检测状态:",
fontSize = 18.sp,
color = Color.Blue,
modifier = Modifier.padding(8.dp)
)
Text(
text = testResult,
fontSize = 16.sp,
color = when {
testResult.contains("测试通过") -> Color.Green
testResult.contains("测试失败") -> Color.Red
else -> Color.Black
},
modifier = Modifier.padding(8.dp)
)
// 显示测试进度
if (isTesting) {
Text(
text = "测试进度: $testStep/3",
fontSize = 14.sp,
color = Color.Gray,
modifier = Modifier.padding(4.dp)
)
}
}
Spacer(modifier = Modifier.height(32.dp))
// 新增:开始三次检测按钮
Button(
onClick = {
isTesting = true
testStep = 0
firstOrientation = ""
secondOrientation = ""
thirdOrientation = ""
testResult = "请插入USB设备开始测试\n第一步:正插"
},
enabled = !isTesting,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text("开始三次正反插检测")
}
// 新增:重置测试按钮
if (isTesting) {
Button(
onClick = {
isTesting = false
testStep = 0
testResult = ""
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text("重置测试")
}
}
// 单独检测CC引脚按钮
Button(
onClick = {
val ccValue = readCcOrientation()
ccOrientation = ccValue
ccOrientationText = parseCcOrientation(ccValue)
deviceInfo = "手动检测完成 - 方向: $ccOrientationText"
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text("单独检测正反插方向")
}
// 重新检测按钮
Button(
onClick = {
if (usbSupported) {
checkOtgStatus(context) { connected, info ->
otgConnected = connected
deviceInfo = info
}
// 重新检测CC引脚状态
if (otgConnected) {
val ccValue = readCcOrientation()
ccOrientation = ccValue
ccOrientationText = parseCcOrientation(ccValue)
}
}
},
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text("重新检测OTG状态")
}
// 返回按钮
Button(
onClick = onBack,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text("返回主菜单")
}
}
}
// 检查OTG状态
private fun checkOtgStatus(context: Context, callback: (Boolean, String) -> Unit) {
val usbManager = context.getSystemService(Context.USB_SERVICE) as? UsbManager
if (usbManager == null) {
callback(false, "无法获取USB服务")
return
}
val deviceList = usbManager.deviceList
val isConnected = deviceList.isNotEmpty()
if (isConnected) {
val deviceInfo = buildString {
appendLine("检测到USB设备:")
deviceList.values.forEachIndexed { index, device ->
appendLine("设备 ${index + 1}:")
appendLine("名称: ${device.deviceName}")
appendLine("厂商ID: 0x${device.vendorId.toString(16)}")
appendLine("产品ID: 0x${device.productId.toString(16)}")
// 显示CC引脚状态
val ccValue = readCcOrientation()
val orientationText = parseCcOrientation(ccValue)
appendLine("插口方向: $orientationText")
appendLine()
}
}
callback(true, deviceInfo)
} else {
callback(false, "未检测到USB设备")
}
}
// 读取 CC 引脚状态
private fun readCcOrientation(): String {
return try {
// 尝试多个可能的路径
val possiblePaths = arrayOf(
"/sys/devices/virtual/oplus_chg/usb/typec_cc_orientation",
"/sys/devices/platform/charger/power_supply/usb/typec_cc_orientation",
"/sys/class/power_supply/usb/typec_cc_orientation"
)
var result = "文件不存在"
for (path in possiblePaths) {
val file = File(path)
if (file.exists()) {
val content = getFileInfo(path)
if (content != null) {
result = content
break
}
}
}
result
} catch (e: Exception) {
Log.d("CC_DEBUG", "读取CC引脚异常: ${e.message}")
"读取错误: ${e.message}"
}
}
// 解析 CC 引脚状态为可读信息
private fun parseCcOrientation(ccValue: String): String {
return when {
ccValue.contains("2") -> "正插"
ccValue.contains("1") -> "反插"
ccValue.contains("文件不存在") -> "CC引脚文件不存在"
ccValue.contains("读取错误") -> ccValue
else -> "未知状态: $ccValue"
}
}
private fun getFileInfo(path: String): String? {
val mFile = File(path)
var mFileReader: FileReader? = null
val BUFFER_SIZE = 128
return try {
mFileReader = FileReader(mFile)
val data = CharArray(BUFFER_SIZE)
val charCount = mFileReader.read(data)
if (charCount <= 0) {
null
} else {
val content = String(data, 0, charCount).trim()
val status = content.split("\n").dropLastWhile { it.isEmpty() }.toTypedArray()
status[0]
}
} catch (e: IOException) {
Log.e("OTG_DEBUG", "读取文件错误: ", e)
null
} finally {
mFileReader?.close()
}
}这个为什么总是显示0/3就算我插入了扒出来他还是不会推进到下一步,为什么给我解决办法
最新发布