Compare commits

..

1 Commits

Author SHA1 Message Date
areumwoo
ad5077db69 feat: #72 Read/Write 표시 위치 수정 미적용 2026-03-02 10:27:56 +09:00
18 changed files with 92 additions and 377 deletions

View File

@@ -214,10 +214,3 @@
- `loadFluenceTable()`, `loadHzTable()`, `calculateInterpolatedC()` 영향 확인 - `loadFluenceTable()`, `loadHzTable()`, `calculateInterpolatedC()` 영향 확인
- 성능/안정성 이슈 시 - 성능/안정성 이슈 시
- `txPacketLoop()` 주기, `RX_TIMEOUT_THRESHOLD`, DB 로그 적재량 점검 - `txPacketLoop()` 주기, `RX_TIMEOUT_THRESHOLD`, DB 로그 적재량 점검
## 10) Troubleshooting
- 시리얼 초기 TX 누락(Startup race, FD 설명, 수정 내역):
- [`docs/serial_tx_startup_race.md`](docs/serial_tx_startup_race.md)
- 변경 요약 문서(`git diff` 기준):
- [`docs/change_summary_2026-03-04.md`](docs/change_summary_2026-03-04.md)

View File

@@ -88,7 +88,4 @@ interface Preference {
suspend fun getPowerSupplySerialListFromPreference(): Flow<List<String>> suspend fun getPowerSupplySerialListFromPreference(): Flow<List<String>>
///// /////
suspend fun saveInfoChartLineStates(states: Map<String, Boolean>)
suspend fun getInfoChartLineStates(): Flow<Map<String, Boolean>>
} }

View File

@@ -68,9 +68,6 @@ class PreferenceRepository(private val context: Context) : Preference {
val PRODUCT_SERIAL = stringPreferencesKey("PRODUCT_SERIAL") val PRODUCT_SERIAL = stringPreferencesKey("PRODUCT_SERIAL")
val LASER_HAND_SERIAL = stringPreferencesKey("LASER_HAND_SERIAL") val LASER_HAND_SERIAL = stringPreferencesKey("LASER_HAND_SERIAL")
val POWER_SUPPLY_SERIAL = stringPreferencesKey("POWER_SUPPLY_SERIAL") val POWER_SUPPLY_SERIAL = stringPreferencesKey("POWER_SUPPLY_SERIAL")
// InfoScreen Chart Checkboxes
val INFO_CHART_LINE_STATES = stringPreferencesKey("INFO_CHART_LINE_STATES")
} }
override suspend fun clearAllPreferences() { override suspend fun clearAllPreferences() {
@@ -562,31 +559,4 @@ class PreferenceRepository(private val context: Context) : Preference {
emit(listOf("B", "U", "O", "C", "L", "D")) emit(listOf("B", "U", "O", "C", "L", "D"))
} }
} }
override suspend fun saveInfoChartLineStates(states: Map<String, Boolean>) {
try {
val stateJson = gson.toJson(states)
context.datastore.edit { preferences ->
preferences[INFO_CHART_LINE_STATES] = stateJson
}
} catch (e: Exception) {
Timber.e(e, "Failed to serialize INFO_CHART_LINE_STATES to JSON.")
}
}
override suspend fun getInfoChartLineStates(): Flow<Map<String, Boolean>> {
return context.datastore.data.map { preferences ->
preferences[INFO_CHART_LINE_STATES]
}.distinctUntilChanged().map { jsonString ->
if (!jsonString.isNullOrBlank()) {
val type = object : TypeToken<Map<String, Boolean>>() {}.type
gson.fromJson<Map<String, Boolean>>(jsonString, type) ?: emptyMap()
} else {
emptyMap()
}
}.catch { e ->
Timber.e(e, "Failed to get or parse INFO_CHART_LINE_STATES. Emitting default.")
emit(emptyMap())
}
}
} }

View File

