path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/climate/ClimateScreen.kt
3091179282
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/ClimateEvent.kt
3870925627
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/login/LoginEvent.kt
4135363154
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/LoginScreen.kt
3596956664
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/Credentials.kt
3553296279
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/LoginState.kt
684056715
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/pivotcontrol/PivotControlScreen.kt
3361587621
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/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 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/ControlState.kt
2751532434
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/session/SessionScreen.kt
2118900157
@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/model/MachineModel.kt
1744884973
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/PivotControlsWithSectors.kt
4090297101
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/IdPivotModel.kt
1459561744
package com.example.controlpivot.ui.model data class IdPivotModel( val idPivot: Int, val pivotName: String, )
pivot-control/app/src/main/java/com/example/controlpivot/Extensions.kt
1648705354
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/MyApplication.kt
2001717709
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/MainActivity.kt
4167250563
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/AppModule.kt
2618676423
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/AppConstants.kt
146598919
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/utils/CheckPermissions.kt
2780632623
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/GetUriFromFile.kt
684234882
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/Converters.kt
1451657833
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/DateFormat.kt
1217318897
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/DateTimeObj.kt
4251119670
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/Message.kt
651892683
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/Resource.kt
721726500
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/NetworkConnectivityObserver.kt
2813979942
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/ConnectivityObserver.kt
982095909
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/data/repository/PivotMachineRepository.kt
473047135
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/ClimateRepository.kt
3616063408
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/MachinePendingDeleteRepository.kt
1152527701
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/PivotControlRepositoryImpl.kt
4173044456
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/ClimateRepositoryImpl.kt
144400226
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/PivotMachineRepositoryImpl.kt
1258603675
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/SessionRepository.kt
1883559161
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/MachinePendingDeleteRepositoryImpl.kt
2013452323
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/SessionRepositoryImpl.kt
107777339
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/PivotControlRepository.kt
4082751368
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/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.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/PivotMachineDataModule.kt
2646137032
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/PivotControlDataModule.kt
3891090345
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/SessionModule.kt
4033616793
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/PendingDeleteModule.kt
1216790902
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/BaseModule.kt
247321245
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/local/datasource/PivotControlLocalDatasourceImpl.kt
3578767171
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/MachinePendingDeleteDatasource.kt
3014156284
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.utils.Resource interface MachinePendingDeleteDatasource { suspend fun savePendingDelete(machinesPending: MachinePendingDelete): Resource<Int> suspend fun getPendingDelete(): Resource<MachinePendingDelete> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/MachinePendingDeleteDatasourceImpl.kt
469347541
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.R import com.example.controlpivot.data.local.DataObjectStorage import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext class MachinePendingDeleteDatasourceImpl( private val machinePendingDeleteStorage: DataObjectStorage<MachinePendingDelete> ): MachinePendingDeleteDatasource { override suspend fun savePendingDelete(machinesPending: MachinePendingDelete): Resource<Int> = withContext(Dispatchers.IO) { machinePendingDeleteStorage.saveData(machinesPending) } override suspend fun getPendingDelete(): Resource<MachinePendingDelete> = withContext(Dispatchers.IO) { try { machinePendingDeleteStorage.getData().first() } catch (e: Exception) { Resource.Error(Message.StringResource(R.string.get_pending_delete_error)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/PivotMachineLocalDatasource.kt
544351933
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow interface PivotMachineLocalDatasource { suspend fun addPivotMachine(machine: PivotMachineEntity): Resource<Int> suspend fun getPivotMachine(id: Int): Resource<PivotMachineEntity> fun getPivotMachineAsync(id: Int): Flow<Resource<PivotMachineEntity>> suspend fun getPivotMachineByRemoteId(remoteId: Int): Resource<PivotMachineEntity> suspend fun getPivotMachines(): Resource<List<PivotMachineEntity>> fun getPivotMachines(query: String): Flow<Resource<List<PivotMachineEntity>>> suspend fun upsertPivotMachines(machines: List<PivotMachineEntity>): Resource<Int> suspend fun updatePivotMachine(machine: PivotMachineEntity): Resource<Int> suspend fun deletePivotMachine(machine: PivotMachineEntity): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/SessionLocalDatasource.kt
2773796556
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.utils.Resource interface SessionLocalDatasource { suspend fun saveSession(session: Session): Resource<Int> suspend fun getSession(): Resource<Session> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/ClimateLocalDatasource.kt
1889629380
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow interface ClimateLocalDatasource { suspend fun addClimate(climate: Climate): Resource<Int> suspend fun getClimate(id: Int): Resource<Climate> suspend fun getClimatesByIdPivot(id: Int): Resource<List<Climate>> fun getClimates(query: String): Flow<Resource<List<Climate>>> suspend fun upsertClimates(climates: List<Climate>): Resource<Int> suspend fun updateClimate(climate: Climate): Resource<Int> suspend fun deleteClimate(climate: Climate): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/PivotMachineLocalDatasourceImpl.kt
1849567105
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.R import com.example.controlpivot.data.local.database.dao.PivotMachineDao import com.example.controlpivot.data.local.model.PivotMachineEntity 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 PivotMachineLocalDatasourceImpl( private val pivotMachineDao: PivotMachineDao ): PivotMachineLocalDatasource { override suspend fun addPivotMachine(machine: PivotMachineEntity): Resource<Int> = withContext(Dispatchers.IO) { val result = pivotMachineDao.insert(machine) if (result > 0L) return@withContext Resource.Success(result.toInt()) Resource.Error( Message.StringResource(R.string.add_machine_error) ) } override suspend fun getPivotMachine(id: Int): Resource<PivotMachineEntity> = withContext(Dispatchers.IO) { val result = pivotMachineDao.get(id) if (result != null) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.machine_not_found) ) } override fun getPivotMachineAsync(id: Int): Flow<Resource<PivotMachineEntity>> = flow { pivotMachineDao.getPivotMachineAsync(id).onEach { if (it == null) emit(Resource.Error(Message.StringResource(R.string.machine_not_found))) else emit(Resource.Success(it)) }.collect() } override suspend fun getPivotMachineByRemoteId(remoteId: Int): Resource<PivotMachineEntity> = withContext(Dispatchers.IO) { val result = pivotMachineDao.getPivotMachine(remoteId) if (result != null) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.machine_not_found) ) } override suspend fun getPivotMachines(): Resource<List<PivotMachineEntity>> = withContext(Dispatchers.IO) { val result = pivotMachineDao.getAllMachines() if (result != null) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.get_machines_error) ) } override fun getPivotMachines(query: String): Flow<Resource<List<PivotMachineEntity>>> = flow { pivotMachineDao.getAll(query).onEach { emit(Resource.Success(it)) }.catch { Resource.Error<List<PivotMachineEntity>>( Message.StringResource(R.string.get_machines_error) ) }.collect() } override suspend fun upsertPivotMachines(machines: List<PivotMachineEntity>): Resource<Int> = synchronized(this) { runBlocking(Dispatchers.IO) { pivotMachineDao.getAll().forEach { machine -> if (machines.find { it.remoteId == machine.id } == null) pivotMachineDao.delete(machine) } val result = pivotMachineDao.upsertAll(machines) if (result.isEmpty() && machines.isNotEmpty()) return@runBlocking Resource.Error<Int>( Message.StringResource(R.string.update_machines_error) ) Resource.Success(result.size) } } override suspend fun updatePivotMachine(machine: PivotMachineEntity): Resource<Int> = withContext(Dispatchers.IO) { val result = pivotMachineDao.update(machine) if (result > 0) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.update_machine_error) ) } override suspend fun deletePivotMachine(machine: PivotMachineEntity): Resource<Int> = withContext(Dispatchers.IO) { val result = pivotMachineDao.delete(machine) if (result > 0) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.delete_machine_error) ) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/SessionLocalDatasourceImpl.kt
1986973309
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.local.DataObjectStorage import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext class SessionLocalDatasourceImpl( private val sessionStorage: DataObjectStorage<Session>, ) : SessionLocalDatasource { override suspend fun saveSession(session: Session): Resource<Int> = withContext(Dispatchers.IO) { sessionStorage.saveData(session) } override suspend fun getSession(): Resource<Session> = withContext(Dispatchers.IO) { try { sessionStorage.getData().first() } catch (e: Exception) { Resource.Error(Message.StringResource(R.string.get_session_error)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/ClimateLocalDatasourceImpl.kt
331163178
package com.example.controlpivot.data.local.datasource import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.data.local.database.dao.ClimateDao 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 ClimateLocalDatasourceImpl( private val climateDao: ClimateDao ): ClimateLocalDatasource { override suspend fun addClimate(climate: Climate): Resource<Int> = withContext(Dispatchers.IO) { val result = climateDao.insert(climate) if (result > 0L) return@withContext Resource.Success(result.toInt()) Resource.Error( Message.StringResource(R.string.add_climate_error) ) } override suspend fun getClimate(id: Int): Resource<Climate> = withContext(Dispatchers.IO) { val result = climateDao.get(id) if (result != null) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.climate_not_found) ) } override suspend fun getClimatesByIdPivot(id: Int): Resource<List<Climate>> = withContext(Dispatchers.IO) { val result = climateDao.getByIdPivot(id) if (result != null) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.climate_not_found) ) } override fun getClimates(query: String): Flow<Resource<List<Climate>>> = flow { climateDao.getAll(query).onEach { emit(Resource.Success(it)) }.catch { Resource.Error<List<Climate>>( Message.StringResource(R.string.get_climates_error) ) }.collect() } override suspend fun upsertClimates(climates: List<Climate>): Resource<Int> = synchronized(this) { runBlocking(Dispatchers.IO) { val result = climateDao.upsertAll(climates) if (result.isEmpty() && climates.isNotEmpty()) return@runBlocking Resource.Error<Int>( Message.StringResource(R.string.update_climates_error) ) Resource.Success(result.size) } } override suspend fun updateClimate(climate: Climate): Resource<Int> = withContext(Dispatchers.IO) { val result = climateDao.update(climate) if (result > 0) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.update_climate_error) ) } override suspend fun deleteClimate(climate: Climate): Resource<Int> = withContext(Dispatchers.IO) { val result = climateDao.delete(climate) if (result > 0) return@withContext Resource.Success(result) Resource.Error( Message.StringResource(R.string.delete_climate_error) ) } }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/datasource/PivotControlLocalDatasource.kt
4272110003
package com.example.controlpivot.data.local.datasource 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 PivotControlLocalDatasource { suspend fun addPivotControl(pivot: PivotControlEntity): Resource<Int> suspend fun upsertSectorControl(sectorControl: SectorControl) : Resource<Int> suspend fun getPivotControl(id: Int): Resource<PivotControlEntity> fun getPivotControls(query: String): Flow<Resource<List<PivotControlEntity>>> fun getSectorControls(query: String): Flow<Resource<List<SectorControl>>> fun getSectorsForPivot(query: Int): Flow<Resource<List<SectorControl>>> suspend fun upsertPivotControls(pivots: List<PivotControlEntity>): Resource<Int> suspend fun updatePivotControl(pivot: PivotControlEntity): Resource<Int> suspend fun deletePivotControl(pivot: PivotControlEntity): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/database/dao/SectorControlDao.kt
4182577339
package com.example.controlpivot.data.local.database.dao import androidx.room.Dao import androidx.room.Query import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import kotlinx.coroutines.flow.Flow @Dao abstract class SectorControlDao: BaseDao<SectorControl>() { override fun getTableName(): String = "sector_controls" @Query("SELECT * FROM sector_control WHERE sector_control_id = :id ") abstract fun getSectorsForPivot(id: Int): Flow<List<SectorControl>> @Query("SELECT * FROM sector_control WHERE sector_control_id LIKE '%' || :query || '%' ORDER BY sector_control_id ASC") abstract fun getAllSectors(query: String): Flow<List<SectorControl>> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/database/dao/ClimateDao.kt
2757833967
package com.example.controlpivot.data.local.database.dao import androidx.room.Dao import androidx.room.Query import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.data.local.database.dao.BaseDao import kotlinx.coroutines.flow.Flow @Dao abstract class ClimateDao: BaseDao<Climate>() { override fun getTableName(): String = "climatic_var" @Query("SELECT * FROM climatic_var WHERE id_pivot LIKE '%' || :query || '%' ORDER BY id_pivot ASC") abstract fun getAll(query: String): Flow<List<Climate>> @Query("SELECT * FROM climatic_var WHERE id_pivot = :id ") abstract fun getByIdPivot(id: Int): List<Climate> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/database/dao/BaseDao.kt
1217766121
package com.example.controlpivot.data.local.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy.Companion.REPLACE import androidx.room.RawQuery import androidx.room.Update import androidx.sqlite.db.SimpleSQLiteQuery import androidx.sqlite.db.SupportSQLiteQuery @Dao abstract class BaseDao<T> { protected abstract fun getTableName(): String @Insert(onConflict = REPLACE) abstract suspend fun insert(item: T): Long @Insert(onConflict = REPLACE) abstract suspend fun upsertAll(items: List<T>): List<Long> @RawQuery protected abstract fun query(query: SupportSQLiteQuery): List<T> fun getAll(): List<T> = query(SimpleSQLiteQuery("SELECT * FROM ${getTableName()}")) fun get(id: Int): T? = query( SimpleSQLiteQuery( "SELECT * FROM ${getTableName()} WHERE id = $id" ) ).firstOrNull() @Update abstract suspend fun update(item: T): Int @Delete abstract suspend fun delete(item : T): Int }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/database/dao/PivotControlDao.kt
1229274609
package com.example.controlpivot.data.local.database.dao import androidx.room.Dao import androidx.room.Query import com.example.controlpivot.data.local.model.PivotControlEntity import kotlinx.coroutines.flow.Flow @Dao abstract class PivotControlDao: BaseDao<PivotControlEntity>() { override fun getTableName(): String = "pivot_control" @Query("SELECT * FROM pivot_control WHERE idPivot LIKE '%' || :query || '%' ORDER BY idPivot ASC") abstract fun getAll(query: String): Flow<List<PivotControlEntity>> }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/database/dao/PivotMachineDao.kt
1149077397
package com.example.controlpivot.data.local.database.dao import androidx.room.Dao import androidx.room.Query import com.example.controlpivot.data.local.model.PivotMachineEntity import kotlinx.coroutines.flow.Flow @Dao abstract class PivotMachineDao: BaseDao<PivotMachineEntity>() { override fun getTableName(): String = "pivot_machines" @Query( "SELECT * FROM pivot_machines WHERE name LIKE " + "'%' || :query || '%' OR " + "location LIKE '%' || :query || '%' OR " + "endowment LIKE '%' || :query || '%'OR " + "flow LIKE '%' || :query || '%' OR " + "pressure LIKE '%' || :query || '%' OR " + "length LIKE '%' || :query || '%' OR " + "area LIKE '%' || :query || '%' OR " + "power LIKE '%' || :query || '%' OR " + "speed LIKE '%' || :query || '%' OR " + "efficiency LIKE '%' || :query || '%' ORDER BY name ASC") abstract fun getAll(query: String): Flow<List<PivotMachineEntity>> @Query("SELECT * FROM pivot_machines ORDER BY name ASC") abstract fun getAllMachines(): List<PivotMachineEntity> @Query("SELECT * FROM pivot_machines WHERE remote_id=:remoteId") abstract fun getPivotMachine(remoteId: Int): PivotMachineEntity? @Query("SELECT * FROM pivot_machines WHERE id=:id") abstract fun getPivotMachineAsync(id: Int): Flow<PivotMachineEntity?> @Query("DELETE FROM pivot_machines") abstract suspend fun deleteAll(): Int }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/database/AppDatabase.kt
43821114
package com.example.controlpivot.data.local.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.local.database.dao.ClimateDao import com.example.controlpivot.data.local.database.dao.PivotControlDao import com.example.controlpivot.data.local.database.dao.PivotMachineDao import com.example.controlpivot.data.local.database.dao.SectorControlDao import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.utils.Converters @Database( entities = [ PivotMachineEntity::class, Climate::class, PivotControlEntity::class, SectorControl::class ], version = 1, exportSchema = false ) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun pivotMachineDao(): PivotMachineDao abstract fun climateDao(): ClimateDao abstract fun pivotControlDao(): PivotControlDao abstract fun sectorControlDao(): SectorControlDao }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/DataObjectStorage.kt
277208927
package com.example.controlpivot.data.local import android.util.Log import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import com.example.controlpivot.AppConstants import com.example.controlpivot.R import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import com.google.gson.Gson import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import java.lang.reflect.Type class DataObjectStorage<T> constructor( private val gson: Gson, private val type: Type, private val dataStore: DataStore<Preferences>, private val preferenceKey: Preferences.Key<String>, ) { suspend fun saveData(data: T): Resource<Int> { try { dataStore.edit { val jsonString = gson.toJson(data, type) it[preferenceKey] = jsonString } } catch (e: Exception) { return Resource.Error(Message.StringResource(R.string.save_data_error)) } return Resource.Success(0) } fun getData(): Flow<Resource<T>> = flow { dataStore.data.map { preferences -> val jsonString = preferences[preferenceKey]?:AppConstants.EMPTY_JSON_STRING val elements = gson.fromJson<T>(jsonString, type) Log.d("TAG", elements.toString()) elements }.catch { emit(Resource.Error(Message.StringResource(R.string.retrieve_data_error))) }.collect { if (it == null) { emit(Resource.Error(Message.StringResource(R.string.retrieve_data_error))) } else emit(Resource.Success(it)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/local/model/MachinePendingDelete.kt
3029572555
package com.example.controlpivot.data.local.model data class MachinePendingDelete( var listId: List<Int> = listOf(), )
pivot-control/app/src/main/java/com/example/controlpivot/data/local/model/PivotMachineEntity.kt
1774464975
package com.example.controlpivot.data.local.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.example.controlpivot.data.remote.model.PivotMachine @Entity(tableName = "pivot_machines") data class PivotMachineEntity( @PrimaryKey(autoGenerate = true) val id: Int = 0, @ColumnInfo(name = "remote_id") val remoteId: Int = Int.MAX_VALUE, @ColumnInfo(name = "name") val name: String = "", val location: String = "", val endowment: Double = 0.0, val flow: Double = 0.0, val pressure: Double = 0.0, val length: Double = 0.0, val area: Double = 0.0, val power: Double = 0.0, val speed: Double = 0.0, val efficiency: Double = 0.0, val isSave: Boolean = true, ) fun PivotMachine.toLocal() = PivotMachineEntity( id, id, name, location, endowment, flow, pressure, length, area, power, speed, efficiency )
pivot-control/app/src/main/java/com/example/controlpivot/data/local/model/PivotControlEntity.kt
3693948279
package com.example.controlpivot.data.local.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "pivot_control") data class PivotControlEntity( @PrimaryKey val id: Int, val idPivot: Int, val progress: Float, val isRunning: Boolean, val stateBomb: Boolean, val wayToPump: Boolean, val turnSense: Boolean, ) @Entity(tableName = "sector_control") data class SectorControl( @PrimaryKey val id: Int, @ColumnInfo(name = "sector_id") val sector_id: Int, val irrigateState: Boolean, val dosage: Int, val motorVelocity: Int, @ColumnInfo(name = "sector_control_id") val sector_control_id: Int )
pivot-control/app/src/main/java/com/example/controlpivot/data/common/model/Climate.kt
3582991337
package com.example.controlpivot.data.common.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "climatic_var") data class Climate( @PrimaryKey val id:Int, val id_pivot: Int, val referenceEvapo: Double, val cropEvapo: Double, val cropCoefficient: Double, val solarRadiation: Int, val windSpeed: Double, val atmoPressure: Double, val rainy: Int, val temp: Double, val RH: Double, val timestamp: String = "", )
pivot-control/app/src/main/java/com/example/controlpivot/data/common/model/Session.kt
2748796486
package com.example.controlpivot.data.common.model import com.google.gson.annotations.SerializedName data class Session( @SerializedName("id") val id: Int, @SerializedName("name") val name: String, @SerializedName("user_name") val userName: String, @SerializedName("password") val password: String, @SerializedName("role") val role: String )
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/SessionRemoteDatasourceImpl.kt
714052464
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.remote.MessageBody import com.example.controlpivot.data.remote.service.SessionApiService import com.example.controlpivot.ui.screen.login.Credentials import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class SessionRemoteDatasourceImpl( private val sessionApiService: SessionApiService, ) : SessionRemoteDatasource { override suspend fun getSession( credentials: Credentials, ): Resource<Session> = withContext(Dispatchers.IO){ try { val response = sessionApiService.getSession( credentials ) if (response.isSuccessful) { return@withContext Resource.Success(response.body()!!.session) } Resource.Error( Message.DynamicString(Gson().fromJson( response.errorBody()?.charStream(), MessageBody::class.java ).message) ) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.login_error)) } } override suspend fun updateSession(credentials: Credentials): Resource<Session> = withContext(Dispatchers.IO){ try { val response = sessionApiService.updateSession( credentials ) if (response.isSuccessful) { return@withContext Resource.Success(response.body()!!) } Resource.Error(Message.StringResource(R.string.update_error)) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.update_error)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/PivotControlRemoteDatasource.kt
1970878351
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.remote.model.PivotControl import com.example.controlpivot.utils.Resource interface PivotControlRemoteDatasource { suspend fun getPivotControls(): Resource<List<PivotControl>> suspend fun getSectorControls(): Resource<List<SectorControl>> suspend fun insertPivotControl(pivot: PivotControlEntity): Resource<Int> suspend fun insertSectorControl(sector: SectorControl): Resource<Int> suspend fun updatePivotControl(pivot: PivotControlEntity): Resource<Int> suspend fun updateSectorControl(sector: SectorControl): Resource<Int> suspend fun deletePivotControl(pivotId: Int): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/PivotMachineRemoteDatasource.kt
1133698628
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.data.remote.model.PivotMachine import com.example.controlpivot.utils.Resource interface PivotMachineRemoteDatasource { suspend fun getPivotMachines(): Resource<List<PivotMachine>> suspend fun insertPivotMachine(machine: PivotMachine): Resource<PivotMachine> suspend fun updatePivotMachine(machine: PivotMachine): Resource<Int> suspend fun deletePivotMachine(machineId: Int): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/PivotMachineRemoteDatasourceImpl.kt
1870393944
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.R import com.example.controlpivot.data.remote.MessageBody import com.example.controlpivot.data.remote.model.PivotMachine import com.example.controlpivot.data.remote.service.PivotMachineApiService import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class PivotMachineRemoteDatasourceImpl( private val pivotMachineApiService: PivotMachineApiService ): PivotMachineRemoteDatasource { override suspend fun getPivotMachines(): Resource<List<PivotMachine>> = withContext(Dispatchers.IO) { try { val response = pivotMachineApiService.getPivotMachines() if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString( Gson().fromJson( response.errorBody()?.charStream(), MessageBody::class.java ).message )) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.fetch_machines_error)) } } override suspend fun insertPivotMachine(machine: PivotMachine): Resource<PivotMachine> = withContext(Dispatchers.IO) { try { val response = pivotMachineApiService.insertPivotMachine(machine) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.add_machine_error)) } } override suspend fun updatePivotMachine(machine: PivotMachine): Resource<Int> = withContext(Dispatchers.IO) { try { val response = pivotMachineApiService.updatePivotMachine(machine) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.update_machine_error)) } } override suspend fun deletePivotMachine(machineId: Int): Resource<Int> = withContext(Dispatchers.IO) { try { val response = pivotMachineApiService.deletePivotMachine(machineId) if (response.isSuccessful || response.code() == 404) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.delete_machine_error)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/ClimateRemoteDatasource.kt
3374557398
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.utils.Resource interface ClimateRemoteDatasource { suspend fun getClimates(): Resource<List<Climate>> suspend fun insertClimate(climate: Climate): Resource<Int> suspend fun updateClimate(climate: Climate): Resource<Int> suspend fun deleteClimate(climateId: Int): Resource<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/ClimateRemoteDatasourceImpl.kt
1806045858
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.data.remote.MessageBody import com.example.controlpivot.data.remote.service.ClimateApiService import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ClimateRemoteDatasourceImpl( private val climateApiService: ClimateApiService ): ClimateRemoteDatasource { override suspend fun getClimates(): Resource<List<Climate>> = withContext(Dispatchers.IO) { try { val response = climateApiService.getClimates() if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error( Message.DynamicString( Gson().fromJson( response.errorBody()?.charStream(), MessageBody::class.java ).message )) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.fetch_climates_error)) } } override suspend fun insertClimate(climate: Climate): Resource<Int> = withContext(Dispatchers.IO) { try { val response = climateApiService.insertClimate(climate) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.add_climate_error)) } } override suspend fun updateClimate(climate: Climate): Resource<Int> = withContext(Dispatchers.IO) { try { val response = climateApiService.updateClimate(climate) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.update_climate_error)) } } override suspend fun deleteClimate(climateId: Int): Resource<Int> = withContext(Dispatchers.IO) { try { val response = climateApiService.deleteClimate(climateId) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.delete_climate_error)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/SessionRemoteDatasource.kt
3571800476
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.ui.screen.login.Credentials import com.example.controlpivot.utils.Resource interface SessionRemoteDatasource { suspend fun getSession( credentials: Credentials ): Resource<Session> suspend fun updateSession( credentials: Credentials ): Resource<Session> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/datasource/PivotControlRemoteDatasourceImpl.kt
3244514884
package com.example.controlpivot.data.remote.datasource import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.remote.model.PivotControl import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.remote.MessageBody import com.example.controlpivot.data.remote.service.PivotControlApiService import com.example.controlpivot.data.remote.service.SectorControlApiService import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class PivotControlRemoteDatasourceImpl( private val pivotControlApiService: PivotControlApiService, private val sectorControlApiService: SectorControlApiService ): PivotControlRemoteDatasource { override suspend fun getPivotControls(): Resource<List<PivotControl>> = withContext(Dispatchers.IO) { try { val response = pivotControlApiService.getPivotControls() if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error( Message.DynamicString( Gson().fromJson( response.errorBody()?.charStream(), MessageBody::class.java ).message )) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.fetch_pivots_error)) } } override suspend fun getSectorControls(): Resource<List<SectorControl>> = withContext(Dispatchers.IO) { try { val response = sectorControlApiService.getSectorControls() if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error( Message.DynamicString( Gson().fromJson( response.errorBody()?.charStream(), MessageBody::class.java ).message )) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.fetch_sectors_error)) } } override suspend fun insertPivotControl(pivot: PivotControlEntity): Resource<Int> = withContext(Dispatchers.IO) { try { val response = pivotControlApiService.insertPivotControl(pivot) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.add_pivot_error)) } } override suspend fun insertSectorControl(sector: SectorControl): Resource<Int> = withContext(Dispatchers.IO) { try { val response = sectorControlApiService.insertSectorControl(sector) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.add_sector_error)) } } override suspend fun updatePivotControl(pivot: PivotControlEntity): Resource<Int> = withContext(Dispatchers.IO) { try { val response = pivotControlApiService.updatePivotControl(pivot) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.update_pivot_error)) } } override suspend fun updateSectorControl(sector: SectorControl): Resource<Int> = withContext(Dispatchers.IO) { try { val response = sectorControlApiService.updateSectorControl(sector) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.update_sector_error)) } } override suspend fun deletePivotControl(pivotId: Int): Resource<Int> = withContext(Dispatchers.IO) { try { val response = pivotControlApiService.deletePivotControl(pivotId) if (response.isSuccessful) return@withContext Resource.Success(response.body()!!) Resource.Error(Message.DynamicString(response.errorBody().toString())) }catch (e: Exception) { Resource.Error(Message.StringResource(R.string.delete_pivot_error)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/model/PivotControl.kt
64384816
package com.example.controlpivot.data.remote.model import com.example.controlpivot.data.local.model.SectorControl data class PivotControl( val id: Int, val idPivot: Int, val progress: Float, val isRunning: Boolean, val stateBomb: Boolean, val wayToPump: Boolean, val turnSense: Boolean, val sectorControlList: List<SectorControl> )
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/model/PivotMachine.kt
4269663237
package com.example.controlpivot.data.remote.model import com.example.controlpivot.data.local.model.PivotMachineEntity data class PivotMachine( val id: Int, val name: String, val location: String, val endowment: Double, val flow: Double, val pressure: Double, val length: Double, val area: Double, val power: Double, val speed: Double, val efficiency: Double, ) fun PivotMachineEntity.toNetwork() = PivotMachine( remoteId, name, location, endowment, flow, pressure, length, area, power, speed, efficiency )
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/MessageBody.kt
572214489
package com.example.controlpivot.data.remote import com.example.controlpivot.data.common.model.Session data class MessageBody ( val message: String, val session: Session, )
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/service/SessionApiService.kt
2065835893
package com.example.controlpivot.data.remote.service import com.example.controlpivot.AppConstants import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.remote.MessageBody import com.example.controlpivot.ui.screen.login.Credentials import retrofit2.Response import retrofit2.http.Body import retrofit2.http.Headers import retrofit2.http.POST import retrofit2.http.PUT interface SessionApiService { @Headers("Content-Type: application/json") @POST(AppConstants.SESSION_API_PATH) suspend fun getSession( @Body credentials: Credentials ): Response<MessageBody> @Headers("Content-Type: application/json") @PUT(AppConstants.SESSION_API_PATH) suspend fun updateSession( @Body credentials: Credentials ): Response<Session> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/service/SectorControlApiService.kt
540705318
package com.example.controlpivot.data.remote.service import com.example.controlpivot.AppConstants import com.example.controlpivot.data.local.model.SectorControl import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Query interface SectorControlApiService { @GET(AppConstants.PIVOT_SECTOR_CONTROL_API_PATH) suspend fun getSectorControls( ): Response<List<SectorControl>> @POST suspend fun insertSectorControl( @Body sectorControl: SectorControl ): Response<Int> @PUT suspend fun updateSectorControl( @Body sectorControl: SectorControl ): Response<Int> @DELETE suspend fun deleteSectorControl( @Query("pivotId") sectorId: Int ): Response<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/service/PivotControlApiService.kt
2096036173
package com.example.controlpivot.data.remote.service import com.example.controlpivot.AppConstants import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.data.remote.model.PivotControl import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Query interface PivotControlApiService { @GET(AppConstants.PIVOT_CONTROL_API_PATH) suspend fun getPivotControls( ): Response<List<PivotControl>> @POST suspend fun insertPivotControl( @Body pivotControl: PivotControlEntity ): Response<Int> @PUT suspend fun updatePivotControl( @Body pivotControl: PivotControlEntity ): Response<Int> @DELETE suspend fun deletePivotControl( @Query("pivotId") pivotId: Int ): Response<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/service/ClimateApiService.kt
3082050165
package com.example.controlpivot.data.remote.service import com.example.controlpivot.AppConstants import com.example.controlpivot.data.common.model.Climate import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Query interface ClimateApiService { @GET(AppConstants.CLIMATE_API_PATH) suspend fun getClimates( ): Response<List<Climate>> @POST suspend fun insertClimate( @Body climate: Climate ): Response<Int> @PUT suspend fun updateClimate( @Body climate: Climate ): Response<Int> @DELETE suspend fun deleteClimate( @Query("climateId") climateId: Int ): Response<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/data/remote/service/PivotMachineApiService.kt
2331514197
package com.example.controlpivot.data.remote.service import com.example.controlpivot.AppConstants import com.example.controlpivot.data.remote.model.PivotMachine import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path interface PivotMachineApiService { @GET(AppConstants.PIVOT_MACHINES_API_PATH) suspend fun getPivotMachines( ): Response<List<PivotMachine>> @POST(AppConstants.PIVOT_MACHINES_API_PATH) suspend fun insertPivotMachine( @Body pivotMachine: PivotMachine ): Response<PivotMachine> @PUT(AppConstants.PIVOT_MACHINES_API_PATH) suspend fun updatePivotMachine( @Body pivotMachine: PivotMachine ): Response<Int> @DELETE(AppConstants.PIVOT_MACHINES_API_PATH+AppConstants.DELETE_API_PATH) suspend fun deletePivotMachine( @Path("id") id: Int ): Response<Int> }
pivot-control/app/src/main/java/com/example/controlpivot/domain/usecase/GetPivotControlsWithSectorsUseCase.kt
3673847876
package com.example.controlpivot.domain.usecase import android.util.Log import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.repository.PivotControlRepository import com.example.controlpivot.ui.model.PivotControlsWithSectors import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach class GetPivotControlsWithSectorsUseCase( private val controlRepository: PivotControlRepository, ) { operator fun invoke(query: String): Flow<Resource<List<PivotControlsWithSectors>>> = flow { controlRepository.getAllPivotControls(query) .combine(controlRepository.getAllSectorControls("")) { result, resource -> when (result) { is Resource.Error -> { emit(Resource.Error(result.message)) return@combine } is Resource.Success -> { var sectorList = listOf<SectorControl>() when (resource) { is Resource.Error -> { emit(Resource.Error(resource.message)) return@combine } is Resource.Success -> { sectorList = resource.data Log.d("GET", resource.data.toString()) } } emit( Resource.Success( result.data.map { pivotControl -> PivotControlsWithSectors( id = pivotControl.id, idPivot = pivotControl.idPivot, progress = pivotControl.progress, isRunning = pivotControl.isRunning, stateBomb = pivotControl.stateBomb, wayToPump = pivotControl.wayToPump, turnSense = pivotControl.turnSense, sectorList = sectorList.filter { it.sector_control_id == pivotControl.id } ) } )) } } }.collect() } }
pivot-control/app/src/main/java/com/example/controlpivot/domain/usecase/GetIdPivotNameUseCase.kt
3125131138
package com.example.controlpivot.domain.usecase import com.example.controlpivot.data.repository.PivotMachineRepository import com.example.controlpivot.ui.model.IdPivotModel import com.example.controlpivot.utils.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach class GetIdPivotNameUseCase( private val pivotMachineRepository: PivotMachineRepository, ) { operator fun invoke(query: String): Flow<Resource<List<IdPivotModel>>> = flow { pivotMachineRepository.getAllPivotMachines(query).onEach { result -> when (result) { is Resource.Error -> { emit(Resource.Error(result.message)) return@onEach } is Resource.Success -> { emit(Resource.Success( result.data.filter { it.remoteId != Int.MAX_VALUE } .map { machine -> IdPivotModel( idPivot = machine.remoteId, pivotName = machine.name ) } )) } } }.collect() } }
pivot-control/app/src/main/java/com/example/controlpivot/domain/usecase/DeletePendingMachineUseCase.kt
2690419018
package com.example.controlpivot.domain.usecase import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.data.remote.datasource.PivotMachineRemoteDatasource import com.example.controlpivot.data.repository.MachinePendingDeleteRepository import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking class DeletePendingMachineUseCase( private val remoteDatasource: PivotMachineRemoteDatasource, private val machinePendingDeleteRepository: MachinePendingDeleteRepository, ) { suspend operator fun invoke() = synchronized(this) { runBlocking(Dispatchers.IO) { machinePendingDeleteRepository.getPendingDelete().let { resource -> val pendingDelete = when (resource) { is Resource.Error -> MachinePendingDelete() is Resource.Success -> resource.data } val deletedList = pendingDelete.listId.toMutableList() pendingDelete.listId.forEach { when (remoteDatasource.deletePivotMachine(it)) { is Resource.Success -> { deletedList.remove(it) machinePendingDeleteRepository.savePendingDelete( MachinePendingDelete(deletedList) ) } else -> {} } } } } } }
Calculator-Android/app/src/androidTest/java/com/example/dmstingachcalculator/ExampleInstrumentedTest.kt
6363477
package com.example.dmstingachcalculator 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.dmstingachcalculator", appContext.packageName) } }
Calculator-Android/app/src/test/java/com/example/dmstingachcalculator/ExampleUnitTest.kt
937775570
package com.example.dmstingachcalculator 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) } }
Calculator-Android/app/src/main/java/com/example/dmstingachcalculator/MainActivity.kt
1481363606
package com.example.dmstingachcalculator import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
AndroidApp_VeXe/app/src/androidTest/java/com/example/login/ExampleInstrumentedTest.kt
4292129466
package com.example.login 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.login", appContext.packageName) } }
AndroidApp_VeXe/app/src/test/java/com/example/login/ExampleUnitTest.kt
595896254
package com.example.login 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) } }
AndroidApp_VeXe/app/src/main/java/com/example/login/ui/theme/Color.kt
178537291
package com.example.login.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)
AndroidApp_VeXe/app/src/main/java/com/example/login/ui/theme/Theme.kt
4227603865
package com.example.login.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 LoginTheme( 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 ) }
AndroidApp_VeXe/app/src/main/java/com/example/login/ui/theme/Type.kt
3273098344
package com.example.login.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 ) */ )
AndroidApp_VeXe/app/src/main/java/com/example/login/MainActivity.kt
1994883971
package com.example.login import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
AndroidApp_VeXe/app/src/main/java/com/example/login/Login.kt
2630439124
package com.example.login import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class Login : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) } }
AndroidApp_VeXe/app/src/main/java/com/example/login/Registration.kt
4195786672
package com.example.login import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class Registration : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registration) } }
My_Location/app/src/androidTest/java/com/example/mylocation/ExampleInstrumentedTest.kt
2064907680
package com.example.mylocation 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.mylocation", appContext.packageName) } }
My_Location/app/src/test/java/com/example/mylocation/ExampleUnitTest.kt
1438559452
package com.example.mylocation 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) } }
My_Location/app/src/main/java/com/example/mylocation/MapsActivity.kt
311010508
package com.example.mylocation import android.content.pm.PackageManager import android.location.Location import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.core.app.ActivityCompat import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.example.mylocation.databinding.ActivityMapsBinding import com.google.android.gms.location.CurrentLocationRequest import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices class MapsActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var binding: ActivityMapsBinding private lateinit var currentLocation: Location private lateinit var fusedLocationProviderClient: FusedLocationProviderClient private val permissionCode = 101 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMapsBinding.inflate(layoutInflater) setContentView(binding.root) fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) // Obtain the SupportMapFragment and get notified when the map is ready to be used. getCurrentLocationUser() } private fun getCurrentLocationUser(){ if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), permissionCode) Toast.makeText(this, "permission", Toast.LENGTH_LONG).show() return } else{ fusedLocationProviderClient.lastLocation.addOnSuccessListener { location -> if(location != null){ currentLocation = location Toast.makeText(this, currentLocation.latitude.toString()+ "" + currentLocation.longitude.toString(), Toast.LENGTH_LONG).show() val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) getCurrentLocationUser() } else{ Toast.makeText( this, "Permission denied. Unable to show current location.", Toast.LENGTH_SHORT ).show() } } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when(requestCode){ permissionCode -> if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){ getCurrentLocationUser() } } } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ override fun onMapReady(googleMap: GoogleMap) { val latLng = LatLng(currentLocation.latitude, currentLocation.longitude) val markerOptions: MarkerOptions = MarkerOptions().position(latLng).title("Current Location") googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f)) googleMap.addMarker(markerOptions) } }
CorouniteSample/app/src/androidTest/java/com/example/corounitesample/ExampleInstrumentedTest.kt
1838679690
package com.example.corounitesample 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.corounitesample", appContext.packageName) } }
CorouniteSample/app/src/test/java/com/example/corounitesample/ExampleUnitTest.kt
4028589944
package com.example.corounitesample 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) } }