content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.mviapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/ui/theme/Color.kt
1603509236
package com.example.mviapp.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MVIAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/ui/theme/Theme.kt
1995623631
package com.example.mviapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/ui/theme/Type.kt
3321522997
package com.example.mviapp import android.os.Bundle import android.widget.Toast import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import coil.compose.rememberImagePainter import com.example.mviapp.api.AnimalService import com.example.mviapp.model.Animal import com.example.mviapp.ui.theme.MVIAppTheme import com.example.mviapp.view.MainIntent import com.example.mviapp.view.MainState import com.example.mviapp.view.MainViewModel import com.example.mviapp.view.ViewModelFactory import kotlinx.coroutines.launch class MainActivity : FragmentActivity() { private lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainViewModel = ViewModelProviders .of(this, ViewModelFactory(AnimalService.api)) .get(MainViewModel::class.java) val onButtonClick: () -> Unit = { lifecycleScope.launch { mainViewModel.userIntent.send(MainIntent.FetchAnimal) } } setContent { MVIAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainScreen(viewModel = mainViewModel, onButtonClick = onButtonClick) } } } } } @Composable fun MainScreen(viewModel: MainViewModel, onButtonClick: () -> Unit) { val state = viewModel.state.value when (state) { is MainState.Idle -> IdleScreen(onButtonClick = onButtonClick) is MainState.Loading -> LoadingScreen() is MainState.Animals -> AnimalList(animals = state.animals) is MainState.Error -> { IdleScreen(onButtonClick = onButtonClick) Toast.makeText(LocalContext.current, state.error, Toast.LENGTH_SHORT).show() } } } @Composable fun IdleScreen(onButtonClick: () -> Unit) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Button(onClick = onButtonClick) { Text(text = "Fetch Animals") } } } @Composable fun LoadingScreen() { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator() } } @Composable fun AnimalList(animals: List<Animal>) { LazyColumn { items(items = animals) { AnimalItem(animal = it) Divider(color = Color.LightGray, modifier = Modifier.padding(vertical = 4.dp)) } } } @Composable fun AnimalItem(animal: Animal) { Row( modifier = Modifier .fillMaxWidth() .height(100.dp) ) { val url = AnimalService.BASE_URL + animal.image val painter = rememberImagePainter(data = url) Image( painter = painter, contentDescription = null, modifier = Modifier.size(100.dp), contentScale = ContentScale.FillHeight ) Column( modifier = Modifier .fillMaxSize() .padding(start = 4.dp) ) { Text(text = animal.name, fontWeight = FontWeight.Bold) Text(text = animal.location) } } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/MainActivity.kt
2378851943
package com.example.mviapp.model data class Animal( val name: String = "", val location: String = "", val image: String = "" )
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/model/Animal.kt
1103851502
package com.example.mviapp.view import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.mviapp.api.AnimalRepository import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.launch class MainViewModel(private val animalRepository: AnimalRepository) : ViewModel() { val userIntent = Channel<MainIntent>(Channel.UNLIMITED) var state = mutableStateOf<MainState>(MainState.Idle) private set init { handleIntent() } private fun handleIntent() { viewModelScope.launch { userIntent.consumeAsFlow().collect { collector -> when (collector) { is MainIntent.FetchAnimal -> fetchAnimals() } } } } private fun fetchAnimals() { viewModelScope.launch { state.value = MainState.Loading state.value = try { MainState.Animals(animalRepository.getAnimals()) } catch (e: Exception) { e.printStackTrace() MainState.Error(e.localizedMessage) } } } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/MainViewModel.kt
3501329836
package com.example.mviapp.view import com.example.mviapp.model.Animal sealed class MainState { data object Idle : MainState() data object Loading : MainState() data class Animals(val animals: List<Animal>) : MainState() data class Error(val error: String?) : MainState() }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/MainState.kt
407557533
package com.example.mviapp.view import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.mviapp.api.AnimalApi import com.example.mviapp.api.AnimalRepository class ViewModelFactory(private val api: AnimalApi) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { return MainViewModel(AnimalRepository(api)) as T } throw IllegalArgumentException("Unknown class name") } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/ViewModelFactory.kt
2493094996
package com.example.mviapp.view sealed class MainIntent { data object FetchAnimal : MainIntent() }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/MainIntent.kt
958450864
package com.example.mviapp.api import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object AnimalService { const val BASE_URL = "https://raw.githubusercontent.com/CatalinStefan/animalApi/master/" private fun getRetrofit() = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() val api: AnimalApi = getRetrofit().create(AnimalApi::class.java) }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/api/AnimalService.kt
2624634530
package com.example.mviapp.api import com.example.mviapp.model.Animal import retrofit2.http.GET interface AnimalApi { @GET("animals.json") suspend fun getAnimals(): List<Animal> }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/api/AnimalApi.kt
2268741462
package com.example.mviapp.api import com.example.mviapp.model.Animal class AnimalRepository(private val api: AnimalApi) { suspend fun getAnimals(): List<Animal> = api.getAnimals() }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/api/AnimalRepository.kt
2792167888
package com.alperen.statesamancioglu.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/ui/theme/Color.kt
1258427492
package com.alperen.statesamancioglu.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun StateSamanciogluTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/ui/theme/Theme.kt
4223095565
package com.alperen.statesamancioglu.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/ui/theme/Type.kt
2295007732
package com.alperen.statesamancioglu import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.alperen.statesamancioglu.ui.theme.StateSamanciogluTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { StateSamanciogluTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val navController = rememberNavController() NavHost(navController = navController, startDestination ="firstScreen" ) { composable(route = "firstScreen") { val viewModel = viewModel<FirstScreenVM>() val time by viewModel.counter.collectAsStateWithLifecycle() //bu lifecycle'a saygı duyar. //.collectAsState() //lifecycle awareness değil. FirstScreen(time = time, onButtonClicked = { navController.navigate("secondScreen") } ) } composable(route= "secondScreen") { SecondScreen() } } } } } } }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/MainActivity.kt
542241386
package com.alperen.statesamancioglu import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn class FirstScreenVM:ViewModel() { private var count = 0 val counter = flow { while (true) { delay(1000L) println("Running Flow") emit(count++) } }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(10000),0) }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/FirstScreenVM.kt
3858069072
package com.alperen.statesamancioglu import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun SecondScreen(){ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Text(text = "Second Screen", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center, modifier = Modifier.padding(2.dp) ) } }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/secondScreen.kt
4170756210
package com.alperen.statesamancioglu import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun FirstScreen(time: Int, onButtonClicked:()->Unit){ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Text(text = time.toString(), style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center, modifier = Modifier.padding(2.dp).clickable(onClick = onButtonClicked) ) } }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/FirstScreen.kt
4258706048
package net.projecttl.mod.example.mixin import net.minecraft.client.gui.screen.TitleScreen import org.spongepowered.asm.mixin.Mixin import org.spongepowered.asm.mixin.injection.At import org.spongepowered.asm.mixin.injection.Inject import org.spongepowered.asm.mixin.injection.callback.CallbackInfo @Mixin(TitleScreen::class) class ExampleMixin { @Inject(at = [At("HEAD")], method = ["init()V"]) private fun init(info: CallbackInfo) { println("This line is printed by an example mod mixin!") } }
kotlin-fabric-mod-template/src/main/kotlin/net/projecttl/mod/example/mixin/ExampleMixin.kt
3833756619
package net.projecttl.mod.example import net.fabricmc.api.ModInitializer import org.slf4j.LoggerFactory class ExampleMod : ModInitializer { val logger = LoggerFactory.getLogger("ExampleMod") override fun onInitialize() { TODO("Not yet implemented") } }
kotlin-fabric-mod-template/src/main/kotlin/net/projecttl/mod/example/ExampleMod.kt
3847905308
package com.example.controlpivot import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.controlpivot", appContext.packageName) } }
pivot-control/app/src/androidTest/java/com/example/controlpivot/ExampleInstrumentedTest.kt
931896525
package com.example.controlpivot import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
pivot-control/app/src/test/java/com/example/controlpivot/ExampleUnitTest.kt
3631547911
package com.example.controlpivot.ui.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Job import kotlinx.coroutines.launch class SplashViewModel(private val sessionRepository: SessionRepository): ViewModel() { private val _isLogged = MutableLiveData<Boolean?>(null) val isLogged: LiveData<Boolean?> = _isLogged var job: Job? = null fun checkLogin(){ job?.cancel() job = viewModelScope.launch{ when(val result = sessionRepository.getSession()){ is Resource.Error -> _isLogged.postValue(false) is Resource.Success -> { _isLogged.postValue(true) } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/SplashViewModel.kt
2448980935
package com.example.controlpivot.ui.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.data.remote.datasource.PivotMachineRemoteDatasource import com.example.controlpivot.data.repository.MachinePendingDeleteRepository import com.example.controlpivot.data.repository.PivotMachineRepository import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.domain.usecase.DeletePendingMachineUseCase import com.example.controlpivot.ui.screen.createpivot.PivotMachineEvent import com.example.controlpivot.ui.screen.createpivot.PivotMachineState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PivotMachineViewModel( private val connectivityObserver: NetworkConnectivityObserver, private val pivotMachineRepository: PivotMachineRepository, private val sessionRepository: SessionRepository, private val pendingDeleteUseCase: DeletePendingMachineUseCase, private val machinePendingDeleteRepository: MachinePendingDeleteRepository, private val pivotMachineRemoteDatasource: PivotMachineRemoteDatasource, ) : ViewModel() { private var session: Session? = null private var _networkStatus = ConnectivityObserver.Status.Available private var getCurrentMachineJob: Job? = null private var deleteMachineJob: Job? = null private var getMachinesByNameJob: Job? = null private var registerMachineJob: Job? = null private var getSessionJob: Job? = null private var refreshDataJob: Job? = null private var networkObserverJob: Job? = null private val _state = MutableStateFlow(PivotMachineState()) val state = _state.asStateFlow() private val _event = MutableSharedFlow<Event>() val event = _event.asSharedFlow() sealed class Event() { class ShowMessage(val message: Message) : Event() data object PivotMachineCreated : Event() } init { loadSession() getPivotMachineByName() observeNetworkChange() refreshData() } fun onEvent(event: PivotMachineEvent) { when (event) { is PivotMachineEvent.DeleteMachine -> { deleteMachine(event.machineId) } is PivotMachineEvent.ResetDataMachine -> { _state.update { it.copy(currentMachine = PivotMachineEntity()) } } is PivotMachineEvent.SelectMachine -> { getCurrentMachine(event.id) } is PivotMachineEvent.CreateMachine -> { registerPivotMachine(event.machine) } is PivotMachineEvent.SearchMachine -> { getPivotMachineByName(event.query) } } } fun refreshData() { refreshDataJob?.cancel() refreshDataJob = viewModelScope.launch(Dispatchers.IO) { _state.update { it.copy(isLoading = true) } if (isNetworkAvailable()) { pivotMachineRepository.registerPendingMachines() pendingDeleteUseCase() if (pivotMachineRepository.arePendingPivotMachines()) reloadPivotMachines() } _state.update { it.copy(isLoading = false) } } } private suspend fun reloadPivotMachines() { val result = pivotMachineRepository.fetchPivotMachine() if (result is Resource.Error) _event.emit(Event.ShowMessage(result.message)) } private fun loadSession() { getSessionJob?.cancel() getSessionJob = viewModelScope.launch(Dispatchers.IO) { when (val result = sessionRepository.getSession()) { is Resource.Error -> { _event.emit(Event.ShowMessage(result.message)) } is Resource.Success -> session = result.data } } } private fun registerPivotMachine(machine: PivotMachineEntity) { registerMachineJob?.cancel() registerMachineJob = viewModelScope.launch(Dispatchers.IO) { if (machine.name == "" || machine.location == "" || machine.endowment == 0.0 || machine.flow == 0.0 || machine.pressure == 0.0 || machine.area == 0.0 || machine.length == 0.0 || machine.power == 0.0 || machine.efficiency == 0.0 || machine.speed == 0.0 ) { _event.emit( Event.ShowMessage(Message.StringResource(R.string.values_are_required))) return@launch } else { when (val result = pivotMachineRepository.upsertPivotMachine(machine)) { is Resource.Error -> _event.emit(Event.ShowMessage(result.message)) is Resource.Success -> { _event.emit(Event.PivotMachineCreated) if (isNetworkAvailable()) { when (val response = pivotMachineRepository.savePivotMachine(result.data)) { is Resource.Error -> _event.emit(Event.ShowMessage(response.message)) is Resource.Success -> {} } } } } } } } private suspend fun isNetworkAvailable(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _event.emit( Event.ShowMessage(Message.StringResource(R.string.internet_error))) return false } return true } private fun getPivotMachineByName(query: String = "") { getMachinesByNameJob?.cancel() getMachinesByNameJob = viewModelScope.launch(Dispatchers.IO) { pivotMachineRepository.getAllPivotMachines(query).collectLatest { result -> when (result) { is Resource.Error -> _event.emit(Event.ShowMessage(result.message)) is Resource.Success -> _state.update { it.copy(machines = result.data) } } } } } private fun getCurrentMachine(id: Int) { getCurrentMachineJob?.cancel() getCurrentMachineJob = viewModelScope.launch(Dispatchers.IO) { pivotMachineRepository.getPivotMachineAsync(id).onEach { result -> when (result) { is Resource.Error -> _event.emit(Event.ShowMessage(result.message)) is Resource.Success -> _state.update { it.copy(currentMachine = result.data) } } }.collect() } } private fun deleteMachine(machineId: Int) { deleteMachineJob?.cancel() deleteMachineJob = viewModelScope.launch(Dispatchers.IO) { when (val response = pivotMachineRepository.getPivotMachine(machineId)) { is Resource.Error -> _event.emit(Event.ShowMessage(response.message)) is Resource.Success -> { val result = pivotMachineRepository.deletePivotMachine(machineId) if (result is Resource.Error) _event.emit(Event.ShowMessage(result.message)) else { if (response.data.isSave) { val machinePendingDelete = when (val result = machinePendingDeleteRepository.getPendingDelete()) { is Resource.Error -> MachinePendingDelete() is Resource.Success -> result.data } if (isNetworkAvailable()) { pivotMachineRemoteDatasource.deletePivotMachine(response.data.remoteId) } else { val listId = machinePendingDelete.listId.toMutableList() listId.add(response.data.remoteId) when (val resultDelete = machinePendingDeleteRepository.savePendingDelete( MachinePendingDelete(listId) )) { is Resource.Error -> _event.emit( Event.ShowMessage(resultDelete.message) ) is Resource.Success -> { } } } } _event.emit( Event.ShowMessage( Message.StringResource(R.string.machine_deleted) ) ) } } } } } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/PivotMachineViewModel.kt
649942019
package com.example.controlpivot.ui.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.ui.screen.login.Credentials import com.example.controlpivot.ui.screen.login.LoginEvent import com.example.controlpivot.ui.screen.login.LoginState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class LoginViewModel( private val sessionRepository: SessionRepository, private val connectivityObserver: NetworkConnectivityObserver ) : ViewModel() { private var loginJob: Job? = null private var networkObserverJob: Job? = null private var changeCredentialsJob: Job? = null private var getSessionJob: Job? = null private val _state = MutableStateFlow(LoginState()) val state = _state.asStateFlow() private val _message = MutableSharedFlow<Message>() val message = _message.asSharedFlow() private val _isLogged = MutableLiveData(false) val isLogged: LiveData<Boolean> = _isLogged private var _networkStatus = ConnectivityObserver.Status.Available private var session: Session? = null init { loadSession() observeNetworkChange() } fun onEvent(event: LoginEvent) { when (event) { is LoginEvent.Login -> login(event.credentials) is LoginEvent.ChangeCredentials -> changeCredentials(event.credentials) } } private fun changeCredentials(credentials: Credentials) { changeCredentialsJob?.cancel() changeCredentialsJob = viewModelScope.launch(Dispatchers.IO) { credentials.validate().let { result -> if (result is Resource.Error) { _message.emit(result.message) return@launch } } if (!isNetworkAvalible()) return@launch _state.update { it.copy(isLoading = true) } when (val result = sessionRepository.updateSession( credentials )) { is Resource.Error -> { _state.update { it.copy(isLoading = false) } _message.emit(result.message) } is Resource.Success -> { _isLogged.postValue(true) _message.emit(Message.StringResource(R.string.update_success)) } } } } fun login(credentials: Credentials) { loginJob?.cancel() loginJob = viewModelScope.launch(Dispatchers.IO) { credentials.validate().let { result -> if (result is Resource.Error) { _message.emit(result.message) return@launch } } if (!isNetworkAvalible()) return@launch _state.update { it.copy(isLoading = true) } when (val result = sessionRepository.fetchSession( credentials )) { is Resource.Error -> { _state.update { it.copy(isLoading = false) } _message.emit(result.message) } is Resource.Success -> { _isLogged.postValue(true) } } } } private suspend fun isNetworkAvalible(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _message.emit(Message.StringResource(R.string.internet_error)) return false } return true } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } fun loadSession() { getSessionJob?.cancel() getSessionJob = viewModelScope.launch(Dispatchers.IO) { when (val result = sessionRepository.getSession()) { is Resource.Error -> { _message.emit(result.message) } is Resource.Success -> { Log.d("LOG", result.data.toString()) _state.update { it.copy(session = result.data) }} } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/LoginViewModel.kt
2759395208
package com.example.controlpivot.ui.viewmodel import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.repository.ClimateRepository import com.example.controlpivot.domain.usecase.GetIdPivotNameUseCase import com.example.controlpivot.ui.screen.climate.ClimateEvent import com.example.controlpivot.ui.screen.climate.ClimateState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.time.LocalDateTime import java.time.format.DateTimeFormatter class ClimateViewModel( private val climateRepository: ClimateRepository, private val connectivityObserver: NetworkConnectivityObserver, private val getIdPivotNameUseCase: GetIdPivotNameUseCase, ) : ViewModel() { private var _networkStatus = ConnectivityObserver.Status.Available private var networkObserverJob: Job? = null private var selectByIdPivotJob: Job? = null private var getClimatesJob: Job? = null private var getIdPivotNameListJob: Job? = null private var refreshDataJob: Job? = null private val _state = MutableStateFlow(ClimateState()) val state = _state.asStateFlow() private val _message = MutableSharedFlow<Message>() val message = _message.asSharedFlow() init { getClimates() getIdPivotNameList() observeNetworkChange() } @RequiresApi(Build.VERSION_CODES.O) fun onEvent(event: ClimateEvent) { when (event) { is ClimateEvent.SelectClimateByIdPivot -> selectByIdPivot(event.id) } } private fun getIdPivotNameList(query: String = "") { getIdPivotNameListJob?.cancel() getIdPivotNameListJob = viewModelScope.launch(Dispatchers.IO) { getIdPivotNameUseCase(query).collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> _state.update { it.copy(idPivotList = result.data) } } } } } @RequiresApi(Build.VERSION_CODES.O) private fun selectByIdPivot(id: Int) { selectByIdPivotJob?.cancel() selectByIdPivotJob = viewModelScope.launch(Dispatchers.IO) { when (val result = climateRepository.getClimatesById(id)) { is Resource.Error -> {} is Resource.Success -> _state.update { climateState -> val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val listTime = result.data.map { LocalDateTime.parse(it.timestamp, formatter) } val timeMostRecently = listTime.maxByOrNull { it } val climate = result.data.find { it.timestamp == timeMostRecently!!.format(formatter) } climateState.copy(currentClimate = climate) } } Log.d("OneClimate", _state.value.currentClimate.toString()) } } fun refreshData() { refreshDataJob?.cancel() refreshDataJob = viewModelScope.launch(Dispatchers.IO) { _state.update { it.copy(isLoading = true) } if (isNetworkAvailable()) { getClimates() } _state.update { it.copy(isLoading = false) } } } private fun getClimates() { getClimatesJob?.cancel() getClimatesJob = viewModelScope.launch(Dispatchers.IO) { if (climateRepository.fetchClimate() is Resource.Success) { climateRepository.getAllClimates("").collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> { _state.update { it.copy(climates = result.data) } } } } } } } private suspend fun isNetworkAvailable(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _message.emit(Message.StringResource(R.string.internet_error)) return false } return true } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/ClimateViewModel.kt
3131310096
package com.example.controlpivot.ui.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.repository.PivotControlRepository import com.example.controlpivot.domain.usecase.GetIdPivotNameUseCase import com.example.controlpivot.domain.usecase.GetPivotControlsWithSectorsUseCase import com.example.controlpivot.ui.screen.pivotcontrol.ControlEvent import com.example.controlpivot.ui.screen.pivotcontrol.ControlState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PivotControlViewModel( private val connectivityObserver: NetworkConnectivityObserver, private val controlRepository: PivotControlRepository, private val getIdPivotNameUseCase: GetIdPivotNameUseCase, private val getPivotControlsWithSectorsUseCase: GetPivotControlsWithSectorsUseCase, ) : ViewModel() { private var _networkStatus = ConnectivityObserver.Status.Available private var saveControlsJob: Job? = null private var saveSectorsJob: Job? = null private var networkObserverJob: Job? = null private var selectByIdPivotJob: Job? = null private var getIdPivotNameListJob: Job? = null private var getPivotControls: Job? = null private var showMessageJob: Job? = null private var refreshDataJob: Job? = null private val _state = MutableStateFlow(ControlState()) val state = _state.asStateFlow() private val _message = MutableSharedFlow<Message>() val message = _message.asSharedFlow() init { observeNetworkChange() getIdPivotNameList() getPivotControls() refreshData() } fun onEvent(event: ControlEvent) { when (event) { is ControlEvent.SaveControls -> saveControls(event.controls) is ControlEvent.SaveSectors -> saveSectors(event.sectors) is ControlEvent.SelectControlByIdPivot -> selectByIdPivot(event.id) is ControlEvent.ShowMessage -> showMessage(event.string) } } private fun refreshData() { refreshDataJob?.cancel() refreshDataJob = viewModelScope.launch(Dispatchers.IO) { if (isNetworkAvailable()) { while (true) { getPivotControls() delay(1000) } } } } private fun showMessage(string: Int) { showMessageJob?.cancel() showMessageJob = viewModelScope.launch(Dispatchers.IO) { _message.emit(Message.StringResource(string)) } } private fun getPivotControls() { getPivotControls?.cancel() getPivotControls = viewModelScope.launch(Dispatchers.IO) { val resource = controlRepository.fetchPivotControl() if (resource is Resource.Error) { _message.emit(resource.message) } } } private fun getIdPivotNameList(query: String = "") { getIdPivotNameListJob?.cancel() getIdPivotNameListJob = viewModelScope.launch(Dispatchers.IO) { getIdPivotNameUseCase(query).collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> _state.update { it.copy(idPivotList = result.data) } } } } } private fun selectByIdPivot(id: Int, query: String = "") { selectByIdPivotJob?.cancel() selectByIdPivotJob = viewModelScope.launch(Dispatchers.IO) { getPivotControlsWithSectorsUseCase(query).collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> { _state.update { controlState -> controlState.copy(controls = result.data.find { it.id == id } ?: state.value.controls) } Log.d("CONTROLS", _state.value.toString()) } } } } } private fun saveControls(controls: PivotControlEntity) { saveControlsJob?.cancel() saveControlsJob = viewModelScope.launch(Dispatchers.IO) { val result = controlRepository.addPivotControl(controls) _state.update { it.copy( controls = it.controls.copy( id = controls.id, idPivot = controls.idPivot, progress = controls.progress, isRunning = controls.isRunning, stateBomb = controls.stateBomb, wayToPump = controls.wayToPump, turnSense = controls.turnSense, ) ) } if (result is Resource.Error) { _message.emit(result.message) } } } private fun saveSectors(sectors: SectorControl) { saveSectorsJob?.cancel() saveSectorsJob = viewModelScope.launch(Dispatchers.IO) { val result = controlRepository.upsertSectorControl(sectors) selectByIdPivot(sectors.sector_control_id) if (result is Resource.Error) _message.emit(result.message) } } private suspend fun isNetworkAvailable(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _message.emit(Message.StringResource(R.string.internet_error)) _state.update { it.copy(networkStatus = false) } return false } _state.update { it.copy(networkStatus = true) } return true } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/PivotControlViewModel.kt
3502989793
package com.example.controlpivot.ui.activity import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import com.example.controlpivot.MainActivity import com.example.controlpivot.toast import com.example.controlpivot.ui.screen.login.LoginScreen import com.example.controlpivot.ui.theme.ControlPivotTheme import com.example.controlpivot.ui.viewmodel.LoginViewModel import kotlinx.coroutines.flow.collectLatest import org.koin.androidx.viewmodel.ext.android.viewModel class LoginActivity: ComponentActivity() { private val loginViewModel by viewModel<LoginViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ControlPivotTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val state by loginViewModel.state.collectAsState() LoginScreen(state = state, onEvent = loginViewModel::onEvent) LaunchedEffect(Unit) { loginViewModel.isLogged.observe(this@LoginActivity) { if (it) { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() } } loginViewModel.message.collectLatest { message -> [email protected](message) } } } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/activity/LoginActivity.kt
3545299348
package com.example.controlpivot.ui.activity import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.example.controlpivot.MainActivity import com.example.controlpivot.ui.screen.SplashScreen import com.example.controlpivot.ui.theme.ControlPivotTheme import com.example.controlpivot.ui.viewmodel.SplashViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class SplashActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ControlPivotTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val splashViewModel by viewModel<SplashViewModel>() SplashScreen () splashViewModel.checkLogin() splashViewModel.isLogged.observe(this) { if (it == null) return@observe if (it) startActivity(Intent(this, MainActivity::class.java)) else startActivity(Intent(this, LoginActivity::class.java)) finish() } } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/activity/SplashActivity.kt
2221237678
package com.example.controlpivot.ui.navigation import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.currentBackStackEntryAsState import com.example.controlpivot.ui.screen.createpivot.BottomNavScreen @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class) @Composable fun BottomNavBarAnimation( navController: NavController, ) { val screens = listOf( BottomNavScreen.PivotMachines, BottomNavScreen.Climate, BottomNavScreen.Control, BottomNavScreen.Settings ) val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route ElevatedCard( Modifier .height(75.dp), shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp), colors = CardDefaults.cardColors( containerColor = Color.White ) ) { Row( Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically, ) { screens.forEach { screen -> val isSelected = currentRoute?.contains(screen.route) ?: false val animatedWeight by animateFloatAsState( targetValue = if (isSelected) 1.5f else .5f, label = "" ) Box( modifier = Modifier.weight(animatedWeight), contentAlignment = Alignment.Center, ) { val interactionSource = remember { MutableInteractionSource() } BottomNavItem( modifier = Modifier.clickable( interactionSource = interactionSource, indication = null ) { navController.navigate(screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } }, screen = screen, isSelected = isSelected ) } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/navigation/BottomNavBarAnimated.kt
4248438515
package com.example.controlpivot.ui.navigation import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.shadow import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.screen.createpivot.BottomNavScreen import com.example.controlpivot.ui.theme.GreenLow @Composable fun BottomNavItem( modifier: Modifier = Modifier, screen: BottomNavScreen, isSelected: Boolean, ) { val animatedHeight by animateDpAsState( targetValue = if (isSelected) 50.dp else 40.dp, label = "" ) val animatedElevation by animateDpAsState( targetValue = if (isSelected) 15.dp else 0.dp, label = "" ) val animatedAlpha by animateFloatAsState( targetValue = if (isSelected) 1f else .5f, label = "" ) val animatedIconSize by animateDpAsState( targetValue = if (isSelected) 28.dp else 28.dp, animationSpec = spring( stiffness = Spring.StiffnessLow, dampingRatio = Spring.DampingRatioMediumBouncy ), label = "" ) val animatedColor by animateColorAsState( targetValue = if (isSelected) GreenLow else MaterialTheme.colorScheme.background, label = "" ) Box( modifier = modifier .background(color = MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center, ) { Row( modifier = Modifier .height(animatedHeight) .shadow( elevation = 0.dp, shape = RoundedCornerShape(20.dp) ) .background( color = animatedColor, shape = RoundedCornerShape(20.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ) { FlipIcon( modifier = Modifier .align(Alignment.CenterVertically) .fillMaxHeight() .padding(start = 11.dp) .alpha(animatedAlpha) .size(animatedIconSize), isActive = isSelected, activeIcon = screen.activeIcon, inactiveIcon = screen.inactiveIcon, contentDescription = screen.route ) AnimatedVisibility(visible = isSelected) { Text( text = screen.route, modifier = Modifier.padding(start = 8.dp, end = 15.dp), maxLines = 1, ) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/navigation/BottomNavItem.kt
1084265905
package com.example.controlpivot.ui.navigation import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.foundation.layout.Box import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource @Composable fun FlipIcon( modifier: Modifier = Modifier, isActive: Boolean, activeIcon: Int, inactiveIcon: Int, contentDescription: String, ) { val animationRotation by animateFloatAsState( targetValue = if (isActive) 180f else 0f, animationSpec = spring( stiffness = Spring.StiffnessLow, dampingRatio = Spring.DampingRatioMediumBouncy ), label = "" ) Box( modifier = modifier //.graphicsLayer { rotationY = animationRotation }, ,contentAlignment = Alignment.Center, ) { Icon( painter = painterResource(id = if (animationRotation > 90f) activeIcon else inactiveIcon), contentDescription = contentDescription, ) } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/navigation/FlipIcon.kt
2713357149
package com.example.controlpivot.ui.component import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredWidthIn import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Scaffold import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.convertCharacter import com.example.controlpivot.ui.theme.GreenHigh @SuppressLint("UnusedMaterialScaffoldPaddingParameter", "UnusedMaterial3ScaffoldPaddingParameter") @Composable fun BottomSheetIrrigation( checkIrrigate: Boolean, sector: Int, dosage: Int, onEvent: (AddTagEvent) -> Unit, ) { var bottomCheckIrrigate by remember { mutableStateOf(checkIrrigate) } var bottomDosage by remember { mutableIntStateOf(dosage) } Scaffold( modifier = Modifier .wrapContentHeight() .background(Color.White) ) { Column( modifier = Modifier .wrapContentHeight() .background(Color.White), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Box( modifier = Modifier, contentAlignment = Alignment.TopCenter ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( modifier = Modifier.padding(bottom = 10.dp), text = "SECTOR $sector", style = MaterialTheme.typography.headlineSmall ) Row( modifier = Modifier .fillMaxWidth(0.9f) .height(60.dp) .background( color = Color.LightGray.copy(alpha = 0.3f), shape = RoundedCornerShape(6.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( modifier = Modifier.padding(start = 15.dp), text = "Regar", style = MaterialTheme.typography.headlineSmall ) Box( modifier = Modifier.padding(end = 75.dp) ) { CircularCheckBox( checked = bottomCheckIrrigate, onCheckedChange = { bottomCheckIrrigate = !bottomCheckIrrigate }, borderColor = Color.DarkGray ) } } Spacer(modifier = Modifier.height(15.dp)) Row( modifier = Modifier .fillMaxWidth(0.9f) .height(60.dp) .background( color = Color.LightGray.copy(alpha = 0.3f), shape = RoundedCornerShape(6.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( modifier = Modifier.padding(start = 15.dp), text = "Dosificación", style = MaterialTheme.typography.headlineSmall ) Row( modifier = Modifier.padding(end = 15.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = Modifier .size(35.dp) .clip(RoundedCornerShape(10.dp)) .background(Color.LightGray.copy(alpha = 0.6f)) .padding(4.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { if (bottomDosage > 0) bottomDosage = bottomDosage.dec() } ) { Icon( painter = painterResource(id = R.drawable.minus), contentDescription = null, modifier = Modifier .size(25.dp) .padding(2.dp) .align(Alignment.Center), tint = Color.Black.copy(alpha = 0.5f) ) } BasicTextField( value = bottomDosage.toString(), onValueChange = { it.convertCharacter() bottomDosage = if (it.isEmpty()) 0 else it.toInt() }, modifier = Modifier .requiredWidthIn(min = 20.dp, max = 100.dp) .width(35.dp) .height(30.dp) .background(Color.Transparent) .border(0.dp, Color.Transparent) .align(Alignment.CenterVertically) .padding(start = 4.dp, end = 4.dp), textStyle = MaterialTheme.typography.titleLarge.copy( textAlign = TextAlign.Center ), keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), ) Box( modifier = Modifier .size(35.dp) .clip(RoundedCornerShape(10.dp)) .background(Color.LightGray.copy(alpha = 0.6f)) .padding(4.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { bottomDosage = bottomDosage.inc() } ) { Icon( painter = painterResource(id = R.drawable.plus), contentDescription = null, modifier = Modifier .size(25.dp) .padding(2.dp) .align(Alignment.Center), tint = Color.Black.copy(alpha = 0.5f) ) } } } Spacer(modifier = Modifier.height(15.dp)) Row( modifier = Modifier .fillMaxWidth(0.9f) .height(110.dp) .background( color = Color.LightGray.copy(alpha = 0.3f), shape = RoundedCornerShape(6.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { SpeedSelector(onSpeedChanged = {}) } } } Spacer(modifier = Modifier.height(15.dp)) TextButton( enabled = true, modifier = Modifier .fillMaxWidth() .padding(15.dp), onClick = { onEvent( AddTagEvent.Save( bottomCheckIrrigate, bottomDosage ) ) }, colors = ButtonDefaults.elevatedButtonColors( containerColor = GreenHigh, contentColor = Color.White ) ) { Text( modifier = Modifier .align(Alignment.CenterVertically) .padding(5.dp), fontSize = 20.sp, fontWeight = FontWeight.Bold, text = "Aceptar" ) } } } } sealed class AddTagEvent() { class Save(val checkIrrigate: Boolean, val dosage: Int) : AddTagEvent() object Close : AddTagEvent() } @Preview(showSystemUi = true, showBackground = true) @Composable fun SheetPreview() { BottomSheetIrrigation(checkIrrigate = true, sector = 1, dosage = 0, onEvent = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/BottomSheetIrrigation.kt
2919499708
package com.example.controlpivot.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.LocalTextStyle import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.theme.GreenHigh @Composable fun SearchBar( hint: String = "", textStyle: TextStyle = LocalTextStyle.current, onValueChange: (String) -> Unit, ) { var text by rememberSaveable { mutableStateOf(hint) } CustomTextField( value = text, onValueChange = { text = it.changeValueBehavior(hint, text) onValueChange(if (text != hint) text else "") }, modifier = Modifier .fillMaxWidth() .wrapContentHeight(align = Alignment.Top) .clip(RoundedCornerShape(20.dp)) .background(color = Color.LightGray.copy(alpha = 0.25f)) .padding(3.dp), textStyle = if (text == hint) textStyle.copy(color = GreenHigh.copy(alpha = 0.4f)) else textStyle, leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = null, modifier = Modifier .size(40.dp) .padding(10.dp), tint = GreenHigh.copy(alpha = 0.4f) ) }, trailingIcon = { Icon( imageVector = Icons.Default.Close, contentDescription = null, modifier = Modifier .size(38.dp) .padding(10.dp) .clickable( indication = null, interactionSource = remember { MutableInteractionSource() }) { onValueChange("") text = hint }, tint = GreenHigh.copy(alpha = 0.4f) ) }, singleLine = true ) } private fun String.changeValueBehavior( hint: String, text: String, maxLength: Long = Long.MAX_VALUE ): String { if (this.length > maxLength) return text if (this.isEmpty()) return hint if (text == hint) { var tempText = this hint.forEach { c -> tempText = tempText.replaceFirst(c.toString(), "") } return tempText } return this }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/SearchBar.kt
3213918555
package com.example.controlpivot.ui.component import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Text import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.convertCharacter import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenLow import com.example.controlpivot.ui.theme.PurpleGrey40 @Composable fun PasswordTextField( label: String, value: Any, keyboardType: KeyboardType, leadingIcon: Int, trailingIcon: @Composable()(() -> Unit)? = null, singleLine: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, suffix: String = "", visualTransformation: VisualTransformation = VisualTransformation.None, imeAction: ImeAction = ImeAction.Next, onValueChange: (String) -> Unit, ) { var text by remember { mutableStateOf(if (value == 0.0) "" else value.toString()) } var isError by remember { mutableStateOf(false) } var isFocused by remember { mutableStateOf(false) } var passwordHidden by rememberSaveable { mutableStateOf(true) } var isTextFieldFilled by remember { mutableStateOf(false) } val keyboardController = LocalSoftwareKeyboardController.current val focusManager = LocalFocusManager.current val errorMessage = "Campo vacío" OutlinedTextField( value = text, onValueChange = { text = it onValueChange( if(value is Double && text.isEmpty()) "0.0" else text ) isError = it.isEmpty() isTextFieldFilled = it.isNotEmpty() }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(top = 8.dp) .onFocusChanged { isFocused = it.isFocused if (isTextFieldFilled) { //focusManager.clearFocus() } }, label = { Text( text = if (isError) "${label}*" else label, fontSize = if (isFocused || text.isNotEmpty() || value is Long) 12.sp else 15.sp, color = when { isFocused && !isError -> GreenHigh !isFocused && text.isNotEmpty() -> GreenHigh isError -> Color.Red else -> Color.Black } ) }, singleLine = singleLine, readOnly = readOnly, colors = OutlinedTextFieldDefaults.colors( unfocusedBorderColor = if (text.isEmpty()) Color.Black else GreenHigh, errorBorderColor = Color.Red, focusedLabelColor = GreenHigh, unfocusedContainerColor = if (text.isEmpty()) GreenLow else Color.Transparent ), leadingIcon = { Icon( modifier = Modifier .size(24.dp), painter = painterResource(id = leadingIcon), contentDescription = label, tint = PurpleGrey40 ) }, trailingIcon = { IconButton(onClick = { passwordHidden = !passwordHidden }) { val visibilityIcon = if (passwordHidden) R.drawable.show else R.drawable.hide Icon( painter = painterResource(id = visibilityIcon), contentDescription = null, modifier = Modifier .size(24.dp), tint = PurpleGrey40 ) } }, isError = isError, keyboardOptions = KeyboardOptions.Default.copy( imeAction = imeAction, keyboardType = keyboardType ), visualTransformation = if (passwordHidden) PasswordVisualTransformation() else VisualTransformation.None, keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() } ), supportingText = { Text( text = if (isError) errorMessage else "", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.End, color = Color.Red, fontSize = 10.sp, ) }, suffix = { Text(text = suffix) }, shape = RoundedCornerShape(25.dp), textStyle = textStyle ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/PasswordTextField.kt
4199048733
package com.example.controlpivot.ui.component import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenMedium import kotlin.math.roundToInt @Composable fun SpeedSelector( onSpeedChanged: (Float) -> Unit, ) { var speed by remember { mutableFloatStateOf(0f) } Column( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Row( verticalAlignment = Alignment.CenterVertically, ) { Text( text = "Velocidad del Motor: ", style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(bottom = 6.dp, end = 4.dp) ) Text( text = "${speed.roundToInt()} m/s", style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold), modifier = Modifier.padding(bottom = 4.dp) ) } Spacer(modifier = Modifier.height(20.dp)) SpeedSlider( value = speed, onValueChange = { speed = it onSpeedChanged(it) } ) } } @Composable fun SpeedSlider( value: Float, onValueChange: (Float) -> Unit, ) { val thumbSize = 15.dp Slider( value = value, valueRange = 0f..100f, steps = 10, onValueChange = onValueChange, modifier = Modifier .fillMaxWidth() .graphicsLayer { translationY = -thumbSize.toPx() / 2 } .padding(7.dp), colors = SliderDefaults.colors( thumbColor = GreenHigh, activeTrackColor = GreenMedium, inactiveTrackColor = Color.Gray ) ) } @Preview @Composable fun SpeedSelectorPreview() { SpeedSelector(onSpeedChanged = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/SpeedSelector.kt
3086106301
package com.example.controlpivot.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.triStateToggleable import androidx.compose.material.CheckboxColors import androidx.compose.material.CheckboxDefaults import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Check import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun CustomCheckBox( checked: Boolean, onCheckedChange: ((Boolean) -> Unit)?, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, colors: CheckboxColors = CheckboxDefaults.colors(), ) { val selectableModifier = if (onCheckedChange != null) { Modifier.triStateToggleable( state = ToggleableState(checked), onClick = { onCheckedChange(!checked) }, enabled = enabled, interactionSource = interactionSource, indication = null ) } else { Modifier } Box( modifier = modifier .then(selectableModifier) .background( if (checked) colors.boxColor( enabled = enabled, state = ToggleableState.On ).value else colors.boxColor( enabled = enabled, state = ToggleableState.Off ).value ) ) { if (checked) Icon( imageVector = Icons.Rounded.Check, contentDescription = null, tint = colors.checkmarkColor( state = ToggleableState.On ).value, modifier = Modifier .padding(defaultCheckPadding) .fillMaxSize() ) } } private val defaultCheckPadding = 4.dp @Preview(showSystemUi = true, showBackground = true) @Composable fun CustomCheckBoxPreview() { CircularCheckBox(checked = true, onCheckedChange = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/CustomCheckBox.kt
520797011
package com.example.controlpivot.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.LocalTextStyle import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Clear import androidx.compose.material.icons.rounded.Search import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun CustomTextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, textStyle: TextStyle = LocalTextStyle.current, placeholder: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null, trailingIcon: @Composable (() -> Unit)? = null, singleLine: Boolean = false, maxLines: Int = Int.MAX_VALUE, visualTransformation: VisualTransformation = VisualTransformation.None, keyboardOptions: KeyboardOptions = KeyboardOptions.Default ) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled, textStyle = textStyle, decorationBox = { innerTextField -> Row(verticalAlignment = CenterVertically) { if (leadingIcon != null) { Box { leadingIcon() } } if (placeholder != null) { placeholder() } else { Box( modifier = Modifier .weight(1f) .padding(start = 2.dp, top = 6.dp, bottom = 6.dp, end = 8.dp) ) { innerTextField() } } if (trailingIcon != null) { Box { trailingIcon() } } } }, singleLine = singleLine, visualTransformation = visualTransformation, keyboardOptions = keyboardOptions ) } @Preview(showSystemUi = true, showBackground = true) @Composable fun CustomTextFieldPreview() { CustomTextField( value = "text", onValueChange = { }, modifier = Modifier .fillMaxWidth() .wrapContentHeight(align = Alignment.Top) .clip(RoundedCornerShape(6.dp)) .background(color = Color.LightGray) .padding(5.dp), leadingIcon = { Icon( imageVector = Icons.Rounded.Search, //painter = painterResource(id = R.drawable.round_search), contentDescription = null, modifier = Modifier.padding(start = 10.dp) ) }, trailingIcon = { Icon( imageVector = Icons.Rounded.Clear, //painter = painterResource(id = R.drawable.round_clear), contentDescription = null, modifier = Modifier.padding(end = 4.dp) ) }, singleLine = true ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/CustomTextField.kt
1857447184
package com.example.controlpivot.ui.component import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.toSize import com.example.controlpivot.ui.model.IdPivotModel @Composable fun PivotSpinner( optionList: List<IdPivotModel>, selectedOption: String, onSelected: (Int) -> Unit, loading: () -> Unit, ) { val context = LocalContext.current var expandedState by remember { mutableStateOf(false) } var option = selectedOption var textFieldSize by remember { mutableStateOf(Size.Zero) } val icon = if (expandedState) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown Column( modifier = Modifier .padding(10.dp) ) { TextField( value = option, onValueChange = { option = it }, trailingIcon = { Icon( imageVector = icon, contentDescription = "", Modifier.clickable { expandedState = !expandedState } ) }, modifier = Modifier .onGloballyPositioned { coordinates -> textFieldSize = coordinates.size.toSize() }, label = { Text( text = "Seleccionar Máquina de Pivote", fontSize = if (selectedOption.isNotEmpty()) 10.sp else 18.sp, fontWeight = if (selectedOption.isNotEmpty()) FontWeight.Thin else FontWeight.Bold, ) }, readOnly = true, textStyle = TextStyle( fontSize = 18.sp, fontWeight = FontWeight.Bold, ), colors = OutlinedTextFieldDefaults.colors( focusedContainerColor = Color.White, unfocusedContainerColor = Color.White ) ) DropdownMenu( expanded = expandedState, onDismissRequest = { expandedState = false }, modifier = Modifier .width(with(LocalDensity.current) { textFieldSize.width.toDp() }), ) { optionList.forEach { idPivotModel -> DropdownMenuItem( text = { Text( text = idPivotModel.pivotName, fontSize = 18.sp, fontWeight = FontWeight.Bold, ) }, onClick = { option = idPivotModel.pivotName Toast.makeText( context, "" + option, Toast.LENGTH_LONG ).show() onSelected(idPivotModel.idPivot) loading() }) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/PivotSpinner.kt
3416855046
package com.example.controlpivot.ui.component import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.center import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.ui.theme.Green import com.example.controlpivot.ui.theme.GreenHigh import kotlin.math.absoluteValue import kotlin.math.atan import kotlin.math.cos import kotlin.math.sin @Composable fun QuadrantIrrigation( onClick: (Int) -> Unit, isRunning: Boolean, pauseIrrigation: () -> Unit, progress: Float, sectorStateList: List<Boolean>, ) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Spacer(modifier = Modifier.height(16.dp)) QuadrantView( progress, getSector = { onClick(it) }, sectorStateList = sectorStateList) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Center ) { Button( onClick = { pauseIrrigation() }, modifier = Modifier .weight(1f) .padding(8.dp) .wrapContentWidth() ) { Icon( modifier = Modifier .size(30.dp), painter = if (isRunning) painterResource(id = R.drawable.pause) else painterResource(id = R.drawable.play), contentDescription = null ) Spacer(modifier = Modifier.width(10.dp)) Text( fontSize = 20.sp, text = if (isRunning) "Pausar" else "Iniciar" ) } } } } @Composable fun QuadrantView( progress: Float, getSector: (Int) -> Unit, sectorStateList: List<Boolean>, ) { var center by remember { mutableStateOf(Offset.Zero) } val strokeWidth: Dp = 1.dp Box( modifier = Modifier .fillMaxWidth() ) { Canvas( modifier = Modifier .aspectRatio(1f) .onGloballyPositioned { coordinates -> center = Offset( coordinates.size.width / 2f, coordinates.size.height / 2f ) } ) { val centerX = size.width / 2 val centerY = size.height / 2 val radius = size.width / 2 drawCircle( color = Green, radius = radius, ) drawCircle( color = Color.Black, center = size.center, radius = radius, style = Stroke(4f) ) drawArc( color = GreenHigh, startAngle = 0f, sweepAngle = progress, useCenter = true ) val angleIncrement = 360f / 4 var currentAngle = 0f for (i in 1..4) { var startAngle = currentAngle var endAngle = currentAngle - angleIncrement val endRadians = Math.toRadians(endAngle.absoluteValue.toDouble()) val endX = centerX + (radius * cos(endRadians)).toFloat() val endY = centerY + (radius * sin(endRadians)).toFloat() val fillProgress = progress.coerceIn(startAngle.absoluteValue, endAngle.absoluteValue) drawLine( color = Color.Black, start = Offset(centerX, centerY), end = Offset(endX, endY), strokeWidth = strokeWidth.toPx() ) drawLine( color = Color.Black, start = Offset(centerX, centerY), end = calculateEndPoint(centerX, centerY, radius, fillProgress), strokeWidth = strokeWidth.toPx() ) currentAngle = endAngle } } Row( modifier = Modifier.align(Alignment.Center) ) { Box( modifier = Modifier .aspectRatio(1f) .fillMaxSize() .padding(20.dp) ) { Box( modifier = Modifier .size(170.dp) .align(Alignment.BottomEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(1) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(1) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 1", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[0], onCheckedChange = {}, borderColor = Color.DarkGray ) } } Box( modifier = Modifier .size(170.dp) .align(Alignment.BottomStart) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(2) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .align(Alignment.TopEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(2) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 2", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[1], onCheckedChange = {}, borderColor = Color.DarkGray ) } } Box( modifier = Modifier .size(170.dp) .align(Alignment.TopStart) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(3) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .align(Alignment.BottomEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(3) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 3", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[2], onCheckedChange = {}, borderColor = Color.DarkGray ) } } Box( modifier = Modifier .size(170.dp) .align(Alignment.TopEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(4) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .align(Alignment.BottomStart) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(4) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 4", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[3], onCheckedChange = {}, borderColor = Color.DarkGray ) } } } } } } private fun calculateEndPoint( centerX: Float, centerY: Float, radius: Float, angle: Float, ): Offset { val radians = Math.toRadians(angle.toDouble()) val endX = centerX + (radius * cos(radians)).toFloat() val endY = centerY + (radius * sin(radians)).toFloat() return Offset(endX, endY) } private fun calculateAngle( centerX: Float, centerY: Float, radius: Float, angle: Float, ): Float { var sectorAngle: Float val radians = Math.toRadians(angle.toDouble()) val endX = centerX + (radius * cos(radians)) val endY = centerY + (radius * sin(radians)) sectorAngle = if (endY.toInt() == 664) { Math.toDegrees( atan((endY - centerY) / (endX - centerX)) ).toFloat() } else { Math.toDegrees( atan((endX - centerX).absoluteValue / (endY - centerY).absoluteValue) ).toFloat() } return sectorAngle }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/QuadrantIrrigation.kt
2568958305
package com.example.controlpivot.ui.component import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Text import androidx.compose.material3.Icon import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.convertCharacter import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenLow import com.example.controlpivot.ui.theme.PurpleGrey40 @Composable fun OutlinedTextFieldWithValidation( label: String, value: Any, keyboardType: KeyboardType, leadingIcon: Int, trailingIcon: @Composable()(() -> Unit)? = null, singleLine: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, suffix: String = "", visualTransformation: VisualTransformation = VisualTransformation.None, imeAction: ImeAction = ImeAction.Next, onValueChange: (String) -> Unit, ) { var text by remember { mutableStateOf(if (value == 0.0) "" else value.toString()) } var isError by remember { mutableStateOf(false) } var isFocused by remember { mutableStateOf(false) } var isTextFieldFilled by remember { mutableStateOf(false) } val keyboardController = LocalSoftwareKeyboardController.current val focusManager = LocalFocusManager.current val errorMessage = "Campo vacío" OutlinedTextField( value = text, onValueChange = { if (keyboardType == KeyboardType.Text) text = it else text = it.convertCharacter() onValueChange( if(value is Double && text.isEmpty()) "0.0" else text ) isError = it.isEmpty() isTextFieldFilled = it.isNotEmpty() }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(top = 8.dp) .onFocusChanged { isFocused = it.isFocused if (isTextFieldFilled) { //focusManager.clearFocus() } }, label = { Text( text = if (isError) "${label}*" else label, fontSize = if (isFocused || text.isNotEmpty() || value is Long) 12.sp else 15.sp, color = when { isFocused && !isError -> GreenHigh !isFocused && text.isNotEmpty() -> GreenHigh isError -> Color.Red else -> Color.Black } ) }, singleLine = singleLine, readOnly = readOnly, colors = OutlinedTextFieldDefaults.colors( unfocusedBorderColor = if (text.isEmpty()) Color.Black else GreenHigh, errorBorderColor = Color.Red, focusedLabelColor = GreenHigh, unfocusedContainerColor = if (text.isEmpty()) GreenLow else Color.Transparent ), leadingIcon = { Icon( modifier = Modifier .size(24.dp), painter = painterResource(id = leadingIcon), contentDescription = label, tint = PurpleGrey40 ) }, trailingIcon = { trailingIcon }, isError = isError, keyboardOptions = KeyboardOptions.Default.copy( imeAction = imeAction, keyboardType = keyboardType ), visualTransformation = visualTransformation, keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() } ), supportingText = { Text( text = if (isError) errorMessage else "", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.End, color = Color.Red, fontSize = 10.sp, ) }, suffix = { Text(text = suffix) }, shape = RoundedCornerShape(25.dp), textStyle = textStyle ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/OutlinedTextFieldWithValidation.kt
3993312052
package com.example.controlpivot.ui.component import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.CheckboxColors import androidx.compose.material.CheckboxDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.theme.GreenHigh @Composable fun CircularCheckBox( size: Dp = defaultSize, borderStroke: Dp = defaultBorderStroke, borderColor: Color = defaultBorderColor, checked: Boolean, onCheckedChange: ((Boolean) -> Unit)?, enabled: Boolean = true, colors: CheckboxColors = CheckboxDefaults.colors( checkedColor = defaultCheckedColor, checkmarkColor = defaultCheckMarkColor, ) ) { CustomCheckBox( checked = checked, onCheckedChange = onCheckedChange, modifier = Modifier .size(size) .clip(CircleShape) .border( border = BorderStroke( width = if (checked) 0.dp else borderStroke, color = borderColor ), CircleShape ), enabled = enabled, colors = colors ) } private val defaultSize = 25.dp private val defaultBorderStroke = 2.dp private val defaultBorderColor = Color.LightGray private val defaultCheckedColor = GreenHigh.copy(alpha = 0.7f) private val defaultCheckMarkColor = Color.White @Preview @Composable fun CircularCheckBoxPreview() { CircularCheckBox(checked = true, onCheckedChange = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/CircularCheckBox.kt
3396838936
package com.example.controlpivot.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val GreenLow = Color(0xFFDCEDDC) val Green = Color(0xFFBDDEBD) val GreenMedium = Color(0xFF67DE6E) val GreenHigh = Color(0xFF04980F) val DarkGray = Color(0xFF43454A) val MediumGray = Color(0xFF727477)
pivot-control/app/src/main/java/com/example/controlpivot/ui/theme/Color.kt
3201920971
package com.example.controlpivot.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = GreenHigh, secondary = Green, tertiary = GreenMedium ) private val LightColorScheme = lightColorScheme( primary = GreenHigh, secondary = Green, tertiary = GreenMedium /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ControlPivotTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicLightColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/theme/Theme.kt
30715343
package com.example.controlpivot.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
pivot-control/app/src/main/java/com/example/controlpivot/ui/theme/Type.kt
944949076
package com.example.controlpivot.ui.screen.createpivot import com.example.controlpivot.data.local.model.PivotMachineEntity sealed class PivotMachineEvent { data class SearchMachine(val query: String) : PivotMachineEvent() data class DeleteMachine(val machineId: Int) : PivotMachineEvent() data class CreateMachine(val machine: PivotMachineEntity) : PivotMachineEvent() data class SelectMachine(val id: Int) : PivotMachineEvent() object ResetDataMachine : PivotMachineEvent() }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachineEvent.kt
1621706090
package com.example.controlpivot.ui.screen.createpivot import android.app.Activity import androidx.navigation.NavController import com.example.controlpivot.ui.screen.Screen sealed class ScreensNavEvent { object ToNewPivotMachine : ScreensNavEvent() object ToPivotMachineList : ScreensNavEvent() object ToClimate : ScreensNavEvent() object ToPivotControl : ScreensNavEvent() object ToSession : ScreensNavEvent() object Back : ScreensNavEvent() } fun Activity.pivotMachineNavEvent( navController: NavController, navEvent: ScreensNavEvent, ) { when (navEvent) { ScreensNavEvent.Back -> { navController.popBackStack() } ScreensNavEvent.ToNewPivotMachine -> { navController.navigate(Screen.PivotMachines.Machine.route) } ScreensNavEvent.ToPivotMachineList -> { navController.navigate(Screen.PivotMachines.List.route) } ScreensNavEvent.ToClimate -> { navController.navigate(Screen.Climate.route) } ScreensNavEvent.ToPivotControl -> { navController.navigate(Screen.Control.route) } ScreensNavEvent.ToSession -> { navController.navigate(Screen.Session.route) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/ScreensNavEvent.kt
582678981
package com.example.controlpivot.ui.screen.createpivot import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.filled.Done import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.example.controlpivot.R import com.example.controlpivot.ui.component.OutlinedTextFieldWithValidation import com.example.controlpivot.ui.theme.GreenMedium @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun AddEditPivotMachineScreen( state: PivotMachineState, onEvent: (PivotMachineEvent) -> Unit, navEvent: (ScreensNavEvent) -> Unit, ) { val scrollState = rememberScrollState() var nameTextValue = state.currentMachine.name var locationTextValue = state.currentMachine.location var endowmentTextValue = state.currentMachine.endowment var flowTextValue = state.currentMachine.flow var pressureTextValue = state.currentMachine.pressure var lengthTextValue = state.currentMachine.length var areaTextValue = state.currentMachine.area var powerTextValue = state.currentMachine.power var speedTextValue = state.currentMachine.speed var efficiencyTextValue = state.currentMachine.efficiency Scaffold( modifier = Modifier.padding(bottom = 75.dp), floatingActionButton = { FloatingActionButton( onClick = { onEvent( PivotMachineEvent.CreateMachine( state.currentMachine.copy( name = nameTextValue, location = locationTextValue, endowment = endowmentTextValue, flow = flowTextValue, pressure = pressureTextValue, length = lengthTextValue, area = areaTextValue, power = powerTextValue, speed = speedTextValue, efficiency = efficiencyTextValue, isSave = false, ) ) ) }, shape = FloatingActionButtonDefaults.extendedFabShape, containerColor = GreenMedium, contentColor = Color.Black, modifier = Modifier ) { Icon(imageVector = Icons.Default.Done, contentDescription = "Save pivot machine") } } ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(state = scrollState) .padding(start = 15.dp, end = 15.dp) ) { Spacer(modifier = Modifier.height(20.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .wrapContentSize() .clip(RoundedCornerShape(15.dp)) .background(Color.LightGray.copy(alpha = 0.2f)) .clickable { navEvent(ScreensNavEvent.Back) }, ) { Icon( imageVector = Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = null, modifier = Modifier .size(40.dp) .padding(7.dp), tint = Color.Gray, ) } Spacer(modifier = Modifier.width(10.dp)) Column { Text( text = stringResource(id = R.string.new_pivot_machine), style = MaterialTheme.typography.h5.copy(fontFamily = FontFamily.SansSerif), modifier = Modifier .padding(start = 5.dp) ) } } Spacer(modifier = Modifier.height(10.dp)) HorizontalDivider( modifier = Modifier.height(5.dp), color = Color.Black ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextFieldWithValidation( label = "Nombre", value = nameTextValue, keyboardType = KeyboardType.Text, leadingIcon = R.drawable.ic_name, onValueChange = { nameTextValue = it.toString() } ) OutlinedTextFieldWithValidation( label = "Ubicación", value = locationTextValue, keyboardType = KeyboardType.Text, leadingIcon = R.drawable.ic_location, onValueChange = { locationTextValue = it.toString() }, singleLine = false, ) OutlinedTextFieldWithValidation( label = "Dotación", value = endowmentTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_flow, suffix = "L/seg ha", onValueChange = { endowmentTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Caudal Nominal", value = flowTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_endowment, suffix = "L/seg", onValueChange = { flowTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Presión", value = pressureTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_pressure, suffix = "kPa", onValueChange = { pressureTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Longitud Total", value = lengthTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_length, suffix = "m", onValueChange = { lengthTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Área", value = areaTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_area, suffix = "m^2", onValueChange = { areaTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Potencia", value = powerTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_power, suffix = "kW", onValueChange = { powerTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Velocidad del Motor", value = speedTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_speed2, suffix = "rpm", onValueChange = { speedTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Eficiencia", value = efficiencyTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_efficiency, suffix = "%", onValueChange = { efficiencyTextValue = it.toDouble() }, imeAction = ImeAction.Done ) Spacer(modifier = Modifier.height(10.dp)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/AddEditPivotMachineScreen.kt
2817726513
package com.example.controlpivot.ui.screen.createpivot import androidx.annotation.DrawableRes import com.example.controlpivot.R import com.example.controlpivot.ui.screen.Screen sealed class BottomNavScreen( val route: String, @DrawableRes val activeIcon: Int, @DrawableRes val inactiveIcon: Int, ) { object PivotMachines : BottomNavScreen( Screen.PivotMachines.route, R.drawable.writing_filled, R.drawable.writing_outlined ) object Climate : BottomNavScreen( Screen.Climate.route, R.drawable.cloudy_day, R.drawable.cloudy_day_outlined ) object Control : BottomNavScreen( Screen.Control.route, R.drawable.control_filled, R.drawable.control_outlined ) object Settings : BottomNavScreen( Screen.Session.route, R.drawable.user_filled, R.drawable.user_outlined ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/BottomNavScreen.kt
4214560250
package com.example.controlpivot.ui.screen.createpivot import android.annotation.SuppressLint import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.PullRefreshState import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.ui.component.SearchBar import com.example.controlpivot.ui.theme.GreenMedium @OptIn(ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun PivotMachineListScreen( state: PivotMachineState, onEvent: (PivotMachineEvent) -> Unit, navEvent: (ScreensNavEvent) -> Unit, pullRefreshState: PullRefreshState, ) { val lazyListState = rememberLazyListState() Scaffold( modifier = Modifier, floatingActionButton = { AnimatedVisibility( lazyListState.canScrollForward || state.machines.isEmpty() || (!lazyListState.canScrollForward && !lazyListState.canScrollBackward), enter = scaleIn(), exit = scaleOut(), modifier = Modifier .padding(bottom = 75.dp) .wrapContentSize() ) { FloatingActionButton( onClick = { onEvent(PivotMachineEvent.ResetDataMachine) navEvent(ScreensNavEvent.ToNewPivotMachine) }, shape = FloatingActionButtonDefaults.extendedFabShape, containerColor = GreenMedium, contentColor = Color.Black, ) { Icon( imageVector = Icons.Default.Add, contentDescription = "Add pivot machine" ) } } } ) { Box( modifier = Modifier .fillMaxSize() .pullRefresh(pullRefreshState) .padding(bottom = 75.dp), ) { Column( modifier = Modifier .padding(horizontal = 15.dp), verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.height(20.dp)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Box( modifier = Modifier .wrapContentSize() .clip(RoundedCornerShape(15.dp)) .background(Color.White.copy(alpha = 0.2f)) .clickable { }, ) { Icon( painter = painterResource(id = R.drawable.task_list), contentDescription = null, modifier = Modifier .size(30.dp) .padding(2.dp), ) } Spacer(modifier = Modifier.width(10.dp)) Text( text = stringResource(id = R.string.pivot_machines), style = MaterialTheme.typography.h5.copy(fontFamily = FontFamily.SansSerif), modifier = Modifier .padding(start = 5.dp), ) } Spacer(modifier = Modifier.height(10.dp)) SearchBar( hint = stringResource(id = R.string.search), textStyle = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Thin, fontStyle = FontStyle.Italic ) ) { onEvent(PivotMachineEvent.SearchMachine(it)) } Spacer(modifier = Modifier.height(10.dp)) LazyColumn( state = lazyListState, modifier = Modifier .fillMaxSize() .padding(bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { items(state.machines) { machine -> var stateHeight by remember { mutableStateOf(true) } val tooltipState = rememberTooltipState() val scope = rememberCoroutineScope() PivotMachineItem( machine = machine, onDeleteClick = { onEvent( PivotMachineEvent.DeleteMachine(machine.id) ) }, onClick = { onEvent( PivotMachineEvent.SelectMachine(machine.id) ) navEvent(ScreensNavEvent.ToNewPivotMachine) }, heightBox = !stateHeight, onExpanded = { stateHeight = !stateHeight }, tooltipState = tooltipState, scope = scope ) } } } PullRefreshIndicator( refreshing = state.isLoading, state = pullRefreshState, modifier = Modifier .align(Alignment.TopCenter) ) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachinesListScreen.kt
4199661792
package com.example.controlpivot.ui.screen.createpivot import com.example.controlpivot.data.local.model.PivotMachineEntity data class PivotMachineState( val machines: List<PivotMachineEntity> = listOf(), var currentMachine: PivotMachineEntity = PivotMachineEntity(), var isLoading: Boolean = false )
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachineState.kt
2885406243
package com.example.controlpivot.ui.screen.createpivot import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Done import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.Warning import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.PlainTooltip import androidx.compose.material3.Text import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.TooltipState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight.Companion.Bold import androidx.compose.ui.text.font.FontWeight.Companion.Thin import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.ui.theme.Green import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun PivotMachineItem( machine: PivotMachineEntity, cornerRadius: Dp = 10.dp, onDeleteClick: () -> Unit, onClick: () -> Unit, heightBox: Boolean, onExpanded: () -> Unit, tooltipState: TooltipState, scope: CoroutineScope, ) { Box( modifier = Modifier .fillMaxWidth() .clickable { onClick() } ) { Canvas(modifier = Modifier.matchParentSize()) { val item = Path().apply { lineTo(size.width, 0f) lineTo(size.width, size.height) lineTo(0f, size.height) close() } clipPath(item) { drawRoundRect( color = Green, size = size, cornerRadius = CornerRadius(cornerRadius.toPx()) ) } } Row { Image( painter = painterResource( id = R.drawable.irrigation_machine ), contentDescription = null, modifier = Modifier .size(60.dp) .padding(12.dp) ) Column( modifier = Modifier .fillMaxSize() .padding(start = 5.dp, bottom = 32.dp, end = 16.dp) ) { Text( text = machine.name, style = MaterialTheme.typography.headlineLarge, fontWeight = Bold, fontSize = 22.sp, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Ubicación: ${machine.location}", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Dotación: ${machine.endowment} L/seg ha", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) if (heightBox) { Text( text = "Caudal: ${machine.flow} L/seg", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Presión: ${machine.pressure} kPa", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Longitud Total: ${machine.length} m", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Área: ${machine.area} m^2", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Tiempo de vuelta: ${machine.speed} horas", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Potencia: ${machine.power} kW", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Eficiencia: ${machine.efficiency} %", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis, ) } } } IconButton( onClick = onDeleteClick, modifier = Modifier.align(Alignment.TopEnd) ) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete alarm", modifier = Modifier.size(25.dp) ) } IconButton( onClick = {}, modifier = Modifier .align(Alignment.BottomStart), ) { TooltipBox( positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), tooltip = { PlainTooltip { Text( text = if (machine.isSave) stringResource(id = R.string.success_registred) else stringResource(id = R.string.pending_register) ) } }, state = tooltipState ) { } Icon( imageVector = if (machine.isSave) Icons.Default.Done else Icons.Default.Warning, contentDescription = "Pending Registration", modifier = Modifier .size(18.dp) .padding(top = 5.dp) .clickable { scope.launch { tooltipState.show() } } ) } IconButton( onClick = {}, modifier = Modifier .align(Alignment.BottomEnd) ) { Icon( imageVector = if (!heightBox) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp, contentDescription = "isExpanded", modifier = Modifier .size(22.dp) .clickable { onExpanded() } ) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachineItem.kt
744916916
package com.example.controlpivot.ui.screen sealed class Screen( val route: String, ) { object PivotMachines : Screen("Información") { object List : Screen("${route}/list") object Machine : Screen("${route}/new") } object Climate : Screen("Clima") object Control : Screen("Control") object Session : Screen("Sesión") }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/Screen.kt
3912117506
package com.example.controlpivot.ui.screen import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.example.controlpivot.R @Composable fun SplashScreen() { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.anim_irrigation)) val secondComposition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.splash_animation)) val progress by animateLottieCompositionAsState( composition = composition, ) //if (progress == 1.0f) animationEnd(true) Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { LottieAnimation( composition = composition, progress = progress, modifier = Modifier .requiredHeight(350.dp) .fillMaxWidth(0.7f), ) LottieAnimation( composition = secondComposition, modifier = Modifier .requiredHeight(350.dp) .fillMaxWidth(0.7f), restartOnPlay = true, iterations = Int.MAX_VALUE ) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/SplashScreen.kt
2719246944
package com.example.controlpivot.ui.screen.climate import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.ui.model.IdPivotModel data class ClimateState ( val climates: List<Climate> = listOf(), var currentClimate: Climate? = null, var selectedIdPivot: Int = 0, var idPivotList: List<IdPivotModel> = listOf(), var isLoading: Boolean = false, )
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/climate/ClimateState.kt
500640052
package com.example.controlpivot.ui.screen.climate import android.annotation.SuppressLint import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Text import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.PullRefreshState import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.ui.component.PivotSpinner @OptIn(ExperimentalMaterialApi::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun ClimateScreen( state: ClimateState, onEvent: (ClimateEvent) -> Unit, pullRefreshState: PullRefreshState, ) { val value = state.currentClimate val items = listOf( value?.atmoPressure ?: "", value?.RH ?: "", value?.rainy ?: "", value?.solarRadiation ?: "", value?.temp ?: "", value?.temp ?: "", value?.windSpeed ?: "", value?.cropCoefficient ?: "" ) val titles = listOf( stringResource(id = R.string.pressure), stringResource(id = R.string.rh), stringResource(id = R.string.rainy), stringResource(id = R.string.solar_radiation), stringResource(id = R.string.temp_min), stringResource(id = R.string.temp_max), stringResource(id = R.string.wind), stringResource(id = R.string.etc), ) val suffix = listOf( stringResource(id = R.string.kpa), stringResource(id = R.string.percent), stringResource(id = R.string.rainy_unit), stringResource(id = R.string.solar_radiation_unit), stringResource(id = R.string.temp_unit), stringResource(id = R.string.temp_unit), stringResource(id = R.string.wind_unit), stringResource(id = R.string.rainy_unit), ) val images = listOf( R.drawable.pressure, R.drawable.humidity, R.drawable.rainy, R.drawable.radiation, R.drawable.max_temp, R.drawable.low_temp, R.drawable.wind, R.drawable.plant, ) var selectedIdPivot by remember { mutableIntStateOf(state.selectedIdPivot) } Scaffold( modifier = Modifier , ) { Box( modifier = Modifier .pullRefresh(pullRefreshState) ) { Image( painter = painterResource( id = R.drawable.background2 ), contentDescription = "Background", contentScale = ContentScale.FillBounds, modifier = Modifier.matchParentSize() ) Column( modifier = Modifier .fillMaxSize() .padding(bottom = 75.dp), horizontalAlignment = Alignment.CenterHorizontally ) { PivotSpinner( optionList = state.idPivotList, selectedOption = state.idPivotList.find { selectedIdPivot == it.idPivot }?.pivotName ?: "", onSelected = { selectedIdPivot = it state.selectedIdPivot = it }, loading = { onEvent( ClimateEvent.SelectClimateByIdPivot(selectedIdPivot) ) } ) Row( modifier = Modifier .align(Alignment.End) .padding(5.dp) ) { Text( modifier = Modifier .padding(5.dp), text = "Última actualización: ", fontSize = 13.sp, fontWeight = FontWeight.Bold ) Text( modifier = Modifier .padding(5.dp), text = state.currentClimate?.timestamp ?: "", fontSize = 12.sp, ) } LazyVerticalGrid( modifier = Modifier .padding(20.dp), columns = GridCells.Fixed(2), content = { items(items.size) { i -> ClimateItem( title = titles[i], value = items[i], suffix = suffix[i], image = images[i] ) } }, //contentPadding = PaddingValues(horizontal = 5.dp, vertical = 5.dp) ) } PullRefreshIndicator( refreshing = state.isLoading, state = pullRefreshState, modifier = Modifier .align(Alignment.TopCenter) ) } } } @Composable fun ClimateItem( title: String, value: Any?, suffix: String, image: Int, ) { ElevatedCard( modifier = Modifier .padding(horizontal = 8.dp, vertical = 8.dp) .size(height = 140.dp, width = 100.dp), ) { Box( ) { Column( modifier = Modifier .fillMaxSize() .padding(top = 8.dp), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = title, modifier = Modifier, textAlign = TextAlign.Center, fontSize = 18.sp, fontWeight = FontWeight.Bold ) Image( painter = painterResource( id = image ), contentDescription = null, modifier = Modifier .size(45.dp) .padding(4.dp) ) Row { Text( text = value.toString(), modifier = Modifier, textAlign = TextAlign.Center, fontSize = 16.sp, fontWeight = FontWeight.Thin ) Spacer(modifier = Modifier.width(7.dp)) Text( text = suffix, modifier = Modifier, textAlign = TextAlign.Center, fontSize = 16.sp, fontWeight = FontWeight.Thin ) } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/climate/ClimateScreen.kt
3091179282
package com.example.controlpivot.ui.screen.climate sealed class ClimateEvent { data class SelectClimateByIdPivot(val id: Int) : ClimateEvent() }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/climate/ClimateEvent.kt
3870925627
package com.example.controlpivot.ui.screen.login sealed class LoginEvent { class Login(val credentials: Credentials): LoginEvent() class ChangeCredentials(val credentials: Credentials): LoginEvent() }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/login/LoginEvent.kt
4135363154
package com.example.controlpivot.ui.screen.login import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material3.Icon import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.example.controlpivot.R import com.example.controlpivot.ui.component.OutlinedTextFieldWithValidation import com.example.controlpivot.ui.component.PasswordTextField import com.example.controlpivot.ui.theme.GreenHigh @Composable fun LoginScreen( state: LoginState, onEvent: (LoginEvent) -> Unit, ) { val loadingComposition by rememberLottieComposition( spec = LottieCompositionSpec.RawRes(R.raw.loading_green) ) val loadingProgress by animateLottieCompositionAsState( composition = loadingComposition, restartOnPlay = true, iterations = Int.MAX_VALUE ) Column( modifier = Modifier .wrapContentSize() .padding(20.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(20.dp)) Image( painter = painterResource( id = R.drawable.irrigation_system ), contentDescription = null, modifier = Modifier .size(120.dp) .padding(4.dp) ) Spacer(modifier = Modifier.height(10.dp)) Text( text = stringResource(id = R.string.pivot_control), style = MaterialTheme.typography.headlineLarge.copy( fontWeight = FontWeight.Black, color = GreenHigh ), ) val userHint = stringResource(id = R.string.user_hint) var user by remember { mutableStateOf("") } Spacer(modifier = Modifier.height(50.dp)) OutlinedTextFieldWithValidation( value = user, onValueChange = { user = it }, textStyle = if (user == userHint) LocalTextStyle.current.copy( color = Color.DarkGray.copy(alpha = 0.4f) ) else LocalTextStyle.current, keyboardType = KeyboardType.Text, label = "Usuario", leadingIcon = R.drawable.profile ) Spacer(modifier = Modifier.height(20.dp)) val passHint = stringResource(id = R.string.password_hint) var pass by remember { mutableStateOf("") } PasswordTextField( value = pass, onValueChange = { pass = it }, textStyle = if (user == userHint) LocalTextStyle.current.copy( color = Color.DarkGray.copy(alpha = 0.4f) ) else LocalTextStyle.current, keyboardType = KeyboardType.Password, label = "Contraseña", leadingIcon = R.drawable.lock, imeAction = ImeAction.Done, ) Spacer(modifier = Modifier.height(30.dp)) Box(modifier = Modifier .requiredHeight(60.dp) .fillMaxWidth(.8f) .clip(RoundedCornerShape(25.dp)) .background(GreenHigh) .clickable { if (state.isLoading) return@clickable onEvent( LoginEvent.Login( Credentials( user.let { it.trim() }, pass.let { it.trim() } ) ) ) } ) { Row( verticalAlignment = CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { Spacer(modifier = Modifier.width(20.dp)) Text( text = stringResource(id = R.string.login), style = MaterialTheme.typography.bodyMedium.copy( color = Color.White, ), textAlign = TextAlign.Center, fontSize = 18.sp, modifier = Modifier.weight(1f) ) Icon( imageVector = Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null, modifier = Modifier .width(40.dp) .height(35.dp) .padding( start = 3.dp, end = 8.dp ), tint = Color.White ) } } Spacer(modifier = Modifier.height(20.dp)) AnimatedVisibility( visible = state.isLoading, enter = scaleIn(), exit = scaleOut() ) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { LottieAnimation( composition = loadingComposition, progress = loadingProgress, modifier = Modifier .size(160.dp) ) } } } } @Preview(showSystemUi = true) @Composable fun LoginScreenPreview() { LoginScreen(state = LoginState(), onEvent = { LoginEvent.Login(Credentials()) }) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/login/LoginScreen.kt
3596956664
package com.example.controlpivot.ui.screen.login import com.example.controlpivot.R import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource data class Credentials( val userName: String = "", val password: String = "", ) { fun validate(): Resource<Int> { if (userName.isEmpty()) return Resource.Error(Message.StringResource(R.string.empty_userName)) if (password.isEmpty()) return Resource.Error(Message.StringResource(R.string.empty_password)) return Resource.Success(0) } private fun String.isLetterOrDigits(): Boolean = all { it.isLetterOrDigit() } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/login/Credentials.kt
3553296279
package com.example.controlpivot.ui.screen.login import com.example.controlpivot.data.common.model.Session data class LoginState( val isLoading: Boolean = false, val session: Session = Session( 0, "", "", "", "" ) )
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/login/LoginState.kt
684056715
package com.example.controlpivot.ui.screen.pivotcontrol import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.BottomSheetDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.ModalBottomSheetProperties import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.room.ColumnInfo import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.ui.component.AddTagEvent import com.example.controlpivot.ui.component.BottomSheetIrrigation import com.example.controlpivot.ui.component.PivotSpinner import com.example.controlpivot.ui.component.QuadrantIrrigation import com.example.controlpivot.ui.theme.GreenHigh import kotlinx.coroutines.delay import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun PivotControlScreen( state: ControlState, onEvent: (ControlEvent) -> Unit, ) { var selectedIdPivot by remember { mutableIntStateOf(state.selectedIdPivot) } val scrollState = rememberScrollState() var openBottomSheet by rememberSaveable { mutableStateOf(false) } var skipPartiallyExpanded by remember { mutableStateOf(true) } var edgeToEdgeEnabled by remember { mutableStateOf(false) } val bottomSheetState = rememberModalBottomSheetState( skipPartiallyExpanded = skipPartiallyExpanded ) val scope = rememberCoroutineScope() var isRunning by remember { mutableStateOf(state.controls.isRunning) } var progress by remember { mutableFloatStateOf(state.controls.progress) } var motorVelocity by remember { mutableFloatStateOf(0.3f) } var clickedSector by remember { mutableIntStateOf(0) } var stateBomb by remember { mutableStateOf(state.controls.stateBomb) } var wayToPump by remember { mutableStateOf(state.controls.wayToPump) } var turnSense by remember { mutableStateOf(state.controls.turnSense) } var sectorStateList by remember { mutableStateOf( mutableListOf( state.controls.sectorList[0].irrigateState, state.controls.sectorList[1].irrigateState, state.controls.sectorList[2].irrigateState, state.controls.sectorList[3].irrigateState ) ) } var isSelectedControl by remember { mutableStateOf(false) } LaunchedEffect(isSelectedControl) { isRunning = state.controls.isRunning progress = state.controls.progress motorVelocity = 0.3f clickedSector = 0 stateBomb = state.controls.stateBomb wayToPump = state.controls.wayToPump turnSense = state.controls.turnSense sectorStateList = mutableListOf( state.controls.sectorList[0].irrigateState, state.controls.sectorList[1].irrigateState, state.controls.sectorList[2].irrigateState, state.controls.sectorList[3].irrigateState ) isSelectedControl = false } LaunchedEffect(isRunning) { while (isRunning) { delay(100) if (!turnSense) progress += 0.3f else progress -= 0.3f } } Box( modifier = Modifier .fillMaxSize() .background(Color.LightGray.copy(alpha = 0.3f)) .padding(bottom = 50.dp) ) { if (openBottomSheet) { val windowInsets = if (edgeToEdgeEnabled) WindowInsets(0) else BottomSheetDefaults.windowInsets ModalBottomSheet( modifier = Modifier.height(500.dp), onDismissRequest = { openBottomSheet = false }, sheetState = bottomSheetState, windowInsets = windowInsets, shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp), contentColor = Color.Black, containerColor = Color.White, tonalElevation = 8.dp, ) { BottomSheetIrrigation( checkIrrigate = state.controls.sectorList[clickedSector - 1].irrigateState, sector = clickedSector, dosage = state.controls.sectorList[clickedSector - 1].dosage, onEvent = { event -> when (event) { is AddTagEvent.Close -> scope.launch { bottomSheetState.hide() }.invokeOnCompletion { if (bottomSheetState.isVisible) openBottomSheet = false } is AddTagEvent.Save -> { if (state.idPivotList.isNotEmpty()) { onEvent( ControlEvent.SaveControls( controls = PivotControlEntity( id = state.controls.id, idPivot = state.controls.idPivot, progress = progress, isRunning = isRunning, stateBomb = stateBomb, wayToPump = wayToPump, turnSense = turnSense ) ) ) onEvent( ControlEvent.SaveSectors( sectors = SectorControl( id = state.controls.sectorList[clickedSector - 1].id, sector_id = clickedSector, irrigateState = event.checkIrrigate, dosage = event.dosage, motorVelocity = 0, sector_control_id = state.controls.sectorList[clickedSector - 1].sector_control_id ) ) ) sectorStateList[clickedSector - 1] = event.checkIrrigate if (event.checkIrrigate) { onEvent(ControlEvent.ShowMessage(R.string.check_irrigate)) if (bottomSheetState.isVisible) openBottomSheet = false } else { onEvent(ControlEvent.ShowMessage(R.string.uncheck_irrigate)) if (bottomSheetState.isVisible) openBottomSheet = false } } else { onEvent(ControlEvent.ShowMessage(R.string.pivot_not_selected)) } } } }) } } } Column( modifier = Modifier .padding(bottom = 80.dp) .verticalScroll(state = scrollState), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(20.dp)) PivotSpinner( optionList = state.idPivotList, selectedOption = state.idPivotList.find { selectedIdPivot == it.idPivot }?.pivotName ?: "", onSelected = { selectedIdPivot = it state.selectedIdPivot = it }, loading = { onEvent( ControlEvent.SelectControlByIdPivot( selectedIdPivot ) ) isSelectedControl = true } ) Spacer(modifier = Modifier.height(20.dp)) Text( text = "Riego Sectorizado", fontSize = 25.sp, ) QuadrantIrrigation( isRunning = isRunning, onClick = { clickedSector = it openBottomSheet = !openBottomSheet }, pauseIrrigation = { if (state.networkStatus) { if (stateBomb) { isRunning = !isRunning onEvent( ControlEvent.SaveControls( controls = PivotControlEntity( id = state.controls.id, idPivot = state.controls.idPivot, progress = progress, isRunning = isRunning, stateBomb = stateBomb, wayToPump = wayToPump, turnSense = turnSense ) ) ) } else onEvent(ControlEvent.ShowMessage(R.string.bomb_off)) } else onEvent(ControlEvent.ShowMessage(R.string.internet_error)) }, progress = progress, sectorStateList = sectorStateList as List<Boolean> ) HorizontalDivider( modifier = Modifier .height(5.dp) .padding(horizontal = 15.dp), color = Color.Black ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { Text( text = "Sistema de Bombeo", fontSize = 25.sp, ) Spacer(modifier = Modifier.width(10.dp)) Switch( checked = stateBomb, onCheckedChange = { stateBomb = !stateBomb if (state.idPivotList.isNotEmpty()) { onEvent( ControlEvent.SaveControls( controls = PivotControlEntity( id = state.controls.id, idPivot = state.controls.idPivot, progress = progress, isRunning = isRunning, stateBomb = stateBomb, wayToPump = wayToPump, turnSense = turnSense ) ) ) } }) } Spacer(modifier = Modifier.height(10.dp)) Box( modifier = Modifier, contentAlignment = Alignment.Center ) { Column( horizontalAlignment = Alignment.Start, verticalArrangement = Arrangement.Center ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.wrapContentSize() ) { Text( text = "Manual", fontSize = 20.sp, modifier = Modifier.padding(6.dp) ) Spacer(modifier = Modifier.width(4.dp)) Switch( checked = wayToPump, onCheckedChange = { wayToPump = !wayToPump if (state.idPivotList.isNotEmpty()) { onEvent( ControlEvent.SaveControls( controls = PivotControlEntity( id = state.controls.id, idPivot = state.controls.idPivot, progress = progress, isRunning = isRunning, stateBomb = stateBomb, wayToPump = wayToPump, turnSense = turnSense ) ) ) } }, modifier = Modifier .padding(8.dp), colors = SwitchDefaults.colors( checkedThumbColor = GreenHigh, checkedIconColor = GreenHigh, checkedTrackColor = Color.White, checkedBorderColor = Color.DarkGray.copy(alpha = 0.6f), uncheckedTrackColor = Color.White, uncheckedBorderColor = Color.DarkGray.copy(alpha = 0.6f), uncheckedThumbColor = GreenHigh, uncheckedIconColor = GreenHigh, ), thumbContent = { Box( modifier = Modifier.background( color = Color.Transparent, shape = RoundedCornerShape(16.dp) ) ) } ) Spacer(modifier = Modifier.width(4.dp)) Text( text = "Automático", fontSize = 20.sp, modifier = Modifier.padding(6.dp) ) } Spacer(modifier = Modifier.height(17.dp)) Row( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.wrapContentSize() ) { Text( text = "Izquierda", fontSize = 20.sp, modifier = Modifier.padding(6.dp) ) Switch( checked = turnSense, onCheckedChange = { turnSense = !turnSense if (state.idPivotList.isNotEmpty()) { onEvent( ControlEvent.SaveControls( controls = PivotControlEntity( id = state.controls.id, idPivot = state.controls.idPivot, progress = progress, isRunning = isRunning, stateBomb = stateBomb, wayToPump = wayToPump, turnSense = turnSense ) ) ) } }, modifier = Modifier .padding(8.dp), colors = SwitchDefaults.colors( checkedThumbColor = GreenHigh, checkedIconColor = GreenHigh, checkedTrackColor = Color.White, checkedBorderColor = Color.DarkGray.copy(alpha = 0.6f), uncheckedTrackColor = Color.White, uncheckedBorderColor = Color.DarkGray.copy(alpha = 0.6f), uncheckedThumbColor = GreenHigh, uncheckedIconColor = GreenHigh, ), thumbContent = { Box( modifier = Modifier.background( color = Color.Transparent, shape = RoundedCornerShape(16.dp) ) ) } ) Text( text = "Derecha", fontSize = 20.sp, modifier = Modifier.padding(6.dp) ) } } } Spacer(modifier = Modifier.height(90.dp)) } } @Preview(showSystemUi = true, showBackground = true) @Composable fun PivotControlPreview() { PivotControlScreen(state = ControlState(), onEvent = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/pivotcontrol/PivotControlScreen.kt
3361587621
package com.example.controlpivot.ui.screen.pivotcontrol import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl sealed class ControlEvent { data class SaveControls(val controls: PivotControlEntity) : ControlEvent() data class SaveSectors(val sectors: SectorControl) : ControlEvent() data class SelectControlByIdPivot(val id: Int) : ControlEvent() data class ShowMessage(val string: Int) : ControlEvent() }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/pivotcontrol/ControlEvent.kt
911498910
package com.example.controlpivot.ui.screen.pivotcontrol import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.ui.model.IdPivotModel import com.example.controlpivot.ui.model.PivotControlsWithSectors data class ControlState( val controls: PivotControlsWithSectors = PivotControlsWithSectors( id = 0, idPivot = 0, progress = 0f, isRunning = false, sectorList = listOf( SectorControl( id = 1, sector_id = 0, irrigateState = false, dosage = 0, motorVelocity = 0, sector_control_id = 0 ), SectorControl( id = 2, sector_id = 0, irrigateState = false, dosage = 0, motorVelocity = 0, sector_control_id = 0 ), SectorControl( id = 3, sector_id = 0, irrigateState = false, dosage = 0, motorVelocity = 0, sector_control_id = 0 ), SectorControl( id = 4, sector_id = 0, irrigateState = false, dosage = 0, motorVelocity = 0, sector_control_id = 0 ), ), stateBomb = false, wayToPump = false, turnSense = false ), var selectedIdPivot: Int = 0, var idPivotList: List<IdPivotModel> = listOf(), var networkStatus : Boolean = false )
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/pivotcontrol/ControlState.kt
2751532434
@file:OptIn(ExperimentalMaterial3Api::class) package com.example.controlpivot.ui.screen.session import android.annotation.SuppressLint import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ExitToApp import androidx.compose.material3.AlertDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.Center import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.ui.component.OutlinedTextFieldWithValidation import com.example.controlpivot.ui.component.PasswordTextField import com.example.controlpivot.ui.screen.login.LoginEvent import com.example.controlpivot.ui.screen.login.LoginState import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenLow import com.example.controlpivot.ui.theme.GreenMedium @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun SessionScreen( onClearSession: () -> Unit, state: LoginState?, onEvent: (LoginEvent) -> Unit, ) { var openDialog by remember { mutableStateOf(false) } Scaffold( modifier = Modifier .fillMaxSize() .padding(bottom = 75.dp), ) { Box(modifier = Modifier.fillMaxSize()) { Box( modifier = Modifier .fillMaxWidth() .height(70.dp) .drawBehind { translate(top = -650f) { drawCircle( brush = Brush.verticalGradient( colors = listOf( GreenLow, GreenMedium, GreenHigh ) ), radius = 300.dp.toPx(), ) } } ) {} Column( modifier = Modifier .wrapContentSize() .padding(top = 95.dp, start = 20.dp, end = 20.dp, bottom = 20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Box( modifier = Modifier .size(120.dp) .background(color = Color.Transparent, shape = CircleShape) .padding(bottom = 12.dp), ) { Image( painter = painterResource(id = R.drawable.person1), contentDescription = null, modifier = Modifier .size(120.dp) .align(Center) ) } Text( text = state?.session?.name ?: "", fontSize = 25.sp, fontFamily = FontFamily.Serif ) Spacer(modifier = Modifier.height(10.dp)) OutlinedTextFieldWithValidation( label = stringResource(id = R.string.user_hint), value = state?.session?.userName ?: "", textStyle = LocalTextStyle.current, keyboardType = KeyboardType.Text, leadingIcon = R.drawable.profile, onValueChange = {}, readOnly = true ) Spacer(modifier = Modifier.height(10.dp)) PasswordTextField( label = stringResource(id = R.string.password_hint), value = state?.session?.password ?: "", textStyle = LocalTextStyle.current, keyboardType = KeyboardType.Password, leadingIcon = R.drawable.lock, onValueChange = {}, readOnly = true, ) Spacer(modifier = Modifier.height(10.dp)) OutlinedTextFieldWithValidation( label = stringResource(id = R.string.role), value = state?.session?.role ?: "", textStyle = LocalTextStyle.current, keyboardType = KeyboardType.Text, leadingIcon = R.drawable.category, onValueChange = {}, readOnly = true ) Spacer(modifier = Modifier.height(20.dp)) Box(modifier = Modifier .requiredHeight(60.dp) .fillMaxWidth(0.8f) .clip(RoundedCornerShape(25.dp)) .background(GreenMedium) .clickable { openDialog = true } ) { Row( verticalAlignment = CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { Spacer(modifier = Modifier.width(20.dp)) Icon( imageVector = Icons.AutoMirrored.Filled.ExitToApp, contentDescription = "Close Session", modifier = Modifier .width(40.dp) .height(35.dp) .padding( start = 3.dp, end = 8.dp ), tint = Color.Black ) Text( text = stringResource(id = R.string.close_session), style = MaterialTheme.typography.bodyMedium.copy( color = Color.Black, ), textAlign = TextAlign.Center, fontSize = 18.sp, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(30.dp)) } } } } } if (openDialog) { AlertDialog( onDismissRequest = { openDialog = false }, confirmButton = { TextButton(onClick = { openDialog = false onClearSession() }) { Text( text = "SI", style = TextStyle( fontSize = 15.sp ) ) } }, dismissButton = { TextButton(onClick = { openDialog = false }) { Text( text = "NO", style = TextStyle( fontSize = 15.sp ) ) } }, title = { Row( verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.AutoMirrored.Filled.ExitToApp, contentDescription = null, tint = Color.Black ) Spacer(modifier = Modifier.width(10.dp)) Text( text = "Cerrar Sesión", textAlign = TextAlign.Center ) } }, text = { Text( text = "¿Estás seguro que deseas cerrar sesión?", ) } ) } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/session/SessionScreen.kt
2118900157
package com.example.controlpivot.ui.model data class MachineModel( val id: Int, val name: String, val endowment: Long, val flow: Long, val pressure: Long, val length: Long, val area: Long, val power: Long, val speed: Long, val efficiency: Long, )
pivot-control/app/src/main/java/com/example/controlpivot/ui/model/MachineModel.kt
1744884973
package com.example.controlpivot.ui.model import com.example.controlpivot.data.local.model.SectorControl data class PivotControlsWithSectors( val id: Int, val idPivot: Int, val progress: Float, val isRunning: Boolean, val stateBomb: Boolean, val wayToPump: Boolean, val turnSense: Boolean, val sectorList : List<SectorControl> )
pivot-control/app/src/main/java/com/example/controlpivot/ui/model/PivotControlsWithSectors.kt
4090297101
package com.example.controlpivot.ui.model data class IdPivotModel( val idPivot: Int, val pivotName: String, )
pivot-control/app/src/main/java/com/example/controlpivot/ui/model/IdPivotModel.kt
1459561744
package com.example.controlpivot import android.annotation.SuppressLint import android.app.Activity import android.widget.Toast import com.example.controlpivot.utils.DateTimeObj import com.example.controlpivot.utils.Message import java.text.SimpleDateFormat fun Activity.toast(message: Message) { when (message) { is Message.DynamicString -> Toast.makeText(this, message.value, Toast.LENGTH_LONG).show() is Message.StringResource -> Toast.makeText(this, message.resId, Toast.LENGTH_LONG).show() } } fun String.convertCharacter(): String { return this.replace(Regex("^\\\\.|,|-|\\\\s"),"").trim() } @SuppressLint("SimpleDateFormat") fun DateTimeObj.toLong() = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("${this.date} ${this.time}")?.time ?: System.currentTimeMillis()
pivot-control/app/src/main/java/com/example/controlpivot/Extensions.kt
1648705354
package com.example.controlpivot import android.app.Application import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@MyApplication) modules(appModule) } } }
pivot-control/app/src/main/java/com/example/controlpivot/MyApplication.kt
2001717709
package com.example.controlpivot import android.annotation.SuppressLint import android.app.ActivityManager import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.activity.compose.setContent import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.lifecycle.Lifecycle import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigation import androidx.navigation.compose.rememberNavController import com.example.controlpivot.ui.activity.LoginActivity import com.example.controlpivot.ui.navigation.BottomNavBarAnimation import com.example.controlpivot.ui.screen.Screen import com.example.controlpivot.ui.screen.climate.ClimateScreen import com.example.controlpivot.ui.screen.createpivot.AddEditPivotMachineScreen import com.example.controlpivot.ui.screen.createpivot.BottomNavScreen import com.example.controlpivot.ui.screen.createpivot.PivotMachineListScreen import com.example.controlpivot.ui.screen.createpivot.ScreensNavEvent import com.example.controlpivot.ui.screen.createpivot.pivotMachineNavEvent import com.example.controlpivot.ui.screen.pivotcontrol.PivotControlScreen import com.example.controlpivot.ui.screen.session.SessionScreen import com.example.controlpivot.ui.theme.ControlPivotTheme import com.example.controlpivot.ui.viewmodel.ClimateViewModel import com.example.controlpivot.ui.viewmodel.LoginViewModel import com.example.controlpivot.ui.viewmodel.PivotControlViewModel import com.example.controlpivot.ui.viewmodel.PivotMachineViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.repeatOnLifecycle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalMaterialApi::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ControlPivotTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val navController = rememberNavController() Scaffold( bottomBar = { BottomNavBarAnimation(navController = navController) } ) { NavHost( navController, startDestination = BottomNavScreen.PivotMachines.route ) { navigation( route = BottomNavScreen.PivotMachines.route, startDestination = Screen.PivotMachines.List.route ) { val pivotMachineViewModel by viewModel<PivotMachineViewModel>() composable(Screen.PivotMachines.List.route) { val state by pivotMachineViewModel.state.collectAsState() val pullRefreshState = rememberPullRefreshState( refreshing = state.isLoading, onRefresh = pivotMachineViewModel::refreshData ) PivotMachineListScreen( state = state, onEvent = pivotMachineViewModel::onEvent, navEvent = { pivotMachineNavEvent( navController = navController, navEvent = it ) }, pullRefreshState = pullRefreshState ) LaunchedEffect(Unit) { pivotMachineViewModel.event.flowWithLifecycle( lifecycle, Lifecycle.State.STARTED ).collectLatest { event -> when (event) { is PivotMachineViewModel.Event.PivotMachineCreated -> pivotMachineNavEvent( navController, ScreensNavEvent.ToPivotMachineList ) is PivotMachineViewModel.Event.ShowMessage -> toast( event.message ) } } } } composable(Screen.PivotMachines.Machine.route) { val state by pivotMachineViewModel.state.collectAsState() AddEditPivotMachineScreen( state = state, onEvent = pivotMachineViewModel::onEvent, navEvent = { navEvent -> pivotMachineNavEvent( navController = navController, navEvent = navEvent ) } ) BackHandler { pivotMachineNavEvent( navController = navController, navEvent = ScreensNavEvent.Back ) } CoroutineScope(Dispatchers.Main).launch { pivotMachineViewModel.event.flowWithLifecycle( lifecycle, Lifecycle.State.STARTED ).collectLatest { event -> Log.d("Activity", event.toString()) when (event) { is PivotMachineViewModel.Event.PivotMachineCreated -> pivotMachineNavEvent( navController, ScreensNavEvent.ToPivotMachineList ) is PivotMachineViewModel.Event.ShowMessage -> toast( event.message ) } } } } } composable(BottomNavScreen.Climate.route) { val climateViewModel by viewModel<ClimateViewModel>() val state by climateViewModel.state.collectAsState() val pullRefreshState = rememberPullRefreshState( refreshing = state.isLoading, onRefresh = climateViewModel::refreshData ) ClimateScreen( state = state, onEvent = climateViewModel::onEvent, pullRefreshState = pullRefreshState ) LaunchedEffect(Unit) { climateViewModel.message.flowWithLifecycle( lifecycle, Lifecycle.State.STARTED ).collectLatest { message -> toast(message) } } } composable(BottomNavScreen.Control.route) { val controlViewModel by viewModel<PivotControlViewModel>() val state by controlViewModel.state.collectAsState() PivotControlScreen( state = state, onEvent = controlViewModel::onEvent ) LaunchedEffect(Unit) { controlViewModel.message.flowWithLifecycle( lifecycle, Lifecycle.State.STARTED ).collectLatest { message -> toast(message) } } } composable(BottomNavScreen.Settings.route) { val loginViewModel by viewModel<LoginViewModel>() val state by loginViewModel.state.collectAsState() SessionScreen( state = state, onEvent = loginViewModel::onEvent, onClearSession = { try { (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager) .clearApplicationUserData() startActivity( Intent( this@MainActivity, LoginActivity::class.java ) ) } catch (e: Exception) { startActivity( Intent( this@MainActivity, LoginActivity::class.java ) ) finish() } } ) LaunchedEffect(Unit) { loginViewModel.message.flowWithLifecycle( lifecycle, Lifecycle.State.STARTED ).collectLatest { message -> toast(message) } } } } } } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/MainActivity.kt
4167250563
package com.example.controlpivot import com.example.controlpivot.data.* import com.example.controlpivot.data.dependency.* import com.example.controlpivot.domain.usecase.* import com.example.controlpivot.ui.viewmodel.* import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val splashModule = module { includes(sessionDataModule) viewModel { SplashViewModel(get()) } } val loginModule = module { includes(sessionDataModule) viewModel { LoginViewModel(get(), get()) } } val pivotModule = module { includes( sessionDataModule, pivotControlDataModule, climateDataModule, pivotMachineDataModule, pendingDeleteModule ) single { DeletePendingMachineUseCase(get(), get()) } single { GetIdPivotNameUseCase(get()) } single { GetPivotControlsWithSectorsUseCase(get()) } viewModel { PivotMachineViewModel(get(), get(), get(), get(), get(), get()) } viewModel { ClimateViewModel(get(), get(), get()) } viewModel { PivotControlViewModel(get(), get(), get(), get()) } } val appModule = module { includes(splashModule, loginModule, pivotModule) }
pivot-control/app/src/main/java/com/example/controlpivot/AppModule.kt
2618676423
package com.example.controlpivot object AppConstants { const val APP_DATABASE_NAME = "app_database" const val APP_PREFERENCES = "app_preferences" const val SESSION_PREFERENCES = "session_preferences" const val CLIMATE_API_PATH = "climate" const val DELETE_API_PATH = "/{id}" const val EMPTY_JSON_STRING = "" const val PENDING_DELETE_PREFERENCES = "pending_delete_preferences" const val PIVOT_CONTROL_API_BASE_URL = "http://192.168.1.101:8080/demo-0.0.1/api/pivot-control/" const val PIVOT_CONTROL_API_PATH = "control" const val PIVOT_SECTOR_CONTROL_API_PATH = "sector" const val PIVOT_MACHINES_API_PATH = "machines" const val SESSION_API_PATH = "login" const val AUTHORIZATION = "DWAi9c!j#8*iRD*Q64kqH150" }
pivot-control/app/src/main/java/com/example/controlpivot/AppConstants.kt
146598919
package com.example.controlpivot.utils import android.content.Context import android.content.pm.PackageManager import androidx.core.app.ActivityCompat class CheckPermissions { companion object{ fun check(context: Context?, permissions: Array<String>): Boolean { if (context != null) { for (permission in permissions) { if (ActivityCompat.checkSelfPermission( context, permission ) != PackageManager.PERMISSION_GRANTED){ return false } } } return true } } }
pivot-control/app/src/main/java/com/example/controlpivot/utils/CheckPermissions.kt
2780632623
package com.example.controlpivot.utils import android.content.Context import android.net.Uri import androidx.core.content.FileProvider import java.io.File class GetUriFromFile { companion object{ operator fun invoke(context: Context, file: File): Uri { return FileProvider.getUriForFile(context, "com.savent.erp.fileprovider", file) } } }
pivot-control/app/src/main/java/com/example/controlpivot/utils/GetUriFromFile.kt
684234882
package com.example.controlpivot.utils import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken class Converters { @TypeConverter fun toDatetime(datetime: String): DateTimeObj = Gson().fromJson(datetime, object : TypeToken<DateTimeObj>() {}.type) @TypeConverter fun fromDatetime(datetime: DateTimeObj): String = Gson().toJson(datetime) }
pivot-control/app/src/main/java/com/example/controlpivot/utils/Converters.kt
1451657833
package com.example.controlpivot.utils import java.time.Instant import java.time.format.DateTimeFormatter import java.util.Locale class DateFormat { companion object { fun format(timestamp: Long, format: String): String { val dateFormat = DateTimeFormatter.ofPattern(format, Locale.ENGLISH) return dateFormat.format(Instant.ofEpochMilli(timestamp)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/utils/DateFormat.kt
1217318897
package com.example.controlpivot.utils data class DateTimeObj(val date: String, val time: String) { companion object { fun fromLong(long: Long) = DateTimeObj( DateFormat.format(long, "yyyy-MM-dd"), DateFormat.format(long, "HH:mm:ss.SSS") ) } }
pivot-control/app/src/main/java/com/example/controlpivot/utils/DateTimeObj.kt
4251119670
package com.example.controlpivot.utils import androidx.annotation.StringRes sealed class Message { data class DynamicString(val value: String): Message() class StringResource(@StringRes val resId: Int, vararg val args: Any): Message() }
pivot-control/app/src/main/java/com/example/controlpivot/utils/Message.kt
651892683
package com.example.controlpivot.utils sealed class Resource<T> { class Success<T>(val data: T): Resource<T>() class Error<T>(val message: Message): Resource<T>() }
pivot-control/app/src/main/java/com/example/controlpivot/utils/Resource.kt
721726500
package com.example.controlpivot import android.annotation.SuppressLint import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Build import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.launch class NetworkConnectivityObserver(context: Context) : ConnectivityObserver { private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager private var networkRequest: NetworkRequest? = null init { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) networkRequest = NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build() } @SuppressLint("NewApi") override fun observe(): Flow<ConnectivityObserver.Status> { return callbackFlow { if(isCurrentOnline()) launch { send(ConnectivityObserver.Status.Available) } else launch { send(ConnectivityObserver.Status.Unavailable) } val callback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) launch { send(ConnectivityObserver.Status.Available) } } override fun onUnavailable() { super.onUnavailable() launch { send(ConnectivityObserver.Status.Unavailable) } } override fun onLosing(network: Network, maxMsToLive: Int) { super.onLosing(network, maxMsToLive) launch { send(ConnectivityObserver.Status.Losing) } } override fun onLost(network: Network) { super.onLost(network) launch { send(ConnectivityObserver.Status.Lost) } } } networkRequest?.let { connectivityManager.registerNetworkCallback(it, callback) } ?: connectivityManager.registerDefaultNetworkCallback(callback) awaitClose { connectivityManager.unregisterNetworkCallback(callback) } } } private fun isCurrentOnline(): Boolean{ val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?: return false if(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) return true return false } }
pivot-control/app/src/main/java/com/example/controlpivot/NetworkConnectivityObserver.kt
2813979942
package com.example.controlpivot import kotlinx.coroutines.flow.Flow interface ConnectivityObserver { fun observe(): Flow<Status> enum class Status { Available, Unavailable, Losing, Lost } }
pivot-control/app/src/main/java/com/example/controlpivot/ConnectivityObserver.kt
982095909
package com.example.controlpivot.data.repository import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow interface PivotMachineRepository { suspend fun upsertPivotMachines(machines: List<PivotMachineEntity>): Resource<Int> suspend fun upsertPivotMachine(machine: PivotMachineEntity): Resource<Int> suspend fun savePivotMachine(localId: Int): Resource<Int> suspend fun registerPendingMachines() suspend fun getPivotMachine(id: Int): Resource<PivotMachineEntity> fun getPivotMachineAsync(id: Int): Flow<Resource<PivotMachineEntity>> suspend fun getPivotMachineByRemoteId(remoteId: Int): Resource<PivotMachineEntity> fun getAllPivotMachines(query: String): Flow<Resource<List<PivotMachineEntity>>> suspend fun arePendingPivotMachines(): Boolean suspend fun fetchPivotMachine(): Resource<Int> suspend fun updatePivotMachine(pivotMachine: PivotMachineEntity): Resource<Int> suspend fun deletePivotMachine(id: Int): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/PivotMachineRepository.kt
473047135
package com.example.controlpivot.data.repository import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow interface ClimateRepository { suspend fun upsertClimates(climates: List<Climate>): Resource<Int> suspend fun addClimate(climate: Climate): Resource<Int> suspend fun getClimate(id: Int): Resource<Climate> suspend fun getClimatesById(id: Int): Resource<List<Climate>> fun getAllClimates(query: String): Flow<Resource<List<Climate>>> suspend fun fetchClimate(): Resource<Int> suspend fun updateClimate(climate: Climate): Resource<Int> suspend fun deleteClimate(id: Int): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/ClimateRepository.kt
3616063408
package com.example.controlpivot.data.repository import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.utils.Resource interface MachinePendingDeleteRepository { suspend fun getPendingDelete(): Resource<MachinePendingDelete> suspend fun savePendingDelete(pendingDelete: MachinePendingDelete): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/MachinePendingDeleteRepository.kt
1152527701
package com.example.controlpivot.data.repository import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.local.datasource.PivotControlLocalDatasource import com.example.controlpivot.data.remote.datasource.PivotControlRemoteDatasource import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow class PivotControlRepositoryImpl( private val localDatasource: PivotControlLocalDatasource, private val remoteDatasource: PivotControlRemoteDatasource, ) : PivotControlRepository { override suspend fun upsertPivotControls(pivots: List<PivotControlEntity>): Resource<Int> = localDatasource.upsertPivotControls(pivots) override suspend fun addPivotControl(pivot: PivotControlEntity): Resource<Int> { localDatasource.addPivotControl(pivot) val response = remoteDatasource.updatePivotControl(pivot) if (response is Resource.Error) return response return Resource.Success(0) } override suspend fun upsertSectorControl(sectorControl: SectorControl): Resource<Int> { localDatasource.upsertSectorControl(sectorControl) val response = remoteDatasource.updateSectorControl(sectorControl) if (response is Resource.Error) return response return Resource.Success(0) } override suspend fun getPivotControl(id: Int): Resource<PivotControlEntity> = localDatasource.getPivotControl(id) override fun getAllPivotControls(query: String): Flow<Resource<List<PivotControlEntity>>> = localDatasource.getPivotControls(query) override fun getAllSectorControls(query: String): Flow<Resource<List<SectorControl>>> = localDatasource.getSectorControls(query) override fun getSectorsForPivot(query: Int): Flow<Resource<List<SectorControl>>> = localDatasource.getSectorsForPivot(query) override suspend fun fetchPivotControl(): Resource<Int> { return when (val response = remoteDatasource.getPivotControls()) { is Resource.Error -> Resource.Error(response.message) is Resource.Success -> { response.data.forEach { control -> if (control.isRunning) { val result = localDatasource.getPivotControl(control.id) if (result is Resource.Success) { val action = remoteDatasource.updatePivotControl(result.data) if (action is Resource.Error) Resource.Error<Int>(action.message) } } else { localDatasource.addPivotControl( PivotControlEntity( id = control.id, idPivot = control.idPivot, progress = control.progress, isRunning = control.isRunning, stateBomb = control.stateBomb, wayToPump = control.wayToPump, turnSense = control.turnSense, ) ) } when (val result = remoteDatasource.getSectorControls()) { is Resource.Error -> Resource.Error<List<SectorControl>>(result.message) is Resource.Success -> { result.data.forEach { localDatasource.upsertSectorControl( SectorControl( id = it.id, sector_id = it.sector_id, irrigateState = it.irrigateState, dosage = it.dosage, motorVelocity = it.motorVelocity, sector_control_id = control.id ) ) } } } } Resource.Success(0) } } } override suspend fun updatePivotControl(pivot: PivotControlEntity): Resource<Int> = remoteDatasource.updatePivotControl(pivot) override suspend fun updateSectorControl(sectorControl: SectorControl): Resource<Int> = remoteDatasource.updateSectorControl(sectorControl) override suspend fun deletePivotControl(id: Int): Resource<Int> = remoteDatasource.deletePivotControl(id) }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/PivotControlRepositoryImpl.kt
4173044456
package com.example.controlpivot.data.repository import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.data.local.datasource.ClimateLocalDatasource import com.example.controlpivot.data.remote.datasource.ClimateRemoteDatasource import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow class ClimateRepositoryImpl( private val localDatasource: ClimateLocalDatasource, private val remoteDatasource: ClimateRemoteDatasource, ) : ClimateRepository { override suspend fun upsertClimates(climates: List<Climate>): Resource<Int> = localDatasource.upsertClimates(climates) override suspend fun addClimate(climate: Climate): Resource<Int> { val response = remoteDatasource.insertClimate(climate) if (response is Resource.Error) return response return localDatasource.addClimate(climate) } override suspend fun getClimate(id: Int): Resource<Climate> = localDatasource.getClimate(id) override suspend fun getClimatesById(id: Int): Resource<List<Climate>> = localDatasource.getClimatesByIdPivot(id) override fun getAllClimates(query: String): Flow<Resource<List<Climate>>> = localDatasource.getClimates(query) override suspend fun fetchClimate(): Resource<Int> { return when (val response = remoteDatasource.getClimates()) { is Resource.Error -> Resource.Error(response.message) is Resource.Success -> localDatasource.upsertClimates(response.data) } } override suspend fun updateClimate(climate: Climate): Resource<Int> = remoteDatasource.updateClimate(climate) override suspend fun deleteClimate(id: Int): Resource<Int> = remoteDatasource.deleteClimate(id) }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/ClimateRepositoryImpl.kt
144400226
package com.example.controlpivot.data.repository import com.example.controlpivot.data.local.datasource.PivotMachineLocalDatasource import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.data.local.model.toLocal import com.example.controlpivot.data.remote.datasource.PivotMachineRemoteDatasource import com.example.controlpivot.data.remote.model.toNetwork import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.runBlocking class PivotMachineRepositoryImpl( private val localDatasource: PivotMachineLocalDatasource, private val remoteDatasource: PivotMachineRemoteDatasource, ) : PivotMachineRepository { override suspend fun upsertPivotMachines(machines: List<PivotMachineEntity>): Resource<Int> = localDatasource.upsertPivotMachines(machines) override suspend fun upsertPivotMachine(machine: PivotMachineEntity): Resource<Int> = localDatasource.addPivotMachine(machine) override suspend fun savePivotMachine(localId: Int): Resource<Int> { var machineEntity: PivotMachineEntity? = null when (val result = localDatasource.getPivotMachine(localId)) { is Resource.Error -> return Resource.Error(result.message) is Resource.Success -> { machineEntity = result.data } } var machineId = 0 var isSave = true when (val result = remoteDatasource.insertPivotMachine(machineEntity.toNetwork())) { is Resource.Error -> isSave = false is Resource.Success -> machineId = result.data.id } return localDatasource.updatePivotMachine( machineEntity.copy( remoteId = machineId, isSave = isSave ) ) } override suspend fun registerPendingMachines() = synchronized(this) { runBlocking(Dispatchers.IO) { when (val result = localDatasource.getPivotMachines()) { is Resource.Error -> {} is Resource.Success -> { result.data.filter { !it.isSave }.forEach { when(val response = remoteDatasource.insertPivotMachine(it.toNetwork())) { is Resource.Error -> {} is Resource.Success -> localDatasource.updatePivotMachine( it.copy(isSave = true)) } } } } } } override suspend fun getPivotMachine(id: Int): Resource<PivotMachineEntity> = localDatasource.getPivotMachine(id) override fun getPivotMachineAsync(id: Int): Flow<Resource<PivotMachineEntity>> = localDatasource.getPivotMachineAsync(id) override suspend fun getPivotMachineByRemoteId(remoteId: Int): Resource<PivotMachineEntity> = localDatasource.getPivotMachineByRemoteId(remoteId) override fun getAllPivotMachines(query: String): Flow<Resource<List<PivotMachineEntity>>> = localDatasource.getPivotMachines(query) override suspend fun arePendingPivotMachines(): Boolean { when (val result = localDatasource.getPivotMachines()) { is Resource.Error -> return false is Resource.Success -> { var pendingMachine = result.data.filter { !it.isSave } if (pendingMachine.isEmpty()) return true return false } } } override suspend fun fetchPivotMachine(): Resource<Int> { return when (val response = remoteDatasource.getPivotMachines()) { is Resource.Error -> Resource.Error(response.message) is Resource.Success -> { localDatasource.upsertPivotMachines(response.data.map { it.toLocal() }) } } } override suspend fun updatePivotMachine(pivotMachine: PivotMachineEntity): Resource<Int> = localDatasource.updatePivotMachine(pivotMachine) override suspend fun deletePivotMachine(id: Int): Resource<Int> { return when (val result = localDatasource.getPivotMachine(id)) { is Resource.Error -> Resource.Error(result.message) is Resource.Success -> { localDatasource.deletePivotMachine(result.data) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/PivotMachineRepositoryImpl.kt
1258603675
package com.example.controlpivot.data.repository import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.ui.screen.login.Credentials import com.example.controlpivot.utils.Resource interface SessionRepository { suspend fun getSession(): Resource<Session> suspend fun fetchSession(credentials: Credentials): Resource<Int> suspend fun updateSession(credentials: Credentials): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/SessionRepository.kt
1883559161
package com.example.controlpivot.data.repository import com.example.controlpivot.data.local.datasource.MachinePendingDeleteDatasource import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.utils.Resource class MachinePendingDeleteRepositoryImpl( private val machinePendingDeleteDatasource: MachinePendingDeleteDatasource ): MachinePendingDeleteRepository { override suspend fun getPendingDelete(): Resource<MachinePendingDelete> = machinePendingDeleteDatasource.getPendingDelete() override suspend fun savePendingDelete(pendingDelete: MachinePendingDelete): Resource<Int> = machinePendingDeleteDatasource.savePendingDelete(pendingDelete) }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/MachinePendingDeleteRepositoryImpl.kt
2013452323
package com.example.controlpivot.data.repository import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.local.datasource.SessionLocalDatasource import com.example.controlpivot.data.remote.datasource.SessionRemoteDatasource import com.example.controlpivot.ui.screen.login.Credentials import com.example.controlpivot.utils.Resource class SessionRepositoryImpl( private val remoteDatasource: SessionRemoteDatasource, private val localDatasource: SessionLocalDatasource, ) : SessionRepository { override suspend fun getSession(): Resource<Session> = localDatasource.getSession() override suspend fun fetchSession(credentials: Credentials): Resource<Int> { return when (val response = remoteDatasource.getSession(credentials)) { is Resource.Success -> localDatasource.saveSession( Session( id = response.data.id, name = response.data.name, userName = credentials.userName, password = credentials.password, role = response.data.role ) ) is Resource.Error -> Resource.Error(response.message) } } override suspend fun updateSession(credentials: Credentials): Resource<Int> { return when (val response = remoteDatasource.updateSession(credentials)) { is Resource.Success -> Resource.Success(response.data.id) is Resource.Error -> Resource.Error(response.message) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/SessionRepositoryImpl.kt
107777339
package com.example.controlpivot.data.repository import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow interface PivotControlRepository { suspend fun upsertPivotControls(pivots: List<PivotControlEntity>): Resource<Int> suspend fun addPivotControl(pivot: PivotControlEntity): Resource<Int> suspend fun upsertSectorControl(sectorControl: SectorControl): Resource<Int> suspend fun getPivotControl(id: Int): Resource<PivotControlEntity> fun getAllPivotControls(query: String): Flow<Resource<List<PivotControlEntity>>> fun getAllSectorControls(query: String): Flow<Resource<List<SectorControl>>> fun getSectorsForPivot(query: Int) : Flow<Resource<List<SectorControl>>> suspend fun fetchPivotControl(): Resource<Int> suspend fun updatePivotControl(pivot: PivotControlEntity): Resource<Int> suspend fun updateSectorControl(sectorControl: SectorControl): Resource<Int> suspend fun deletePivotControl(id: Int): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/repository/PivotControlRepository.kt
4082751368
package com.example.controlpivot.data.dependency import com.example.controlpivot.data.local.database.AppDatabase import com.example.controlpivot.data.local.datasource.ClimateLocalDatasource import com.example.controlpivot.data.local.datasource.ClimateLocalDatasourceImpl import com.example.controlpivot.data.remote.datasource.ClimateRemoteDatasource import com.example.controlpivot.data.remote.datasource.ClimateRemoteDatasourceImpl import com.example.controlpivot.data.remote.service.ClimateApiService import com.example.controlpivot.data.repository.ClimateRepository import com.example.controlpivot.data.repository.ClimateRepositoryImpl import org.koin.dsl.module import retrofit2.Retrofit val climateDataModule = module { includes(baseModule) single { get<AppDatabase>().climateDao() } single<ClimateLocalDatasource> { ClimateLocalDatasourceImpl(get()) } single<ClimateApiService> { get<Retrofit>().create(ClimateApiService::class.java) } single<ClimateRemoteDatasource> { ClimateRemoteDatasourceImpl(get()) } single<ClimateRepository> { ClimateRepositoryImpl(get(), get()) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/dependency/ClimateDataModule.kt
1458218722
package com.example.controlpivot.data.dependency import com.example.controlpivot.data.local.database.AppDatabase import com.example.controlpivot.data.local.datasource.PivotMachineLocalDatasource import com.example.controlpivot.data.local.datasource.PivotMachineLocalDatasourceImpl import com.example.controlpivot.data.remote.datasource.PivotMachineRemoteDatasource import com.example.controlpivot.data.remote.datasource.PivotMachineRemoteDatasourceImpl import com.example.controlpivot.data.remote.service.PivotMachineApiService import com.example.controlpivot.data.repository.PivotMachineRepository import com.example.controlpivot.data.repository.PivotMachineRepositoryImpl import org.koin.dsl.module import retrofit2.Retrofit val pivotMachineDataModule = module { includes(baseModule) single { get<AppDatabase>().pivotMachineDao() } single<PivotMachineLocalDatasource> { PivotMachineLocalDatasourceImpl(get()) } single<PivotMachineApiService> { get<Retrofit>().create(PivotMachineApiService::class.java) } single<PivotMachineRemoteDatasource> { PivotMachineRemoteDatasourceImpl(get()) } single<PivotMachineRepository> { PivotMachineRepositoryImpl(get(), get()) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/dependency/PivotMachineDataModule.kt
2646137032
package com.example.controlpivot.data.dependency import com.example.controlpivot.data.local.database.AppDatabase import com.example.controlpivot.data.local.datasource.PivotControlLocalDatasource import com.example.controlpivot.data.local.datasource.PivotControlLocalDatasourceImpl import com.example.controlpivot.data.remote.datasource.PivotControlRemoteDatasource import com.example.controlpivot.data.remote.datasource.PivotControlRemoteDatasourceImpl import com.example.controlpivot.data.remote.service.PivotControlApiService import com.example.controlpivot.data.remote.service.SectorControlApiService import com.example.controlpivot.data.repository.PivotControlRepository import com.example.controlpivot.data.repository.PivotControlRepositoryImpl import org.koin.dsl.module import retrofit2.Retrofit val pivotControlDataModule = module { includes(baseModule) single { get<AppDatabase>().pivotControlDao() } single { get<AppDatabase>().sectorControlDao() } single<PivotControlLocalDatasource> { PivotControlLocalDatasourceImpl(get(), get()) } single<PivotControlApiService> { get<Retrofit>().create(PivotControlApiService::class.java) } single<SectorControlApiService> { get<Retrofit>().create(SectorControlApiService::class.java) } single<PivotControlRemoteDatasource> { PivotControlRemoteDatasourceImpl(get(), get()) } single<PivotControlRepository> { PivotControlRepositoryImpl(get(), get()) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/dependency/PivotControlDataModule.kt
3891090345
package com.example.controlpivot.data.dependency import androidx.datastore.preferences.core.stringPreferencesKey import com.example.controlpivot.AppConstants import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.local.DataObjectStorage import com.example.controlpivot.data.local.datasource.SessionLocalDatasource import com.example.controlpivot.data.local.datasource.SessionLocalDatasourceImpl import com.example.controlpivot.data.remote.datasource.SessionRemoteDatasource import com.example.controlpivot.data.remote.datasource.SessionRemoteDatasourceImpl import com.example.controlpivot.data.remote.service.SessionApiService import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.data.repository.SessionRepositoryImpl import com.google.gson.reflect.TypeToken import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import retrofit2.Retrofit val sessionDataModule = module { includes(baseModule) single<SessionLocalDatasource> { SessionLocalDatasourceImpl( DataObjectStorage<Session>( get(), object : TypeToken<Session>() {}.type, androidContext().datastore, stringPreferencesKey((AppConstants.SESSION_PREFERENCES)) ) ) } single<SessionApiService> { get<Retrofit>().create(SessionApiService::class.java) } single<SessionRemoteDatasource> { SessionRemoteDatasourceImpl(get()) } single<SessionRepository> { SessionRepositoryImpl(get(), get()) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/dependency/SessionModule.kt
4033616793
package com.example.controlpivot.data.dependency import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.controlpivot.AppConstants import com.example.controlpivot.data.local.DataObjectStorage import com.example.controlpivot.data.local.datasource.MachinePendingDeleteDatasource import com.example.controlpivot.data.local.datasource.MachinePendingDeleteDatasourceImpl import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.data.repository.MachinePendingDeleteRepository import com.example.controlpivot.data.repository.MachinePendingDeleteRepositoryImpl import com.google.gson.reflect.TypeToken import org.koin.android.ext.koin.androidContext import org.koin.dsl.module val Context.datastore: DataStore<Preferences> by preferencesDataStore(AppConstants.APP_PREFERENCES) val pendingDeleteModule = module{ includes(baseModule) single<MachinePendingDeleteDatasource> { MachinePendingDeleteDatasourceImpl( DataObjectStorage<MachinePendingDelete>( get(), object : TypeToken<MachinePendingDelete>() {}.type, androidContext().datastore, stringPreferencesKey((AppConstants.PENDING_DELETE_PREFERENCES)) ) ) } single<MachinePendingDeleteRepository> { MachinePendingDeleteRepositoryImpl(get()) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/dependency/PendingDeleteModule.kt
1216790902
package com.example.controlpivot.data.dependency import androidx.room.Room import com.example.controlpivot.AppConstants import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.data.local.database.AppDatabase import com.google.gson.Gson import okhttp3.OkHttpClient import org.koin.android.ext.koin.androidApplication import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory val baseModule = module { single<AppDatabase> { Room.databaseBuilder( androidApplication(), AppDatabase::class.java, AppConstants.APP_DATABASE_NAME ).build() } single<OkHttpClient> { val builder = OkHttpClient.Builder() builder.addInterceptor { chain -> val request = chain.request().newBuilder() .addHeader("Authorization", AppConstants.AUTHORIZATION) .build() chain.proceed(request) } builder.build() } single<Retrofit> { Retrofit.Builder() .baseUrl(AppConstants.PIVOT_CONTROL_API_BASE_URL) .client(get()) .addConverterFactory(GsonConverterFactory.create()) .build() } single { Gson() } single { NetworkConnectivityObserver(androidContext()) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/dependency/BaseModule.kt
247321245
package com.example.controlpivot.data.local.datasource import android.util.Log import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.local.database.dao.PivotControlDao import com.example.controlpivot.data.local.database.dao.SectorControlDao import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext class PivotControlLocalDatasourceImpl( private val pivotControlDao: PivotControlDao, private val sectorControlDao: SectorControlDao ): PivotControlLocalDatasource { override suspend fun addPivotControl(pivot: PivotControlEntity): Resource<Int> = withContext(Dispatchers.IO) { val result = pivotControlDao.insert(pivot) if (result > 0L) return@withContext Resource.Success(result.toInt()) Resource.Error( Message.StringResource(R.string.add_pivot_error) ) } override suspend fun upsertSectorControl(sectorControl: SectorControl): Resource<Int> = withContext(Dispatchers.IO) { val result = sectorControlDao.insert(sectorControl) if (result > 0L) return@withContext Resource.Success(result.toInt()) Resource.Error( Message.StringResource(R.string.add_sector_error) ) } override suspend fun getPivotControl(id: Int): Resource<PivotControlEntity> = withContext(Dispatchers.IO) { val result = pivotControlDao.get(id) if (result != null) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.pivot_not_found) ) } override fun getPivotControls(query: String): Flow<Resource<List<PivotControlEntity>>> = flow { pivotControlDao.getAll(query).onEach { emit(Resource.Success(it)) }.catch { Resource.Error<List<PivotControlEntity>>( Message.StringResource(R.string.get_pivots_error) ) }.collect() } override fun getSectorControls(query: String): Flow<Resource<List<SectorControl>>> = flow { sectorControlDao.getAllSectors(query).onEach { emit(Resource.Success(it)) }.catch { Resource.Error<List<SectorControl>>( Message.StringResource(R.string.get_sectors_error) ) }.collect() } override fun getSectorsForPivot(query: Int): Flow<Resource<List<SectorControl>>> = flow { sectorControlDao.getSectorsForPivot(query).onEach { emit(Resource.Success(it)) }.catch { Resource.Error<List<SectorControl>>( Message.StringResource(R.string.get_sectors_error) ) }.collect() } override suspend fun upsertPivotControls(pivots: List<PivotControlEntity>): Resource<Int> = synchronized(this) { runBlocking(Dispatchers.IO) { val result = pivotControlDao.upsertAll(pivots) if (result.isEmpty() && pivots.isNotEmpty()) return@runBlocking Resource.Error<Int>( Message.StringResource(R.string.update_pivots_error) ) Resource.Success(result.size) } } override suspend fun updatePivotControl(pivot: PivotControlEntity): Resource<Int> = withContext(Dispatchers.IO) { val result = pivotControlDao.update(pivot) if (result > 0) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.update_pivot_error) ) } override suspend fun deletePivotControl(pivot: PivotControlEntity): Resource<Int> = withContext(Dispatchers.IO) { val result = pivotControlDao.delete(pivot) if (result > 0) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.delete_pivot_error) ) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/PivotControlLocalDatasourceImpl.kt
3578767171