@@ -260,11 +260,9 @@ class MainActivity : ComponentActivity() {
// This prevents serial interrupts from stealing CPU during the first frame. // This prevents serial interrupts from stealing CPU during the first frame.
delay(200) delay(200)
// IMPORTANT:
// rxPacketLoop() starts serial open() asynchronously.
// Start RX first so txPacketOnce() is less likely to run before FD is ready.
vm.rxPacketLoop()
vm.txPacketOnce() vm.txPacketOnce()
vm.rxPacketLoop()
vm.txPacketLoop() vm.txPacketLoop()
Timber.d("System fully operational.") Timber.d("System fully operational.")

View File

@@ -439,15 +439,15 @@ fun ConfigScreen(
mainViewModel.saveGuideBeamToPreference() mainViewModel.saveGuideBeamToPreference()
} }
// Guide Beam step mapping (0~10): /*
// 0 -> fixed 0 val value = when(guideBeam.toInt()) {
// 1~10 -> min~max range in 10 steps (10 -> max) 0 -> 0
val step = guideBeam.toInt().coerceIn(0, 10) 1 -> guideBeamMin
val value = if (step == 0) { 10 -> guideBeamMax
0 else -> (guideBeamMin + (guideBeam.toInt() - 1) * ((guideBeamMax - guideBeamMin) / 9))
} else {
guideBeamMin + ((step-1) * (guideBeamMax - guideBeamMin) / 9)
} }
*/
val value = (guideBeamMin + (guideBeam.toInt() - 1) * ((guideBeamMax - guideBeamMin) / 9))
Timber.d("guideBeam: $value, guideBeamMax: $guideBeamMax, guideBeamMin: $guideBeamMin") Timber.d("guideBeam: $value, guideBeamMax: $guideBeamMax, guideBeamMin: $guideBeamMin")
mainViewModel.txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = value)) mainViewModel.txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = value))

View File

