@@ -32,7 +32,10 @@ import dagger.hilt.android.lifecycle.HiltViewModel
3232import kotlinx.coroutines.flow.MutableSharedFlow
3333import kotlinx.coroutines.flow.SharedFlow
3434import kotlinx.coroutines.flow.asSharedFlow
35+ import kotlinx.coroutines.flow.filter
36+ import kotlinx.coroutines.flow.first
3537import kotlinx.coroutines.launch
38+ import kotlinx.coroutines.withTimeoutOrNull
3639import javax.inject.Inject
3740
3841/* *
@@ -69,6 +72,7 @@ class BluetoothViewModel @Inject constructor(
6972 val isSmartAssignmentEnabled = settingsFacade.isSmartAssignmentEnabled
7073 val smartAssignmentTolerancePercent = settingsFacade.smartAssignmentTolerancePercent
7174 val smartAssignmentIgnoreOutsideTolerance = settingsFacade.smartAssignmentIgnoreOutsideTolerance
75+ val autoConnectOnStartup = settingsFacade.autoConnectOnStartup
7276
7377 fun setSmartAssignmentEnabled (enabled : Boolean ) = viewModelScope.launch {
7478 settingsFacade.setSmartAssignmentEnabled(enabled)
@@ -82,6 +86,9 @@ class BluetoothViewModel @Inject constructor(
8286 settingsFacade.setSmartAssignmentIgnoreOutsideTolerance(ignore)
8387 }
8488
89+ fun setAutoConnectOnStartup (enabled : Boolean ) = viewModelScope.launch {
90+ settingsFacade.setAutoConnectOnStartup(enabled)
91+ }
8592 // --- Snackbar events for UI ---
8693 private val _snackbarEvents = MutableSharedFlow <SnackbarEvent >(replay = 0 , extraBufferCapacity = 1 )
8794 val snackbarEvents: SharedFlow <SnackbarEvent > = _snackbarEvents .asSharedFlow()
@@ -92,6 +99,22 @@ class BluetoothViewModel @Inject constructor(
9299 _snackbarEvents .emit(evt)
93100 }
94101 }
102+
103+ // Auto-connect on startup
104+ viewModelScope.launch {
105+ val enabled = settingsFacade.autoConnectOnStartup.first()
106+ if (! enabled) return @launch
107+
108+ val device = withTimeoutOrNull(1_500 ) {
109+ bt.savedDevice
110+ .filter { it != null }
111+ .first()
112+ }
113+
114+ if (device != null ) {
115+ bt.attemptAutoConnectToSavedDevice()
116+ }
117+ }
95118 }
96119
97120 // --- Delegated actions ---
@@ -122,8 +145,6 @@ class BluetoothViewModel @Inject constructor(
122145
123146 fun clearAllErrors () = bt.clearErrors()
124147
125- fun attemptAutoConnectToSavedScale () = bt.attemptAutoConnectToSavedDevice()
126-
127148 fun provideUserInteractionFeedback (type : BluetoothEvent .UserInteractionType , feedbackData : Any ) =
128149 bt.provideUserInteractionFeedback(type, feedbackData)
129150
0 commit comments