1 Commits

Author SHA1 Message Date
areumwoo
ad5077db69 feat: #72 Read/Write 표시 위치 수정 미적용 2026-03-02 10:27:56 +09:00
28 changed files with 193 additions and 810 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

@@ -9,7 +9,7 @@ package com.laseroptek.raman.const
val HzTable_10_10 = mapOf( val HzTable_10_10 = mapOf(
// Pulse Width = 0.5f // Pulse Width = 0.5f
Pair(0.5f, 0.5f) to KEY_GREEN, Pair(0.5f, 0.5f) to KEY_BLUE,
Pair(0.5f, 0.6f) to KEY_BLUE, Pair(0.5f, 0.6f) to KEY_BLUE,
Pair(0.5f, 0.7f) to KEY_BLUE, Pair(0.5f, 0.7f) to KEY_BLUE,
Pair(0.5f, 0.8f) to KEY_BLUE, Pair(0.5f, 0.8f) to KEY_BLUE,

View File

@@ -24,7 +24,7 @@ val HzTable_5_5 = mapOf(
Pair(0.5f,3.4f) to KEY_BLUE, Pair(0.5f,3.4f) to KEY_BLUE,
Pair(0.5f,3.6f) to KEY_BLUE, Pair(0.5f,3.6f) to KEY_BLUE,
Pair(0.5f,3.8f) to KEY_BLUE, Pair(0.5f,3.8f) to KEY_BLUE,
Pair(0.5f,4.0f) to KEY_BLUE, Pair(0.5f,4.0f) to KEY_YELLOW,
Pair(0.5f,4.2f) to KEY_YELLOW, Pair(0.5f,4.2f) to KEY_YELLOW,
Pair(0.5f,4.4f) to KEY_YELLOW, Pair(0.5f,4.4f) to KEY_YELLOW,
Pair(0.5f,4.6f) to KEY_YELLOW, Pair(0.5f,4.6f) to KEY_YELLOW,

View File

@@ -108,7 +108,7 @@ val HzTable_7_7 = mapOf(
Pair(1.5f, 8.0f) to KEY_GRAY, Pair(1.5f, 8.0f) to KEY_GRAY,
// Pulse Width = 3f // Pulse Width = 3f
Pair(3f, 1.1f) to KEY_GRAY, Pair(3f, 1.1f) to KEY_RED,
Pair(3f, 1.2f) to KEY_GRAY, Pair(3f, 1.2f) to KEY_GRAY,
Pair(3f, 1.3f) to KEY_GRAY, Pair(3f, 1.3f) to KEY_GRAY,
Pair(3f, 1.4f) to KEY_GRAY, Pair(3f, 1.4f) to KEY_GRAY,

View File

@@ -61,7 +61,7 @@ const val MAX_Q_SWITCH_VALUE = 250.0f
const val MAX_REFER1_VALUE = 99999999 // 8 byte ascii (ENERGY DETECT MEASURED VALUE) const val MAX_REFER1_VALUE = 99999999 // 8 byte ascii (ENERGY DETECT MEASURED VALUE)
const val DEFAULT_REFER1_VALUE = 0 // initial state const val DEFAULT_REFER1_VALUE = 0 // initial state
const val DEFAULT_DCD_GAS_PRESSURE = 08.0f const val DEFAULT_DCD_GAS_PRESSURE = 06.5f
const val DEFAULT_SPAY_DCD_TIME = 10 const val DEFAULT_SPAY_DCD_TIME = 10
const val DEFAULT_SPAY_DCD_DELAY = 10 const val DEFAULT_SPAY_DCD_DELAY = 10
@@ -461,17 +461,17 @@ val dcdLifeSpanAdjustLists = listOf( 0.5f, 0.7f, 0.9f, 1.0f, 1.1f, 1.2f )
val dcdLifeSpanAdjustStringLists = dcdLifeSpanAdjustLists.map{ it.toString() } val dcdLifeSpanAdjustStringLists = dcdLifeSpanAdjustLists.map{ it.toString() }
val dcdSprayValues = listOf(10, 20, 30, 40, 50, 60, 70, 80, 90, 100).map{ it.toString() } val dcdSprayValues = listOf(10, 20, 30, 40, 50, 60, 70, 80, 90, 100).map{ it.toString() }
val dcdDelayValues = listOf(10, 20, 30, 40).map{ it.toString() } val dcdDelayValues = listOf(10, 20, 30, 40, 50, 60, 70, 80, 90, 100).map{ it.toString() }
// default spray dcd list for options // default spray dcd list for options
val SprayDcdList = listOf<SprayDcd>( val SprayDcdList = listOf<SprayDcd>(
SprayDcd(status = 0x41, sprayTime = 10, sprayDelay = 10), // default SprayDcd(status = 0x44, sprayTime = 10, sprayDelay = 10), // default
SprayDcd(status = 0x41, sprayTime = 10, sprayDelay = 10), SprayDcd(status = 0x44, sprayTime = 10, sprayDelay = 10),
SprayDcd(status = 0x41, sprayTime = 20, sprayDelay = 10), SprayDcd(status = 0x44, sprayTime = 20, sprayDelay = 20),
SprayDcd(status = 0x41, sprayTime = 30, sprayDelay = 20), SprayDcd(status = 0x44, sprayTime = 30, sprayDelay = 20),
SprayDcd(status = 0x41, sprayTime = 40, sprayDelay = 20), SprayDcd(status = 0x44, sprayTime = 40, sprayDelay = 40),
SprayDcd(status = 0x41, sprayTime = 50, sprayDelay = 30), SprayDcd(status = 0x44, sprayTime = 50, sprayDelay = 50),
SprayDcd(status = 0x41, sprayTime = 60, sprayDelay = 30), SprayDcd(status = 0x44, sprayTime = 60, sprayDelay = 60),
) )
val PresetList = listOf<Preset>( val PresetList = listOf<Preset>(

View File

@@ -3,7 +3,7 @@ package com.laseroptek.raman.data.model.serial
import com.laseroptek.raman.const.DEFAULT_DCD_GAS_PRESSURE import com.laseroptek.raman.const.DEFAULT_DCD_GAS_PRESSURE
data class DcdGas( data class DcdGas(
val status: Int = 0x50, // 1Byte(A(0x41): on, D(0x44): off, P(0x50): pressure) val status: Int = 0x41, // 1Byte(A(0x41): on, D(0x44): off, P(0x50): pressure)
val pressure: Float = DEFAULT_DCD_GAS_PRESSURE, // Ascii 4Byte (xx.x): Pressure val pressure: Float = DEFAULT_DCD_GAS_PRESSURE, // Ascii 4Byte (xx.x): Pressure
val ok: Int = 0x00, // 1Byte(N(0x4E): Not OK, O(0x00F): OK)/ val ok: Int = 0x00, // 1Byte(N(0x4E): Not OK, O(0x00F): OK)/
) )

View File

@@ -1,5 +1,5 @@
package com.laseroptek.raman.data.model.serial package com.laseroptek.raman.data.model.serial
data class HandPiece( data class HandPiece(
val type:Int = 0 // ascii (00 ~ 99) val type:Int = 1 // ascii (00 ~ 99)
) )

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")
} }
@@ -304,7 +295,7 @@ fun HomeScreen(
pulseType = pulseType, pulseType = pulseType,
handPieceType = handPiece.type, handPieceType = handPiece.type,
type = LaserStatusType.REPETITION, type = LaserStatusType.REPETITION,
angle = if (pulseType == 0 || repetitionList.isEmpty()) 0f else repetitionAngle, angle = if (pulseType == 0 || repetitionList.size < 2) 0f else repetitionAngle,
onChange = { angle -> onChange = { angle ->
if (handPiece.type == 0) { if (handPiece.type == 0) {
Toast.makeText( Toast.makeText(
@@ -315,7 +306,7 @@ fun HomeScreen(
return@LaserControlView return@LaserControlView
} }
if (pulseType == 0 || repetitionList.isEmpty()) { if (pulseType == 0 || repetitionList.size < 2) {
//Toast.makeText(context, "Single pulse type (0 Hz)", Toast.LENGTH_SHORT).show() //Toast.makeText(context, "Single pulse type (0 Hz)", Toast.LENGTH_SHORT).show()
} else { } else {
mainViewModel.onChangeRepetition(angle) mainViewModel.onChangeRepetition(angle)
@@ -332,7 +323,7 @@ fun HomeScreen(
return@LaserControlView return@LaserControlView
} }
if (pulseType == 0 || repetitionList.isEmpty()) { if (pulseType == 0 || repetitionList.size < 2) {
//Toast.makeText(context, "Single pulse type (0 Hz)", Toast.LENGTH_SHORT).show() //Toast.makeText(context, "Single pulse type (0 Hz)", Toast.LENGTH_SHORT).show()
} else { } else {
//mainViewModel.onClickRepetition(state) //mainViewModel.onClickRepetition(state)
@@ -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

@@ -256,11 +256,7 @@ fun DcdSettingPopup(
mainViewModel.setSelectedSprayDcdIndex(i) mainViewModel.setSelectedSprayDcdIndex(i)
val optionValue = mainViewModel.sprayDcdList[i] val optionValue = mainViewModel.sprayDcdList[i]
mainViewModel.setSprayDcd(optionValue) mainViewModel.setSprayDcd(optionValue)
mainViewModel.txPacket( mainViewModel.txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, optionValue)
READ_WRITE.WRITE,
CMD.SPRAY_DCD,
optionValue.copy(status = 0x41)
)
scope.launch { scope.launch {
mainViewModel.saveSprayDcdIndexToPreference() mainViewModel.saveSprayDcdIndexToPreference()
@@ -307,11 +303,7 @@ fun DcdSettingPopup(
mainViewModel.setSelectedSprayDcdIndex(i) mainViewModel.setSelectedSprayDcdIndex(i)
val optionValue = mainViewModel.sprayDcdList[i] val optionValue = mainViewModel.sprayDcdList[i]
mainViewModel.setSprayDcd(optionValue) mainViewModel.setSprayDcd(optionValue)
mainViewModel.txPacket( mainViewModel.txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, optionValue)
READ_WRITE.WRITE,
CMD.SPRAY_DCD,
optionValue.copy(status = 0x41)
)
scope.launch { scope.launch {
mainViewModel.saveSprayDcdToPreference() mainViewModel.saveSprayDcdToPreference()
@@ -342,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
@@ -611,12 +603,6 @@ fun DcdSettingPopup(
sprayDcd sprayDcd
) )
mainViewModel.txPacket(
READ_WRITE.WRITE,
CMD.SPRAY_DCD,
sprayDcd.copy(status = 0x41)
)
mainViewModel.setSelectedSprayDcdIndex( selectedSprayDcdIndex ) mainViewModel.setSelectedSprayDcdIndex( selectedSprayDcdIndex )
//mainViewModel.setSprayDcdList( mainViewModel.sprayDcdList ) //mainViewModel.setSprayDcdList( mainViewModel.sprayDcdList )

View File

@@ -97,7 +97,7 @@ fun DcdView(
Column( Column(
modifier = Modifier modifier = Modifier
.width(55.px.dp) .width(45.px.dp)
.fillMaxHeight() .fillMaxHeight()
, horizontalAlignment = Alignment.CenterHorizontally , horizontalAlignment = Alignment.CenterHorizontally
, verticalArrangement = Arrangement.Center , verticalArrangement = Arrangement.Center
@@ -120,7 +120,7 @@ fun DcdView(
) )
} }
Spacer( Modifier.width(5.px.dp)) Spacer( Modifier.width(10.px.dp))
VerticalDivider( VerticalDivider(
color = Color(161,161,170), color = Color(161,161,170),
@@ -128,7 +128,7 @@ fun DcdView(
modifier = Modifier.size(1.px.dp, 30.px.dp) modifier = Modifier.size(1.px.dp, 30.px.dp)
) )
Spacer( Modifier.width(5.px.dp)) Spacer( Modifier.width(10.px.dp))
// Delay // Delay
Timber.d("selectedSprayDcdIndex.value: ${selectedSprayDcdIndex}") Timber.d("selectedSprayDcdIndex.value: ${selectedSprayDcdIndex}")

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
@@ -780,25 +762,21 @@ fun PresetLoadPopup(
.noRippleClickable(onClick = { .noRippleClickable(onClick = {
Timber.d("onClick - Preset Load") Timber.d("onClick - Preset Load")
val selectedPreset = presetViewModel.getPreset(selectedPresetIndex) val selectedPreset =
if (selectedPreset == null) { presetViewModel.getPreset(selectedPresetIndex)
Timber.w("onClick - Preset Load: selectedPreset is null. index=$selectedPresetIndex") val priority =
return@noRippleClickable selectedPreset?.priority ?: 0
}
val priority = selectedPreset.priority
Timber.d("onClick - Preset Load ($priority)") Timber.d("onClick - Preset Load ($priority)")
if (priority > 0) { // if (priority > 0) { // TODO : 검증 필요
mainViewModel.setSelectedPresetIndex( priority ) mainViewModel.setSelectedPresetIndex( priority )
mainViewModel.applyPreset(priority) mainViewModel.applyPreset(priority)
} else {
// 우선순위가 NONE인 경우, 인덱스 설정 X
mainViewModel.setSelectedPresetIndex(0)
mainViewModel.applyPreset(selectedPreset)
}
presetViewModel.clearPreset() presetViewModel.clearPreset()
onClick.invoke(false) onClick.invoke(false)
// } else {
// Timber.d("SKIP - Preset Load ($priority)")
// }
}) })
.size(40.px.dp) .size(40.px.dp)
.background(Color.Transparent) .background(Color.Transparent)
@@ -812,8 +790,6 @@ fun PresetLoadPopup(
contentScale = ContentScale.Crop contentScale = ContentScale.Crop
) )
} }
Spacer(modifier = Modifier.width(10.px.dp))
} }
} }

View File

@@ -28,7 +28,6 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import kotlin.math.abs
import javax.inject.Inject import javax.inject.Inject
@HiltViewModel @HiltViewModel
@@ -81,49 +80,6 @@ class PresetViewModel @Inject constructor(
_repetitionList.value = r _repetitionList.value = r
} }
private data class ResolvedRepetitionContext(
val fluence: Float,
val repetitionOptions: List<Float>,
)
private fun resolveRepetitionContext(
pulseWidth: Float,
fluence: Float,
): ResolvedRepetitionContext {
val availableFluenceList = energyTable.value.getKey2ListForKey1(pulseWidth)
val resolvedFluence = availableFluenceList.minByOrNull { abs(it - fluence) }
?: availableFluenceList.firstOrNull()
?: fluence
val hzType = hzTable.value.getValue(pulseWidth, resolvedFluence)
val repetitionOptions = RepetitionsByColorKey[hzType] ?: RepetitionsByColorKey[KEY_YELLOW].orEmpty()
if (hzType == null) {
Timber.w(
"No hzType found for pulseWidth=%s, fluence=%s. Falling back to default repetition list.",
pulseWidth,
resolvedFluence
)
}
setRepetitionList(repetitionOptions)
return ResolvedRepetitionContext(
fluence = resolvedFluence,
repetitionOptions = repetitionOptions,
)
}
private fun resolveNearestLowerOrEqualRepetition(
currentRepetition: Float,
repetitionOptions: List<Float>,
): Float {
return repetitionOptions
.filter { it <= currentRepetition }
.maxOrNull()
?: repetitionOptions.minOrNull()
?: currentRepetition
}
fun loadHzTable(handPieceType: Int) { fun loadHzTable(handPieceType: Int) {
Timber.d("loadHzTable($handPieceType)") Timber.d("loadHzTable($handPieceType)")
@@ -295,17 +251,21 @@ class PresetViewModel @Inject constructor(
// 4. fluence update (energyTable) // 4. fluence update (energyTable)
val newFluenceList = energyTable.value.getKey2ListForKey1(newPulseWidth) val newFluenceList = energyTable.value.getKey2ListForKey1(newPulseWidth)
val newFluence = newFluenceList.firstOrNull() ?: currentList[index].fluence val newFluence = newFluenceList.get(0)
// 5. repetition update (hzTable) // 5. repetition update (hzTable)
val repetitionContext = resolveRepetitionContext(newPulseWidth, newFluence) val hzType = hzTable.value.getValue(newPulseWidth, newFluence)
Timber.d("Resolved repetition options for handPieceType update: ${repetitionContext.repetitionOptions}") Timber.d("hzType: ${hzType}")
val newRepetition = repetitionContext.repetitionOptions.firstOrNull() ?: currentList[index].repetition val list = RepetitionsByColorKey.get(hzType)!!
setRepetitionList( list )
val newRepetitionIndex = 0
val newRepetition = list[newRepetitionIndex]
val updatedPreset = currentList[index].copy( val updatedPreset = currentList[index].copy(
handPieceType = newHandPieceType, handPieceType = newHandPieceType,
pulseWidth = newPulseWidth, pulseWidth = newPulseWidth,
fluence = repetitionContext.fluence, fluence = newFluence,
repetition = newRepetition repetition = newRepetition
) )
currentList[index] = updatedPreset currentList[index] = updatedPreset
@@ -351,18 +311,20 @@ class PresetViewModel @Inject constructor(
// 3. update fluence // 3. update fluence
val newFluenceList = energyTable.value.getKey2ListForKey1(newPulseWidth) val newFluenceList = energyTable.value.getKey2ListForKey1(newPulseWidth)
val newFluence = newFluenceList.firstOrNull() ?: currentList[index].fluence val newFluenceIndex = 0
val newFluence = newFluenceList.get(newFluenceIndex)
// 4. update repetition // 4. update repetition
val repetitionContext = resolveRepetitionContext(newPulseWidth, newFluence) val hzType = hzTable.value.getValue(newPulseWidth, newFluence)
val newRepetition = resolveNearestLowerOrEqualRepetition( val list = RepetitionsByColorKey[hzType]!!
currentRepetition = currentList[index].repetition, setRepetitionList( list )
repetitionOptions = repetitionContext.repetitionOptions,
) val newRepetitionIndex = 0
val newRepetition = repetitionList.value[newRepetitionIndex]
val updatedPreset = currentList[index].copy( val updatedPreset = currentList[index].copy(
pulseWidth = newPulseWidth, pulseWidth = newPulseWidth,
fluence = repetitionContext.fluence, fluence = newFluence,
repetition = newRepetition repetition = newRepetition
) )
currentList[index] = updatedPreset currentList[index] = updatedPreset
@@ -392,16 +354,17 @@ class PresetViewModel @Inject constructor(
} }
// 3. update repetition (0) // 3. update repetition (0)
val repetitionContext = resolveRepetitionContext(pulseWidth, newFluence) val hzType = hzTable.value.getValue(pulseWidth, newFluence)
val newRepetition = resolveNearestLowerOrEqualRepetition( val list = RepetitionsByColorKey[hzType]!!
currentRepetition = currentList[index].repetition, setRepetitionList( list )
repetitionOptions = repetitionContext.repetitionOptions,
) val newRepetitionIndex = 0
val newRepetition = repetitionList.value[newRepetitionIndex]
// The original code here had a bug: it was updating `pulseWidth = newFluence` // The original code here had a bug: it was updating `pulseWidth = newFluence`
// It should be `fluence = newFluence` // It should be `fluence = newFluence`
val updatedPreset = currentList[index].copy( val updatedPreset = currentList[index].copy(
fluence = repetitionContext.fluence, fluence = newFluence,
repetition = newRepetition repetition = newRepetition
) )
currentList[index] = updatedPreset currentList[index] = updatedPreset
@@ -422,28 +385,20 @@ class PresetViewModel @Inject constructor(
loadHzTable(handPieceType) loadHzTable(handPieceType)
// update repetition // update repetition
val repetitionContext = resolveRepetitionContext(pulseWidth, fluence) val hzType = hzTable.value.getValue(pulseWidth, fluence)
val currentRepetitionList = repetitionContext.repetitionOptions val list = RepetitionsByColorKey[hzType]!!
setRepetitionList( list )
val newRepetitionIndex = currentRepetitionList.indexOf(repetition).takeIf { it != -1 } ?: 0 val newRepetitionIndex = repetitionList.value.indexOf(repetition).takeIf { it != -1 } ?: 0
val newRepetition = if (isUp == UpDownState.Up) { val newRepetition = if (isUp == UpDownState.Up) {
if (newRepetitionIndex < currentRepetitionList.size - 1) { // Original logic: repetitionIndex < PulseDurations.size -1 (Likely a typo, should be Repetitions.size)
currentRepetitionList[newRepetitionIndex + 1] if (newRepetitionIndex < repetitionList.value.size - 1) repetitionList.value[newRepetitionIndex + 1] else repetition
} else { } else {
repetition // Original logic: repetitionIndex > 1
} if (newRepetitionIndex > 0) repetitionList.value[newRepetitionIndex - 1] else repetition
} else {
if (newRepetitionIndex > 0) {
currentRepetitionList[newRepetitionIndex - 1]
} else {
repetition
}
} }
val updatedPreset = currentList[index].copy( val updatedPreset = currentList[index].copy(repetition = newRepetition)
fluence = repetitionContext.fluence,
repetition = newRepetition
)
currentList[index] = updatedPreset currentList[index] = updatedPreset
//_presetList.value = currentList //_presetList.value = currentList
setPresetList(currentList) setPresetList(currentList)

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

@@ -134,7 +134,6 @@ import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
import kotlin.math.abs
import javax.inject.Inject import javax.inject.Inject
import kotlin.experimental.or import kotlin.experimental.or
import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.milliseconds
@@ -584,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))
} }
@@ -815,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,43 +824,14 @@ class MainViewModel @Inject constructor(
// tx Q-Switch Write // tx Q-Switch Write
txPacket(READ_WRITE.WRITE, CMD.Q_SWITCH, qSwitch.value) txPacket(READ_WRITE.WRITE, CMD.Q_SWITCH, qSwitch.value)
// tx Oven Write (align with Engineer KTP write source)
txPacket(READ_WRITE.WRITE, CMD.OVEN, Oven(ktp = temperature_write.value.ktp))
// 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))
// tx SPRAY_DCD Write (DEFAULT VALUE) // tx SPRAY_DCD Write (DEFAULT VALUE)
txPacket(READ_WRITE.WRITE, CMD.SPRAY_DCD, sprayDcd.value.copy(status = 0x41)) 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
@@ -2082,58 +2043,28 @@ class MainViewModel @Inject constructor(
Timber.d("preset: ${preset}") Timber.d("preset: ${preset}")
val newPreset = if (preset == null) { val newPreset = if (preset == null) {
val defaultPulseWidth = PulseDurations.first()
Preset( Preset(
handPieceType = handPiece.value.type, handPieceType = handPiece.value.type,
priority = priority, priority = priority,
fluence = energyTable.value.getKey2ListForKey1(defaultPulseWidth).firstOrNull() ?: 0f, fluence = energyTable.value.getKey2ListForKey1(0.5f).first(),
repetition = repetitionList.value.first(), repetition = repetitionList.value.first(),
pulseWidth = defaultPulseWidth, pulseWidth = PulseDurations.first(),
) )
} else { } else {
preset preset
} }
applyPreset(newPreset)
}
fun applyPreset(preset: Preset) { val fluenceList = energyTable.value.getKey2ListForKey1(newPreset.pulseWidth)
val newPreset = preset.copy()
val pulseStep = PulseDurations.indexOf(newPreset.pulseWidth).takeIf {it != -1} ?: 0 val pulseStep = PulseDurations.indexOf(newPreset.pulseWidth).takeIf {it != -1} ?: 0
val resolvedPulseWidth = PulseDurations[pulseStep] val fluenceStep = fluenceList.indexOf(newPreset.fluence).takeIf {it != -1} ?: 0
val repetitionStep = repetitionList.value.indexOf(newPreset.repetition).takeIf {it != -1} ?: 0
// 프리셋의 pulseWidth 기준으로 실제 사용 가능한 fluence 목록을 먼저 동기화한다.
val newFluenceList = energyTable.value.getKey2ListForKey1(resolvedPulseWidth)
if (newFluenceList != fluenceList.value) {
setFluenceList(newFluenceList)
}
// 프리셋 fluence가 정확히 없을 수 있으므로, 가장 가까운 값으로 보정한다.
val resolvedFluence = newFluenceList.minByOrNull { abs(it - newPreset.fluence) }
?: newFluenceList.firstOrNull()
?: 0f
val fluenceStep = newFluenceList.indexOf(resolvedFluence).takeIf { it != -1 } ?: 0
// 보정된 (pulseWidth, fluence) 조합으로 repetition 테이블을 다시 계산한다.
val hzType = hzTable.value.getValue(resolvedPulseWidth, resolvedFluence)
val newRepetitionList = RepetitionsByColorKey[hzType] ?: RepetitionsByColorKey[KEY_YELLOW]!!
if (newRepetitionList != repetitionList.value) {
setRepetitionList(newRepetitionList)
}
val repetitionStep = newRepetitionList.indexOf(newPreset.repetition).takeIf { it != -1 } ?: 0
Timber.d("pulseStep: ${pulseStep} fluenceStep: ${fluenceStep} repetitionStep: ${repetitionStep}") Timber.d("pulseStep: ${pulseStep} fluenceStep: ${fluenceStep} repetitionStep: ${repetitionStep}")
val pulseAngle = pulseStep.stepToDegree(totalSteps = PulseDurations.size) val pulseAngle = pulseStep.stepToDegree(totalSteps = PulseDurations.size)
val fluenceAngle = if (newFluenceList.isNotEmpty()) { val fluenceAngle = fluenceStep.stepToDegree(totalSteps = fluenceList.size)
fluenceStep.stepToDegree(totalSteps = newFluenceList.size) val repetitionAngle = repetitionStep.stepToDegree(totalSteps = repetitionList.value.size)
} else {
0f
}
val repetitionAngle = repetitionIndexToAngle(
index = repetitionStep,
totalSteps = newRepetitionList.size,
)
Timber.d("pulseStep: ${pulseStep} fluenceStep: ${fluenceStep} repetitionStep: ${repetitionStep}") Timber.d("pulseStep: ${pulseStep} fluenceStep: ${fluenceStep} repetitionStep: ${repetitionStep}")
@@ -2163,35 +2094,30 @@ class MainViewModel @Inject constructor(
setFluenceList(newFluenceList) setFluenceList(newFluenceList)
} }
// 2-1. Resolve and apply fluence by value (not by old angle/index).
val resolvedFluence = newFluenceList.minByOrNull { abs(it - newFluence) } ?: 0f
val resolvedFluenceIndex = newFluenceList.indexOf(resolvedFluence).takeIf { it >= 0 } ?: 0
if (newFluenceList.isNotEmpty()) {
setFluenceAngle(resolvedFluenceIndex.stepToDegree(totalSteps = newFluenceList.size))
}
// 3. Safely Update Repetition List (Prevents NullPointerException) // 3. Safely Update Repetition List (Prevents NullPointerException)
val newHzType = hzTable.value.getValue(newPulseDuration, resolvedFluence) val newHzType = hzTable.value.getValue(newPulseDuration, newFluence)
val newRepetitionList = RepetitionsByColorKey[newHzType] ?: RepetitionsByColorKey[KEY_YELLOW]!! val newRepetitionList = RepetitionsByColorKey[newHzType] ?: RepetitionsByColorKey[KEY_YELLOW]!!
if (newRepetitionList != repetitionList.value) { if (newRepetitionList != repetitionList.value) {
setRepetitionList(newRepetitionList) setRepetitionList(newRepetitionList)
} }
// 4. Resolve and apply repetition by value (not by old angle/index). // Smartly preserve Repetition Angle
val targetRepetition = currentRepetitionValue ?: 0f // 4. Check if the old repetition value exists in the new list.
val resolvedRepetition = newRepetitionList.minByOrNull { abs(it - targetRepetition) } ?: 0f val oldRepetitionIndex = if (currentRepetitionValue != null) {
val resolvedRepetitionIndex = newRepetitionList.indexOf(resolvedRepetition).takeIf { it >= 0 } ?: 0 newRepetitionList.indexOf(currentRepetitionValue)
if (newRepetitionList.isNotEmpty()) {
val resolvedRepetitionAngle = repetitionIndexToAngle(
index = resolvedRepetitionIndex,
totalSteps = newRepetitionList.size,
)
setRepetitionAngle(resolvedRepetitionAngle)
Timber.d("Resolved repetition by value: old=$currentRepetitionValue, new=$resolvedRepetition, angle=$resolvedRepetitionAngle")
} else { } else {
-1
}
if (oldRepetitionIndex != -1) {
// If the old value exists, set the slider to that position.
val preservedAngle = oldRepetitionIndex.stepToDegree(totalSteps = newRepetitionList.size)
setRepetitionAngle(preservedAngle)
Timber.d("Repetition value $currentRepetitionValue preserved at new angle $preservedAngle.")
} else {
// If it doesn't exist, THEN reset the slider to the beginning.
setRepetitionAngle(0f) setRepetitionAngle(0f)
Timber.d("Repetition list is empty. Resetting repetition angle to 0f.") Timber.d("Repetition value $currentRepetitionValue not supported in new list. Resetting angle.")
} }
// 5. Conditionally reset the fluence angle slider if needed // 5. Conditionally reset the fluence angle slider if needed
@@ -2204,7 +2130,7 @@ class MainViewModel @Inject constructor(
// 6. Any change invalidates the current preset selection. // 6. Any change invalidates the current preset selection.
setSelectedPresetIndex(0) setSelectedPresetIndex(0)
Timber.d("Updated Laser Parameters: pulse=$newPulseDuration, fluence=$resolvedFluence -> newRepListSize=${newRepetitionList.size}") Timber.d("Updated Laser Parameters: pulse=$newPulseDuration, fluence=$newFluence -> newRepListSize=${newRepetitionList.size}")
} }
/** /**
@@ -2224,16 +2150,13 @@ class MainViewModel @Inject constructor(
setPulseAngle(newPulseStep.stepToDegree(totalSteps = PulseDurations.size)) setPulseAngle(newPulseStep.stepToDegree(totalSteps = PulseDurations.size))
val newPulseDuration = PulseDurations[newPulseStep] val newPulseDuration = PulseDurations[newPulseStep]
// Keep the current fluence value when pulse duration changes via slider. // When pulse duration changes via slider, we use the first available fluence for the new list.
val currentFluenceStep = fluenceAngle.value.degreeToStep(totalSteps = fluenceList.value.size) val firstFluence = energyTable.value.getKey2ListForKey1(newPulseDuration).firstOrNull() ?: 0f
val currentFluence = fluenceList.value.getOrNull(currentFluenceStep)
?: energyTable.value.getKey2ListForKey1(newPulseDuration).firstOrNull()
?: 0f
// Call the centralized helper using the preserved fluence value. // Call the centralized helper, resetting the fluence slider.
updateLaserParameters( updateLaserParameters(
newPulseDuration = newPulseDuration, newPulseDuration = newPulseDuration,
newFluence = currentFluence, newFluence = firstFluence,
) )
} }
@@ -2245,17 +2168,12 @@ class MainViewModel @Inject constructor(
setPulseAngle(newStep.stepToDegree(totalSteps = PulseDurations.size)) setPulseAngle(newStep.stepToDegree(totalSteps = PulseDurations.size))
val newPulseDuration = PulseDurations[newStep] val newPulseDuration = PulseDurations[newStep]
// Keep the current fluence value when pulse duration changes via slider. val firstFluence = energyTable.value.getKey2ListForKey1(newPulseDuration).firstOrNull() ?: 0f
val currentFluenceStep = fluenceAngle.value.degreeToStep(totalSteps = fluenceList.value.size)
val currentFluence = fluenceList.value.getOrNull(currentFluenceStep)
?: energyTable.value.getKey2ListForKey1(newPulseDuration).firstOrNull()
?: 0f
// Call the centralized helper, resetting the fluence slider. // Call the centralized helper, resetting the fluence slider.
updateLaserParameters( updateLaserParameters(
newPulseDuration = newPulseDuration, newPulseDuration = newPulseDuration,
newFluence = currentFluence, newFluence = firstFluence,
) )
} }
} }
@@ -2298,12 +2216,8 @@ class MainViewModel @Inject constructor(
fun onChangeRepetition(angle: Float) { fun onChangeRepetition(angle: Float) {
// This logic is simple and has no complex dependencies, so it can remain as is. // This logic is simple and has no complex dependencies, so it can remain as is.
val normalizedAngle = repetitionIndexToAngle( if (angle != repetitionAngle.value) {
index = angle.degreeToStep(totalSteps = repetitionList.value.size), setRepetitionAngle(angle)
totalSteps = repetitionList.value.size,
)
if (normalizedAngle != repetitionAngle.value) {
setRepetitionAngle(normalizedAngle)
} }
setSelectedPresetIndex(0) setSelectedPresetIndex(0)
} }
@@ -2314,23 +2228,12 @@ class MainViewModel @Inject constructor(
val newStep = if (state == UpDownState.Up) currentStep + 1 else currentStep - 1 val newStep = if (state == UpDownState.Up) currentStep + 1 else currentStep - 1
if (newStep in repetitionList.value.indices) { if (newStep in repetitionList.value.indices) {
val newRepetitionAngle = repetitionIndexToAngle( val newRepetitionAngle = newStep.stepToDegree(totalSteps = repetitionList.value.size)
index = newStep,
totalSteps = repetitionList.value.size,
)
setRepetitionAngle(newRepetitionAngle) setRepetitionAngle(newRepetitionAngle)
setSelectedPresetIndex(0) setSelectedPresetIndex(0)
} }
} }
private fun repetitionIndexToAngle(index: Int, totalSteps: Int): Float {
return when {
totalSteps <= 0 -> 0f
totalSteps == 1 -> 270f
else -> index.stepToDegree(totalSteps = totalSteps)
}
}
/** /**
* Perform all heavy I/O in a single background block. * Perform all heavy I/O in a single background block.
* This prevents the "Skipped frames" caused by 30+ sequential bridge calls * This prevents the "Skipped frames" caused by 30+ sequential bridge calls

View File

@@ -487,7 +487,7 @@ fun QSwitch.toByteArray(): ByteArray {
val delayTimeIntegerPart = this.delayTime.toInt() val delayTimeIntegerPart = this.delayTime.toInt()
val delayTimeFractionPart = ((this.delayTime - delayTimeIntegerPart) * 10).toInt() val delayTimeFractionPart = ((this.delayTime - delayTimeIntegerPart) * 10).toInt()
val intervalTimeIntegerPart = this.intervalTime.toInt() val intervalTimeIntegerPart = this.intervalTime.toInt()
val intervalTimeFractionPart = ((this.intervalTime - intervalTimeIntegerPart) * 10).toInt() val intervalTimeFractionPart = ((this.intervalTime - delayTimeIntegerPart) * 10).toInt()
val delayTimeArray = byteArrayOf( val delayTimeArray = byteArrayOf(
((delayTimeIntegerPart.getNthDigit(2) + 0x30) and 0xFF).toByte(), ((delayTimeIntegerPart.getNthDigit(2) + 0x30) and 0xFF).toByte(),

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,23 +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가 호출되어 초기 패킷이 누락되는 문제를 줄임

View File

@@ -1,237 +0,0 @@
# 변경 소스 설명 (2026-03-10)
## 대상
현재 워크스페이스에서 수정된 항목은 아래와 같습니다.
- `app/src/main/java/com/laseroptek/raman/ui/screens/home/preset/PresetViewModel.kt`
- `app/build.gradle.kts`
실제 로직 변경은 `PresetViewModel.kt`에 있습니다.
`app/build.gradle.kts``git status`상 수정으로 보이지만, 확인한 텍스트 diff 기준으로는 의미 있는 코드 변경이 보이지 않았습니다. 줄바꿈(CRLF/LF) 같은 형식 변화일 가능성이 큽니다.
## 이 파일이 하는 일
`PresetViewModel.kt`는 프리셋 화면의 상태를 관리하는 코드입니다.
쉽게 말하면 사용자가 화면에서 아래 값을 올리거나 내릴 때:
- 핸드피스 종류
- 펄스폭 (`pulseWidth`)
- 에너지 단계 (`fluence`)
- 반복수 (`repetition`)
그 조합에 맞는 다음 값들을 다시 계산해서 화면에 반영하는 역할입니다.
## 이번 변경의 핵심
핵심은 반복수(`repetition`) 계산을 더 안전하고 더 자연스럽게 만든 것입니다.
이전 방식은 다음 문제가 생길 수 있었습니다.
- `pulseWidth``fluence` 조합이 테이블에 정확히 없으면 적절한 반복수 목록을 못 찾을 수 있음
- 못 찾았을 때 강제 `!!` 사용으로 앱이 비정상 종료될 가능성이 있음
- `fluence` 변경 시 다른 필드를 잘못 갱신하는 버그가 있었음
이번 수정에서는 공통 계산 함수가 추가되어, 값이 정확히 일치하지 않아도 가장 가까운 `fluence`를 찾아서 처리하도록 바뀌었습니다.
또한 `pulse duration`이나 `fluence`를 바꿀 때 repetition이 무조건 목록의 첫 값(`1Hz` 등)으로 초기화되지 않도록 규칙이 바뀌었습니다.
새 규칙은 아래와 같습니다.
- 현재 repetition 값 이하인 후보들 중
- 가장 큰 값을 선택
- 만약 그런 값이 하나도 없으면 새 목록의 최소값 사용
예를 들어 현재 repetition이 `10Hz`이고, 새 조건에서 가능한 repetition 목록이 `1, 3, 5, 8`이라면 결과는 `8Hz`가 됩니다.
즉, "현재 값에 최대한 가깝게 유지하되, 새 조건에서 허용되는 값으로 내린다"는 방식입니다.
## 새로 추가된 구조
### 1. `ResolvedRepetitionContext`
```kotlin
private data class ResolvedRepetitionContext(
val fluence: Float,
val repetitionOptions: List<Float>,
)
```
이 구조는 반복수 계산 결과를 한 번에 묶어서 전달하기 위한 작은 데이터 상자입니다.
- `fluence`: 실제로 확정된 에너지 값
- `repetitionOptions`: 그 조건에서 선택 가능한 반복수 목록
### 2. `resolveRepetitionContext()`
이 함수가 이번 수정의 핵심입니다.
동작 순서는 아래와 같습니다.
1. 현재 `pulseWidth`에 대해 사용 가능한 `fluence` 목록을 가져옵니다.
2. 사용자가 가지고 있던 `fluence`와 가장 가까운 실제 값을 찾습니다.
3. 그 조합으로 `hzType`을 찾습니다.
4. `hzType`에 맞는 반복수 목록을 가져옵니다.
5. 만약 `hzType`을 찾지 못하면 기본값(`KEY_YELLOW`) 목록으로 대체합니다.
6. 최종 반복수 목록을 `setRepetitionList()`로 화면 상태에 반영합니다.
즉, 예전보다 훨씬 덜 깨지도록 방어 로직이 들어갔습니다.
### 3. `resolveNearestLowerOrEqualRepetition()`
이 함수는 repetition 선택 규칙을 담당합니다.
동작은 단순합니다.
1. 새 repetition 목록에서 현재 repetition 이하인 값만 고릅니다.
2. 그중 가장 큰 값을 선택합니다.
3. 없다면 새 목록의 최소값을 사용합니다.
이 함수가 추가되면서 `pulse duration` 또는 `fluence` 변경 시 repetition이 불필요하게 `1Hz`로 떨어지지 않게 되었습니다.
## 함수별로 무엇이 바뀌었는가
### 1. `updateHandPieceType()`
핸드피스 종류를 바꾸면:
- 해당 핸드피스에 맞는 테이블을 다시 불러오고
- 기본 `pulseWidth`를 고른 뒤
- 가능한 `fluence`를 정하고
- 그에 맞는 `repetition` 목록을 계산합니다
변경 전에는 반복수 목록을 직접 찾다가 실패 가능성이 있었고,
변경 후에는 `resolveRepetitionContext()`를 통해 안전하게 계산합니다.
또한 새 반복수 값도 목록의 첫 번째 값을 안전하게 가져오도록 바뀌었습니다.
### 2. `updatePulseWidth()`
펄스폭을 올리거나 내리면:
-`pulseWidth`에 맞는 `fluence`를 다시 정하고
- 그 조합에 맞는 `repetition` 목록을 다시 계산합니다
여기도 동일하게 공통 함수 사용으로 바뀌어,
정확히 일치하는 값이 없을 때 현재 값 또는 가장 가까운 값으로 안전하게 처리합니다.
추가로 repetition 선택 방식도 바뀌었습니다.
- 예전: 새 repetition 목록의 첫 번째 값으로 사실상 초기화
- 현재: 기존 repetition 이하에서 가장 가까운 최대값 선택
예:
- 기존 repetition = `10Hz`
- 새 목록 = `1, 3, 5, 8`
- 결과 = `8Hz`
### 3. `updateFluence()`
이 부분은 버그 수정이 포함되어 있어 중요합니다.
기존 코드에는 주석으로도 남아 있듯이,
원래 `fluence`를 업데이트해야 하는 상황에서 잘못된 필드를 갱신하던 문제가 있었습니다.
수정 후에는:
- `pulseWidth`에 맞는 `fluence` 목록에서 다음/이전 값을 고르고
- 그 값으로 반복수 목록을 다시 계산한 뒤
- repetition도 기존 값 이하에서 가장 가까운 최대값으로 다시 선택하고
- 실제 프리셋에는 `fluence = repetitionContext.fluence`를 저장합니다
즉, 사용자가 에너지 단계를 바꿨을 때 실제 프리셋 데이터도 올바르게 바뀌도록 고친 것입니다.
이제 `fluence` 변경 시에도 repetition이 불필요하게 최소값으로 초기화되지 않습니다.
### 4. `updateRepetition()`
반복수만 변경할 때도 사실은 현재 `pulseWidth``fluence`에 맞는 반복수 목록이 먼저 계산되어야 합니다.
이번 수정 후에는:
- 현재 조건에 맞는 반복수 목록을 공통 함수로 얻고
- 그 목록 안에서 위/아래 이동을 수행하고
- 필요하면 `fluence`도 보정된 값으로 같이 저장합니다
이전 코드보다 현재 조건과 실제 목록이 더 일관되게 맞춰집니다.
## 왜 이 수정이 필요한가
이 코드는 여러 테이블을 조합해서 동작합니다.
- `energyTable`: `(pulseWidth, fluence)` 조합에 대한 에너지 정보
- `hzTable`: `(pulseWidth, fluence)` 조합에 대한 `hzType`
- `RepetitionsByColorKey`: `hzType`에 따라 선택 가능한 반복수 목록
문제는 사용자가 가진 값이 테이블의 키와 딱 맞지 않을 수 있다는 점입니다.
예를 들어:
- 현재 `pulseWidth`는 존재하지만
- `fluence`가 소수점 차이로 정확히 일치하지 않거나
- 핸드피스 변경 후 이전 값이 새 테이블에 없는 경우
예전 코드는 이런 경우에 취약했습니다.
이번 수정은 이런 경계 상황에서도 앱이 가능한 범위 안에서 계속 동작하도록 만든 것입니다.
## 코틀린을 모르는 사람 기준으로 문법 설명
### `fun`
함수를 만든다는 뜻입니다.
```kotlin
fun updateFluence(...)
```
### `val`
한 번 정하면 다시 바꾸지 않는 값입니다.
```kotlin
val newFluence = ...
```
### `data class`
관련 있는 값 몇 개를 묶는 작은 자료형입니다.
```kotlin
data class ResolvedRepetitionContext(...)
```
### `copy(...)`
기존 객체를 복사하면서 일부 값만 바꾸는 방식입니다.
```kotlin
currentList[index].copy(
fluence = repetitionContext.fluence,
repetition = newRepetition
)
```
이 코드는 "기존 프리셋을 복사하되 `fluence``repetition`만 새 값으로 바꾼다"는 뜻입니다.
### `?:`
왼쪽 값이 없으면 오른쪽 값을 대신 사용하라는 뜻입니다.
```kotlin
val newFluence = newFluenceList.firstOrNull() ?: currentList[index].fluence
```
즉:
- 목록 첫 값이 있으면 그 값을 쓰고
- 없으면 현재 저장된 `fluence`를 그대로 씁니다
### `firstOrNull()`
목록의 첫 번째 값을 가져오되, 비어 있으면 오류 대신 `null`을 돌려줍니다.
안전한 코드에서 자주 쓰입니다.
## 한 줄 요약
이번 수정은 프리셋 편집 시 `pulseWidth`, `fluence`, `repetition`의 연결 계산을 더 안전하게 만들고, `pulse duration``fluence` 변경 시 repetition을 현재 값에 가장 가깝게 유지하도록 개선했으며, `fluence` 변경 시 잘못된 필드가 갱신되던 버그도 함께 바로잡은 변경입니다.

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) 수신 여부 확인