@@ -32,11 +32,11 @@ fun LifeTimeView(
) { ) {
Column(modifier = Modifier Column(modifier = Modifier
//.noRippleClickable(onClick = onClick) //.noRippleClickable(onClick = onClick)
.size(388.px.dp, 258.px.dp) .size(388.px.dp, 276.px.dp)
.clip(RoundedCornerShape(12.px.dp)) .clip(RoundedCornerShape(12.px.dp))
.border(width = 1.px.dp, color = Color(209, 209, 209), shape = RoundedCornerShape(10.px.dp)) .border(width = 1.px.dp, color = Color(209, 209, 209), shape = RoundedCornerShape(10.px.dp))
.background(Color.White) .background(Color.White)
.padding(3.px.dp, 16.px.dp), .padding(16.px.dp),
verticalArrangement = Arrangement.SpaceEvenly, verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
@@ -55,11 +55,11 @@ fun LifeTimeView(
), ),
) )
Spacer(modifier = Modifier.height(2.px.dp)) Spacer(modifier = Modifier.height(10.px.dp))
// Temp 0..7 // Temp 0..7
for (i in 0..lifeTimeTypes.size -1) { for (i in 0..lifeTimeTypes.size -1) {
val value = when (i) { val hour = when (i) {
0 -> lifeTime.lamp 0 -> lifeTime.lamp
1 -> lifeTime.hp5x5 1 -> lifeTime.hp5x5
2 -> lifeTime.hp7x7 2 -> lifeTime.hp7x7
@@ -70,35 +70,22 @@ fun LifeTimeView(
7 -> lifeTime.water 7 -> lifeTime.water
else -> 0 else -> 0
} }
val modifier = Modifier HourItemView(
modifier = Modifier
.fillMaxSize() .fillMaxSize()
.weight(1f) .weight(1f)
.padding( .padding(
start = 20.px.dp, start = 20.px.dp,
end = 20.px.dp, end = 20.px.dp,
//bottom = 10.px.dp //bottom = 10.px.dp
) ),
val title = lifeTimeTypes[i] title = lifeTimeTypes[i],
val onItemClick = { hour = hour,
Timber.d("onClick > Temp $i ($title)") onClick = {
Timber.d("onClick > Temp $i (${lifeTimeTypes[i]})")
onClick.invoke(i) onClick.invoke(i)
} }
if (i <= 5) {
CountItemView(
modifier = modifier,
title = title,
count = value,
onClick = onItemClick
) )
} else {
HourItemView(
modifier = modifier,
title = title,
hour = value,
onClick = onItemClick
)
}
if (i < lifeTimeTypes.size -1) { if (i < lifeTimeTypes.size -1) {
HorizontalDivider( HorizontalDivider(

View File

@@ -42,7 +42,7 @@ fun TemperatureView(
.clip(RoundedCornerShape(12.px.dp)) .clip(RoundedCornerShape(12.px.dp))
.border(width = 1.px.dp, color = Color(209, 209, 209), shape = RoundedCornerShape(10.px.dp)) .border(width = 1.px.dp, color = Color(209, 209, 209), shape = RoundedCornerShape(10.px.dp))
.background(Color.White) .background(Color.White)
.padding(3.px.dp, 16.px.dp), .padding(16.px.dp),
verticalArrangement = Arrangement.SpaceEvenly, verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
@@ -61,6 +61,8 @@ fun TemperatureView(
), ),
) )
Spacer(modifier = Modifier.height(10.px.dp))
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -87,8 +89,6 @@ fun TemperatureView(
Spacer(modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.weight(1f))
} }
Spacer(modifier = Modifier.height(2.px.dp))
// Tempearture // Tempearture
for (i in 0..temperatureTypes.size -1) { for (i in 0..temperatureTypes.size -1) {
val count1Value = when (i) { val count1Value = when (i) {

View File

@@ -35,7 +35,6 @@ import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import com.laseroptek.raman.const.LaserParameter import com.laseroptek.raman.const.LaserParameter
import com.laseroptek.raman.const.LASER_STATUS
import com.laseroptek.raman.const.LaserStatusType import com.laseroptek.raman.const.LaserStatusType
import com.laseroptek.raman.const.MAX_LASER_COUNT import com.laseroptek.raman.const.MAX_LASER_COUNT
import com.laseroptek.raman.const.PresetButtonType import com.laseroptek.raman.const.PresetButtonType
@@ -93,18 +92,10 @@ fun HomeScreen(
val presetList by mainViewModel.presetList.collectAsState() val presetList by mainViewModel.presetList.collectAsState()
LaunchedEffect(lampCount, lifeTime.lamp, laserStatus.laserStatus) { LaunchedEffect(Unit) {
Timber.d("LaunchedEffect - HomeScreen") Timber.d("LaunchedEffect - HomeScreen")
focusManager.clearFocus(force = true) // Hide the keyboard focusManager.clearFocus(force = true) // Hide the keyboard
// Ensure the system returns to StandBy when lamp thresholds are exceeded
val lampLifetimeLimit = lifeTime.lamp
val reachedLifetimeLimit = lampLifetimeLimit > 0 && lampCount >= lampLifetimeLimit
if (reachedLifetimeLimit && laserStatus.laserStatus != LASER_STATUS.STAND_BY) {
Timber.d("HomeScreen load - forcing StandBy state due to lamp count limit")
mainViewModel.txLaserStatusEntry(LASER_STATUS.STAND_BY)
}
Timber.d("Attempted to hide keyboard on EngineerScreen launch") Timber.d("Attempted to hide keyboard on EngineerScreen launch")
} }
@@ -491,18 +482,6 @@ fun HomeScreen(
return@StandByButton return@StandByButton
} }
val lampLifetimeLimit = lifeTime.lamp
if (lampLifetimeLimit > 0 && lampCount >= lampLifetimeLimit) {
Toast.makeText(
context,
"Lamp lifetime limit reached",
Toast.LENGTH_SHORT
).show()
return@StandByButton
}
val hpCount = mainViewModel.getHPCount() val hpCount = mainViewModel.getHPCount()
if (hpCount < 1) { if (hpCount < 1) {
Toast.makeText( Toast.makeText(

View File

@@ -334,7 +334,7 @@ fun DcdSettingPopup(
modifier = Modifier modifier = Modifier
.fillMaxHeight() .fillMaxHeight()
.size(40.px.dp, 210.px.dp), .size(40.px.dp, 210.px.dp),
chargeRate = gasChargeRate chargeRate = gasChargeRate.toInt()
) )
// Icon // Icon

View File

@@ -28,26 +28,14 @@ import com.laseroptek.raman.ui.screens.main.MainViewModel
import com.laseroptek.raman.utils.DefaultDispatcherProvider import com.laseroptek.raman.utils.DefaultDispatcherProvider
import com.laseroptek.raman.utils.ext.px import com.laseroptek.raman.utils.ext.px
import timber.log.Timber import timber.log.Timber
import kotlin.math.abs
import kotlin.math.ceil
@Composable @Composable
fun GradientSlider( fun GradientSlider(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
chargeRate: Float = 0f, chargeRate: Int = 0, // Value from (0 .. 100)
) { ) {
val normalizedRate = chargeRate.coerceIn(0f, 100f) val chargeIndex = ((chargeRate.coerceIn(0, 100) + 4) / 5).toInt() // 0..19
val bucket = normalizedRate / 5f
val remainder = normalizedRate % 5f
val isExactMultiple = abs(remainder) < 0.0001f
val chargeIndex = when {
normalizedRate == 0f -> -1
isExactMultiple -> (bucket - 1f).toInt().coerceAtLeast(-1)
else -> (ceil(bucket.toDouble()).toInt() - 1)
}.coerceIn(-1, 19)
Timber.d("chargeRate: $chargeRate, chargeIndex: $chargeIndex") Timber.d("chargeRate: $chargeRate, chargeIndex: $chargeIndex")
Box( Box(
@@ -115,6 +103,6 @@ fun GradientSliderPreview(
//mainViewModel = mainViewModel //mainViewModel = mainViewModel
modifier = Modifier modifier = Modifier
.size(40.px.dp, 210.px.dp), .size(40.px.dp, 210.px.dp),
chargeRate = 20f chargeRate = 20
) )
} }

View File

@@ -108,15 +108,15 @@ fun PresetIconButton(
Image( Image(
painter = painterResource(id = painter = painterResource(id =
if (type == PresetButtonType.SAVE) { if (type == PresetButtonType.SAVE) {
R.drawable.ic_preset_save2 R.drawable.ic_preset_save
} else { } else {
R.drawable.ic_preset_load R.drawable.ic_preset_load
} }
), ),
contentDescription = "", contentDescription = "",
modifier = Modifier modifier = Modifier
.size(30.px.dp), .size(20.px.dp),
contentScale = ContentScale.Fit contentScale = ContentScale.Crop
) )
} }
} }

View File

@@ -552,12 +552,12 @@ fun PresetLoadPopup(
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Spacer(Modifier.weight(1f))
if (isEditMode) { if (isEditMode) {
//////////////////////////////////////////////////// ////////////////////////////////////////////////////
// Edit Mode // Edit Mode
Spacer(modifier = Modifier.width(10.px.dp))
// Preset Delete (Delete confirm popup) // Preset Delete (Delete confirm popup)
Box( Box(
modifier = Modifier modifier = Modifier
@@ -578,7 +578,7 @@ fun PresetLoadPopup(
) )
} }
Spacer(Modifier.weight(1f)) Spacer(Modifier.width(10.px.dp))
// Preset Cancel (Reload selected item from mainViewModel) // Preset Cancel (Reload selected item from mainViewModel)
Box( Box(
@@ -646,7 +646,7 @@ fun PresetLoadPopup(
Timber.d("onClick - Confirm Save") Timber.d("onClick - Confirm Save")
// Check empty names and conflict priority exist in the preset viewmodel's presetList // Check empty names and conflict priority exist in the preset viewmodel's presetList
var listToValidate = presetViewModel.presetList.value val listToValidate = presetViewModel.presetList.value
// Check for any presets with an empty name // Check for any presets with an empty name
val hasEmptyName = val hasEmptyName =
@@ -678,32 +678,18 @@ fun PresetLoadPopup(
} }
// Check for duplicate priorities (ignoring priority 0) // Check for duplicate priorities (ignoring priority 0)
val duplicatePriorityGroups = listToValidate val priorityConflicts = listToValidate
.filter { it.priority > 0 } .filter { it.priority > 0 } // Only consider prioritized items
.groupBy { it.priority } .groupBy { it.priority } // Group them by priority
.filter { it.value.size > 1 } .any { it.value.size > 1 } // Check if any group is larger than 1
if (duplicatePriorityGroups.isNotEmpty()) { if (priorityConflicts) {
val resolvedList = listToValidate.map { it.copy() }.toMutableList() Toast.makeText(
val selectedPreset = resolvedList.getOrNull(selectedPresetIndex) context,
"There are duplicate priorities. Please ensure each priority is unique.",
duplicatePriorityGroups.forEach { (priorityValue, presets) -> Toast.LENGTH_LONG
val keeperId = presets ).show()
.firstOrNull { preset -> return@noRippleClickable // Stop the process
selectedPreset != null && preset.id == selectedPreset.id
}
?.id
?: presets.first().id
resolvedList.forEachIndexed { index, preset ->
if (preset.priority == priorityValue && preset.id != keeperId) {
resolvedList[index] = preset.copy(priority = 0)
}
}
}
presetViewModel.setPresetList(resolvedList)
listToValidate = resolvedList
} }
Timber.d("Validation successful. Saving list to MainViewModel.") Timber.d("Validation successful. Saving list to MainViewModel.")
@@ -743,11 +729,7 @@ fun PresetLoadPopup(
contentScale = ContentScale.Crop contentScale = ContentScale.Crop
) )
} }
Spacer(modifier = Modifier.width(10.px.dp))
} else { } else {
Spacer(Modifier.weight(1f))
//////////////////////////////////////////////////// ////////////////////////////////////////////////////
// Select Mode - hide Keyboard // Select Mode - hide Keyboard
focusManager.clearFocus(force = true) // Hide the keyboard focusManager.clearFocus(force = true) // Hide the keyboard
@@ -808,8 +790,6 @@ fun PresetLoadPopup(
contentScale = ContentScale.Crop contentScale = ContentScale.Crop
) )
} }
Spacer(modifier = Modifier.width(10.px.dp))
} }
} }

View File

@@ -1,14 +1,10 @@
package com.laseroptek.raman.ui.screens.info package com.laseroptek.raman.ui.screens.info
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import com.laseroptek.raman.repository.PreferenceRepository
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@@ -29,13 +25,10 @@ data class ChartUiState(
val chamber2State: Boolean = true, val chamber2State: Boolean = true,
val basePlateState: Boolean = true, val basePlateState: Boolean = true,
val waterState: Boolean = true, val waterState: Boolean = true,
) { )
companion object
}
@HiltViewModel @HiltViewModel
class InfoViewModel @Inject constructor( class InfoViewModel @Inject constructor(
private val preferenceRepository: PreferenceRepository,
) : ViewModel() { ) : ViewModel() {
// This is the single source of truth for the checkbox states. // This is the single source of truth for the checkbox states.
@@ -46,7 +39,7 @@ class InfoViewModel @Inject constructor(
fun toggleLine(line: ChartLine) { fun toggleLine(line: ChartLine) {
// .update is a thread-safe way to update the state. // .update is a thread-safe way to update the state.
_chartUiState.update { currentState -> _chartUiState.update { currentState ->
val updatedState = when (line) { when (line) {
ChartLine.INT_TEMP -> currentState.copy(intTempState = !currentState.intTempState) ChartLine.INT_TEMP -> currentState.copy(intTempState = !currentState.intTempState)
ChartLine.EXT_TEMP -> currentState.copy(extTempState = !currentState.extTempState) ChartLine.EXT_TEMP -> currentState.copy(extTempState = !currentState.extTempState)
ChartLine.INT_HUMIDITY -> currentState.copy(intHumidityState = !currentState.intHumidityState) ChartLine.INT_HUMIDITY -> currentState.copy(intHumidityState = !currentState.intHumidityState)
@@ -57,51 +50,10 @@ class InfoViewModel @Inject constructor(
ChartLine.BASE_PLATE -> currentState.copy(basePlateState = !currentState.basePlateState) ChartLine.BASE_PLATE -> currentState.copy(basePlateState = !currentState.basePlateState)
ChartLine.WATER -> currentState.copy(waterState = !currentState.waterState) ChartLine.WATER -> currentState.copy(waterState = !currentState.waterState)
} }
persistChartUiState(updatedState)
updatedState
} }
} }
init { init {
Timber.d("InfoViewModel init") Timber.d("InfoViewModel init")
viewModelScope.launch {
preferenceRepository.getInfoChartLineStates().collectLatest { savedStates ->
if (savedStates.isEmpty()) return@collectLatest
_chartUiState.update { ChartUiState.fromPreference(savedStates) }
} }
} }
}
private fun persistChartUiState(state: ChartUiState) {
viewModelScope.launch {
preferenceRepository.saveInfoChartLineStates(state.toPreferenceMap())
}
}
}
private fun ChartUiState.toPreferenceMap(): Map<String, Boolean> = mapOf(
ChartLine.INT_TEMP.name to intTempState,
ChartLine.EXT_TEMP.name to extTempState,
ChartLine.INT_HUMIDITY.name to intHumidityState,
ChartLine.EXT_HUMIDITY.name to extHumidityState,
ChartLine.KTP.name to ktpState,
ChartLine.CHAMBER1.name to chamber1State,
ChartLine.CHAMBER2.name to chamber2State,
ChartLine.BASE_PLATE.name to basePlateState,
ChartLine.WATER.name to waterState,
)
private fun ChartUiState.Companion.fromPreference(savedStates: Map<String, Boolean>): ChartUiState {
val defaults = ChartUiState()
return ChartUiState(
intTempState = savedStates[ChartLine.INT_TEMP.name] ?: defaults.intTempState,
extTempState = savedStates[ChartLine.EXT_TEMP.name] ?: defaults.extTempState,
intHumidityState = savedStates[ChartLine.INT_HUMIDITY.name] ?: defaults.intHumidityState,
extHumidityState = savedStates[ChartLine.EXT_HUMIDITY.name] ?: defaults.extHumidityState,
ktpState = savedStates[ChartLine.KTP.name] ?: defaults.ktpState,
chamber1State = savedStates[ChartLine.CHAMBER1.name] ?: defaults.chamber1State,
chamber2State = savedStates[ChartLine.CHAMBER2.name] ?: defaults.chamber2State,
basePlateState = savedStates[ChartLine.BASE_PLATE.name] ?: defaults.basePlateState,
waterState = savedStates[ChartLine.WATER.name] ?: defaults.waterState,
)
}

View File

@@ -583,22 +583,22 @@ class MainViewModel @Inject constructor(
saveGuideBeamMinToPreference() saveGuideBeamMinToPreference()
saveGuideBeamMaxToPreference() saveGuideBeamMaxToPreference()
// Engineer 화면에서는 Min/Max 버튼에 따라 표시된 Min 또는 Max 값을 그대로 송신 // After updating the state, send the packet
val newMin = guideBeamMin.value val newMin = guideBeamMin.value // get the potentially updated value
val newMax = guideBeamMax.value val newMax = guideBeamMax.value // get the potentially updated value
val value = when (state) { val guideBeam = guideBeam.value.toInt()
MinMaxUpDownState.MinDown,
MinMaxUpDownState.MinUp,
MinMaxUpDownState.MinLongDown,
MinMaxUpDownState.MinLongUp -> newMin
MinMaxUpDownState.MaxDown, /*
MinMaxUpDownState.MaxUp, val value = when(guideBeamValue) {
MinMaxUpDownState.MaxLongDown, 0 -> 0
MinMaxUpDownState.MaxLongUp -> newMax 1 -> newMin
10 -> newMax
else -> (newMin + (guideBeamValue - 1) * ((newMax - newMin) / 9))
} }
*/
val value = (newMin + (guideBeam - 1) * ((newMax - newMin) / 9))
Timber.d("Engineer guideBeam tx value: $value, guideBeamMax: $newMax, guideBeamMin: $newMin") Timber.d("guideBeam: $value, guideBeam: $guideBeam, guideBeamMax: $newMax, guideBeamMin: $newMin")
txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = value)) txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = value))
} }
@@ -814,15 +814,6 @@ class MainViewModel @Inject constructor(
} }
fun txPacketOnce() { fun txPacketOnce() {
viewModelScope.launch(dispatcherProvider.io) {
// txPacketOnce is called during app startup.
// Because serial open() is started in rxPacketLoop() asynchronously,
// FD can still be -1 here (startup race). Wait briefly before first TX burst.
if (!waitUntilSerialReady()) {
Timber.e("txPacketOnce skipped: serial port is not ready (fd=%d)", serialPortRepository.getFD())
return@launch
}
// viewModel init 으로 이동. 필요. // viewModel init 으로 이동. 필요.
// 경고 정보 조회 (주기적 heart beat) // 경고 정보 조회 (주기적 heart beat)
// repeatOnLifecycle은 Activity가 포그라운드에 있을 때로 한정지어, 특정 Lifecycle이 Trigger 되었을 때 동작하도록 만드는 block 임. // repeatOnLifecycle은 Activity가 포그라운드에 있을 때로 한정지어, 특정 Lifecycle이 Trigger 되었을 때 동작하도록 만드는 block 임.
@@ -834,7 +825,7 @@ class MainViewModel @Inject constructor(
txPacket(READ_WRITE.WRITE, CMD.Q_SWITCH, qSwitch.value) txPacket(READ_WRITE.WRITE, CMD.Q_SWITCH, qSwitch.value)
// tx Guide Beam Write // tx Guide Beam Write
txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = getGuideBeamTxValue())) txPacket(READ_WRITE.WRITE, CMD.GUIDE_BEAM, GuideBeam(value = guideBeam.value.toInt()))
// tx DCD_GAS Write (DEFAULT VALUE) // tx DCD_GAS Write (DEFAULT VALUE)
txPacket(READ_WRITE.WRITE, CMD.DCD_GAS, dcdGas.value.copy(status = 0x50)) txPacket(READ_WRITE.WRITE, CMD.DCD_GAS, dcdGas.value.copy(status = 0x50))
@@ -842,32 +833,6 @@ class MainViewModel @Inject constructor(
// tx SPRAY_DCD Write (DEFAULT VALUE) // tx SPRAY_DCD Write (DEFAULT VALUE)
txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, sprayDcd.value) txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, sprayDcd.value)
} }
}
private suspend fun waitUntilSerialReady(
timeoutMillis: Long = 2000L,
pollIntervalMillis: Long = 20L
): Boolean {
// Poll FD until open() completes, with a bounded timeout to avoid blocking forever.
val start = System.currentTimeMillis()
while (System.currentTimeMillis() - start < timeoutMillis) {
if (serialPortRepository.getFD() != -1) return true
delay(pollIntervalMillis)
}
return serialPortRepository.getFD() != -1
}
// Guide Beam step mapping (0~10)
// 0 -> fixed 0
// 1~10 -> min~max range in 10 steps (10 -> max)
private fun getGuideBeamTxValue(): Int {
val step = guideBeam.value.toInt().coerceIn(0, 10)
return if (step == 0) {
0
} else {
guideBeamMin.value + ((step - 1) * (guideBeamMax.value - guideBeamMin.value) / 9)
}
}
// Example: Emitting an event after a delay // Example: Emitting an event after a delay
fun txPacketLoop() { fun txPacketLoop() {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,53 +0,0 @@
# 변경 요약 (2026-03-04)
이 문서는 현재 `git diff` 기준으로 반영된 변경을 정리합니다.
## 1) 시리얼 초기 전송 누락(Startup race) 대응
### 변경 파일
- `app/src/main/java/com/laseroptek/raman/ui/MainActivity.kt`
- `app/src/main/java/com/laseroptek/raman/ui/screens/main/MainViewModel.kt`
### 변경 내용
- `MainActivity.initialize()`의 시리얼 시작 순서를 조정
- 이전: `txPacketOnce()` -> `rxPacketLoop()` -> `txPacketLoop()`
- 이후: `rxPacketLoop()` -> `txPacketOnce()` -> `txPacketLoop()`
- `MainViewModel.txPacketOnce()`를 코루틴(IO)에서 실행하도록 변경
- `waitUntilSerialReady()` 추가
- 최대 2초 동안 20ms 간격으로 `FD != -1` 확인
- 준비 실패 시 에러 로그 후 초기 TX 중단
- 관련 설명 주석 추가
### 의도/효과
- 앱 시작 직후 `open()` 완료 전 TX가 먼저 발생하는 레이스를 완화/방어
- 포트 미준비 상태(`FD == -1`)에서 write가 호출되어 초기 패킷이 누락되는 문제를 줄임
## 2) HandPiece 기본값 변경
### 변경 파일
- `app/src/main/java/com/laseroptek/raman/data/model/serial/HandPiece.kt`
### 변경 내용
- `HandPiece.type` 기본값 변경
- 이전: `1`
- 이후: `0`
### 영향 포인트
- 기본 인스턴스 생성 시 handpiece type의 초기 상태가 달라집니다.
- 초기 테이블 선택/상태 표시 로직에서 기본 타입 가정이 있다면 함께 점검 필요합니다.
## 3) 문서화
### 추가/수정 파일
- `docs/serial_tx_startup_race.md` (신규)
- `README.md` (Troubleshooting 링크 추가)
### 내용
- FD(File Descriptor) 개념
- startup race 원인 및 수정 내역
- 왜 TX에서 직접 open하지 않았는지
- 확인 포인트
## 4) 참고
- 현재 요약은 커밋 로그가 아닌 워크트리 `git diff` 기준입니다.
- 빌드 검증은 `gradlew` CRLF 문제로 로컬 셸에서 미실행 상태입니다.

View File

@@ -1,41 +0,0 @@
# Serial TX Startup Race 정리
## 1) FD(File Descriptor)란?
- `FD`는 리눅스/안드로이드에서 열린 리소스(파일/소켓/시리얼 포트)를 가리키는 정수 핸들입니다.
- 이 프로젝트에서 시리얼 포트 상태는 다음처럼 판단합니다.
- `FD == -1`: 포트 미오픈(유효하지 않음)
- `FD >= 0`: 포트 오픈 완료(유효)
- 따라서 `FD == -1` 상태에서 `write()`를 호출하면 실제 시리얼 전송이 되지 않습니다.
## 2) 문제 원인
- `txPacketOnce()`가 앱 시작 직후 실행됩니다.
- 시리얼 포트 `open()``rxPacketLoop()` 내부에서 코루틴으로 비동기 시작됩니다.
- 기존 순서에서 `txPacketOnce()`가 먼저 호출되면, 포트 오픈 완료 전(`FD == -1`)에 TX가 시도되어 초기 패킷 전송이 누락될 수 있습니다.
## 3) 적용한 수정
### A. 초기 호출 순서 조정
- 파일: `app/src/main/java/com/laseroptek/raman/ui/MainActivity.kt`
- 변경:
- 이전: `txPacketOnce()` -> `rxPacketLoop()` -> `txPacketLoop()`
- 이후: `rxPacketLoop()` -> `txPacketOnce()` -> `txPacketLoop()`
- 목적: RX 루프가 먼저 포트 오픈을 시작하도록 해서 초기 TX 레이스 확률을 줄임
### B. `txPacketOnce()`에 포트 준비 대기 추가
- 파일: `app/src/main/java/com/laseroptek/raman/ui/screens/main/MainViewModel.kt`
- 변경:
- `txPacketOnce()`를 IO 코루틴에서 실행
- `waitUntilSerialReady()`(최대 2초, 20ms 폴링)로 `FD != -1` 확인 후 TX 진행
- 시간 내 준비 실패 시 로그를 남기고 전송 중단
- 목적: 순서만으로 보장되지 않는 코루틴 스케줄링 레이스를 방어
## 4) 왜 TX에서 직접 open()하지 않았는가?
- 현재 구조에서 `open()`의 데이터 콜백은 `rxPacketLoop()``callbackFlow`와 연결됩니다.
- TX 경로에서 별도 `open()`을 하면 중복 오픈/콜백 소유권/FD 교체 타이밍 이슈가 생길 수 있습니다.
- 안정적인 패턴은:
- 포트 오픈 책임: RX(단일 지점)
- 포트 사용(TX): ready 확인 후 write
## 5) 확인 포인트
- 앱 시작 직후 로그에서 `FD`가 유효해진 뒤 `txPacketOnce()`의 TX 로그가 출력되는지 확인
- 장비 측 시리얼 모니터에서 초기 패킷(Version/Q-Switch/GuideBeam/DCD/SprayDCD) 수신 여부 확인