content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.mad_lab_2 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonColors import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mad_lab_2.ui.theme.MAD_LAB_2Theme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MAD_LAB_2Theme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ChangeColorButton() } } } } } @Composable fun ButtonExample(modifier: Modifier){ Column { var count: MutableState<Int> = rememberSaveable() { mutableStateOf(0) } Text( text = "You have had {${count.value}} glasses of water today", fontSize = 20.sp, textAlign = TextAlign.Center, modifier = Modifier.padding(16.dp) ) Button( onClick = { count.value = 1 }, colors = ButtonDefaults.buttonColors( containerColor = Color.Blue, // Change the color to your desired color // backgroundColor = Color.Red, // Change the color to your desired color contentColor = Color.White // Change the text color if needed ) ) { Text("Add one Glass of Water") } } } @Preview(showBackground = true, showSystemUi = true) @Composable fun ChangeColorButton() { var buttonColor by remember { mutableStateOf(Color.Red) } Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Button( onClick = { if(buttonColor == Color.Green){ buttonColor = Color.Red }else{ buttonColor = Color.Green } }, colors = ButtonDefaults.buttonColors(containerColor = buttonColor) ) { Text(text = "Change Color") } } }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/MainActivity.kt
1846842033
package com.example.mad_lab_2 import android.os.Bundle import android.provider.CalendarContract.Colors import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mad_lab_2.ui.theme.MAD_LAB_2Theme class TaskThree : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MAD_LAB_2Theme { // A surface container using the 'background' color from the theme Column { FillScreenWithRows() FillScreenWithRows() FillScreenWithRows() FillScreenWithRows() FillScreenWithRows() FillScreenWithRows() FillScreenWithRows() } } } } } //@Preview(showBackground = true, backgroundColor = 0x3FFFFFFF) @Preview(showBackground = true, showSystemUi = true) @Composable fun FillScreenWithRows(modifier: Modifier = Modifier) { Card ( modifier = modifier .padding(10.dp) .size(width = 380.dp, height = 100.dp) .clip((RoundedCornerShape(5.dp))), // .border(2.dp, Color.Black) elevation = CardDefaults.cardElevation( defaultElevation = 16.dp ), ){ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly, ) { SizedImage( painter = painterResource(id = R.drawable.noshads_image), contentDescription = "Artist image", imageSize = 100 // Set the desired size here ) ArtistCardColumn() } } } @Composable fun SizedImage( painter: Painter, contentDescription: String?, modifier: Modifier = Modifier, imageSize: Int // Desired size of the image ) { Image( painter = painter, contentDescription = contentDescription, modifier = modifier .size(imageSize.dp) // Set the desired size here .padding(16.dp) .clip(RoundedCornerShape(10.dp)), contentScale = ContentScale.Crop // Adjust content scale if necessary ) } @Composable fun ArtistCardColumn() { Column { Text("Iron Man", fontSize = 30.sp, fontFamily = androidx.compose.ui.text.font.FontFamily.Serif, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold, // modifier = Modifier.padding(16.dp) ) Text("Age: 45" , fontSize = 20.sp, fontFamily = androidx.compose.ui.text.font.FontFamily.Serif, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold, // modifier = Modifier.padding(16.dp) ) } }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/Task03.kt
1953978212
package com.example.mad_lab_2 import android.os.Bundle import android.widget.ImageView import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.magnifier import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mad_lab_2.ui.theme.MAD_LAB_2Theme class TaskTwo : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MAD_LAB_2Theme { // A surface container using the 'background' color from the theme ArtistCardRow() } } } } //@Composable //fun LayoutBox() { // // Row { // Image(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "icon") // Column( // modifier = Modifier.fillMaxSize(), // verticalArrangement = Arrangement.Center, // horizontalAlignment = Alignment.CenterHorizontally // ) { // // // // } // } // //} @Preview(showBackground = true, showSystemUi = true) @Composable fun ArtistCardRow(modifier: Modifier = Modifier) { Card ( modifier = modifier .padding(16.dp) // .size(30.dp) .clip(RoundedCornerShape(10.dp)) .border(2.dp, Color.Black) ){ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly, ) { SizedImageOne( painter = painterResource(id = R.drawable.noshads_image), contentDescription = "Artist image", imageSize = 150 // Set the desired size here ) ArtistCardColumnOne() } } } @Composable fun SizedImageOne( painter: Painter, contentDescription: String?, modifier: Modifier = Modifier, imageSize: Int // Desired size of the image ) { Image( painter = painter, contentDescription = contentDescription, modifier = modifier .size(imageSize.dp) // Set the desired size here .clip(RoundedCornerShape(10.dp)), contentScale = ContentScale.Crop // Adjust content scale if necessary ) } @Composable fun ArtistCardColumnOne() { Column { Text("Noshad Ali", fontSize = 20.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold, modifier = Modifier.padding(16.dp) ) Text("+92 303 0142282", fontSize = 20.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold, modifier = Modifier.padding(16.dp)) } }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/Task02.kt
2854603824
package com.sjh.myapplication 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.sjh.myapplication", appContext.packageName) } }
DataCommunicationAndroidArchitecture/app/src/androidTest/java/com/sjh/myapplication/ExampleInstrumentedTest.kt
3812681622
package com.sjh.myapplication 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) } }
DataCommunicationAndroidArchitecture/app/src/test/java/com/sjh/myapplication/ExampleUnitTest.kt
2815139767
package com.sjh.myapplication import android.app.Application import com.sjh.myapplication.core.util.log.TimberInitializer import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication : Application() { override fun onCreate() { super.onCreate() TimberInitializer.initTimber(BuildConfig.DEBUG) } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/MyApplication.kt
3858529677
package com.sjh.myapplication import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.sjh.myapplication.core.data.utils.NetworkMonitor import com.sjh.myapplication.feature.bluetoothtemp.BlankFragment import com.sjh.myapplication.feature.bluetoothtemp.BlankViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val viewModel: BlankViewModel by viewModels() @Inject lateinit var networkMonitor: NetworkMonitor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel.initLauncher(this) lifecycleScope.launch { networkMonitor.isOnline.collect { isConnected -> if (isConnected) { } else { } } } supportFragmentManager .beginTransaction() .add(R.id.container, BlankFragment(), "first") .commitAllowingStateLoss() // // 블루투스 상태 구독 // subscribeBluetoothState() // // 블루투스 데이터 구독 // subscribeBluetoothData() // // 블루투스 실행 // viewModel.initLauncher(this) } // @SuppressLint("MissingPermission") // private fun subscribeBluetoothState() = lifecycleScope.launch(Dispatchers.IO) { // repeatOnLifecycle(Lifecycle.State.STARTED) { // viewModel.bluetoothState.collect { bluetoothState -> // when (bluetoothState) { // is BluetoothUiState.Activating -> { // bluetoothState.state?.let { // Log.d("whatisthis", it) // } ?: Log.d("whatisthis", "bluetooth is activating") // } // // is BluetoothUiState.Scanning -> { // bluetoothState.device?.let { // Log.d("whatisthis", "${it.name ?: it.address} is scanned") // } ?: Log.d("whatisthis", "bluetooth is scanning") // } // // is BluetoothUiState.Connecting -> { // bluetoothState.device?.let { // Log.d("whatisthis", "${it} is connected") // } ?: Log.d("whatisthis", "bluetooth is connecting") // } // // is BluetoothUiState.DeActivating -> { // Log.d("whatisthis", "bluetooth is deactivating") // } // } // } // } // } // // // private fun subscribeBluetoothData() = lifecycleScope.launch(Dispatchers.IO) { // repeatOnLifecycle(Lifecycle.State.STARTED) { // viewModel.bluetoothData.collect { data -> // Log.d("whatisthis", "data : \n $data") // } // } // } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/MainActivity.kt
1691946424
package com.sjh.myapplication.core.util.log import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger import com.orhanobut.logger.PrettyFormatStrategy import timber.log.Timber /** Default Logger Tag : Logger의 default tag(실제로 나올 일은 없다.) */ const val DEFAULT_LOGGER_TAG = "" /** Default Timber Tag : Timber의 defaault tag */ const val DEFAULT_TIMBER_TAG = "whatisthis" /** * Timber initializer : * Timber 초기화 메서드를 가진 object 클래스 * @constructor Create empty Timber initializer */ object TimberInitializer { fun initTimber(isDebug: Boolean) { // Logger를 커스텀한다. val logFormat = PrettyFormatStrategy.newBuilder().showThreadInfo(true) // 쓰레드 정보 .methodCount(5) // 라인을 몇 개까지 보여줄 지(기본 2줄) .tag(DEFAULT_LOGGER_TAG) // 등록안하면 PRETTY_LOGGER가 default가 된다. (Timber의 tag가 Logger의 default tag에 '-'와 함게 합쳐져서 나온다.) .build() Logger.clearLogAdapters() Logger.addLogAdapter(AndroidLogAdapter(logFormat)) val timberTree = if (isDebug) DebugLogStrategy() else ReleaseLogStrategy() Timber.plant(timberTree) } } /** * Debug log strategy : * Debug 모드일 때 쓰는 log 전략 클래스 * @constructor Create empty Debug log strategy */ class DebugLogStrategy : Timber.DebugTree() { // Timber의 Log 메시지를 Logger로 보여준다. override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { Logger.log(priority, tag, message, t) } // Timber의 tag 메서드를 오버라이드하여 기본 태그를 설정 override fun createStackElementTag(element: StackTraceElement): String? { return DEFAULT_TIMBER_TAG } } /** * Release log strategy : * Release 모드일 때 * @constructor Create empty Release log strategy */ class ReleaseLogStrategy : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { if (priority == android.util.Log.ERROR || priority == android.util.Log.WARN) { //SEND ERROR REPORTS TO YOUR Crashlytics. } } } /** * D log : * 다른 tag를 쓰고 싶을 때 * 예시) "example-tag".dLog("로그") * @param message 로그 내용 */ fun String.dLog(message: String) { Timber.tag(this).d(message) } fun String.eLog(message: String, throwable: Throwable? = null) { if (throwable != null) { Timber.tag(this).e(throwable, message) } else { Timber.tag(this).e(message) } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/util/log/Log.kt
2443431511
package com.sjh.myapplication.core.source.wifi.impl import com.sjh.myapplication.core.source.wifi.WifiDatasource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.onCompletion import timber.log.Timber import java.net.Socket import javax.inject.Inject class WifiDatasourceImpl @Inject constructor() : WifiDatasource { override fun getDataFromPpilot(socket: Socket): Flow<String> { return flow { // 소켓이 연결되지 않은 경우, Flow를 종료 if (!socket.isConnected) { return@flow } // 소켓의 InputStream으로부터 데이터를 읽어옵니다. val reader = socket.getInputStream().bufferedReader() try { var line: String? while (reader.readLine().also { line = it } != null) { emit(line!!) // 읽은 데이터를 Flow에 emit합니다. } } catch (e: Exception) { Timber.d("WifiDatasourceImpl, getDataFromPpilot : ${e}") emit("") } finally { reader.close() // 작업이 완료되면 reader를 닫습니다. } }.flowOn(Dispatchers.IO).onCompletion { cause -> // 예외가 발생하여 Flow가 취소된 경우, 소켓을 닫음 if (cause != null) { socket.close() } } } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/wifi/impl/WifiDatasourceImpl.kt
2246815243
package com.sjh.myapplication.core.source.wifi.di import com.sjh.myapplication.core.source.wifi.WifiDatasource import com.sjh.myapplication.core.source.wifi.impl.WifiDatasourceImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface WifiSocketModule { @Binds fun privdesWifiSocket(impl: WifiDatasourceImpl): WifiDatasource }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/wifi/di/WifiSocketModule.kt
229482091
package com.sjh.myapplication.core.source.wifi.utils import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import com.sjh.myapplication.core.model.PBluetoothDevice
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/wifi/utils/Extension.kt
2532968961
package com.sjh.myapplication.core.source.wifi import kotlinx.coroutines.flow.Flow import java.net.Socket interface WifiDatasource { fun getDataFromPpilot(socket: Socket): Flow<String> }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/wifi/WifiDatasource.kt
2155549667
package com.sjh.myapplication.core.source.database.database import androidx.room.Database import androidx.room.RoomDatabase import com.sjh.myapplication.core.source.database.BluetoothDeviceDao import com.sjh.myapplication.core.source.database.model.BluetoothDeviceEntity @Database( entities = [BluetoothDeviceEntity::class], version = 1, exportSchema = true ) internal abstract class LocalDatabase : RoomDatabase() { abstract fun bluetoothDeviceDao() : BluetoothDeviceDao }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/database/database/LocalDatabase.kt
711636456
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sjh.myapplication.core.source.database.di import com.sjh.myapplication.core.source.database.database.LocalDatabase import com.sjh.myapplication.core.source.database.BluetoothDeviceDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) internal object DaosModule { @Provides fun providesBluetoothDao( localDatabase: LocalDatabase, ): BluetoothDeviceDao = localDatabase.bluetoothDeviceDao() }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/database/di/DaosModule.kt
3645606446
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sjh.myapplication.core.source.database.di import android.content.Context import androidx.room.Room import com.sjh.myapplication.core.source.database.database.LocalDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal object DatabaseModule { @Provides @Singleton fun providesLocalDatabase( @ApplicationContext context: Context, ): LocalDatabase = Room.databaseBuilder( context, LocalDatabase::class.java, "localdatabase.db", ).build() }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/database/di/DatabaseModule.kt
2889496169
package com.sjh.myapplication.core.source.database import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.sjh.myapplication.core.source.database.model.BluetoothDeviceEntity import kotlinx.coroutines.flow.Flow @Dao interface BluetoothDeviceDao { @Insert suspend fun insertDevice(device: BluetoothDeviceEntity) @Delete suspend fun deleteDevice(device: BluetoothDeviceEntity) @Query("SELECT * FROM bluetooth_devices") fun getAllDevices(): Flow<List<BluetoothDeviceEntity>> }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/database/BluetoothDeviceDao.kt
2129189969
package com.sjh.myapplication.core.source.database.model import androidx.room.Entity import androidx.room.PrimaryKey import com.sjh.myapplication.core.model.PBluetoothDevice @Entity(tableName = "bluetooth_devices") data class BluetoothDeviceEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val deviceName: String?, val deviceAddress: String, ) fun BluetoothDeviceEntity.asExternalModel() = PBluetoothDevice( id = id, deviceName = deviceName, deviceAddress = deviceAddress )
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/database/model/BluetoothDeviceEntity.kt
847344256
package com.sjh.myapplication.core.source.bluetoothsocket.impl import android.bluetooth.BluetoothSocket import com.sjh.myapplication.core.source.bluetoothsocket.BluetoothDatasource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.onCompletion import java.io.IOException import javax.inject.Inject class BluetoothDatasourceImpl @Inject constructor() : BluetoothDatasource { override fun getDataFromPpilot(socket: BluetoothSocket): Flow<String> { return flow { // 소켓이 연결되지 않은 경우, Flow를 종료 if (!socket.isConnected) { return@flow } val buffer = ByteArray(1024) try { while (true) { val byteCount = socket.inputStream.read(buffer) // 스트림의 끝에 도달했을 경우, 루프를 종료 if (byteCount == -1) break // 읽은 데이터를 문자열로 변환하여 emit emit(buffer.decodeToString(endIndex = byteCount)) } } catch (e: IOException) { emit("") } finally { // Flow가 종료되면 소켓을 닫음 socket.close() } }.flowOn(Dispatchers.IO).onCompletion { cause -> // 예외가 발생하여 Flow가 취소된 경우, 소켓을 닫음 if (cause != null) { socket.close() } } } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/bluetoothsocket/impl/BluetoothDatasourceImpl.kt
2924088766
package com.sjh.myapplication.core.source.bluetoothsocket import android.bluetooth.BluetoothSocket import kotlinx.coroutines.flow.Flow interface BluetoothDatasource { fun getDataFromPpilot(socket: BluetoothSocket) : Flow<String> }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/bluetoothsocket/BluetoothDatasource.kt
1767355483
package com.sjh.myapplication.core.source.bluetoothsocket.di import com.sjh.myapplication.core.source.bluetoothsocket.BluetoothDatasource import com.sjh.myapplication.core.source.bluetoothsocket.impl.BluetoothDatasourceImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface BluetoothSocketModule { @Binds fun privdesBluetoothSocket(impl : BluetoothDatasourceImpl) : BluetoothDatasource }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/bluetoothsocket/di/BluetoothSocketModule.kt
1359498761
package com.sjh.myapplication.core.source.bluetoothsocket.utils import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import com.sjh.myapplication.core.model.PBluetoothDevice @SuppressLint("MissingPermission") fun BluetoothDevice.asPBluetoothDevice() = PBluetoothDevice( deviceName = this.name, deviceAddress = this.address )
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/source/bluetoothsocket/utils/Extension.kt
3539572281
package com.sjh.myapplication.core.common.result import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart sealed interface DataResult<out T> { data object Loading : DataResult<Nothing> data class Success<T>(val data: T) : DataResult<T> data class Error(val exception: Throwable) : DataResult<Nothing> } fun <T> Flow<T>.asDataResult(): Flow<DataResult<T>> = map<T, DataResult<T>> { DataResult.Success(it) } .onStart { emit(DataResult.Loading) } .catch { emit(DataResult.Error(it)) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/result/DataResult.kt
3719732388
package com.sjh.myapplication.core.common.result import android.bluetooth.BluetoothDevice import com.sjh.myapplication.core.data.model.BluetoothConnectionState import com.sjh.myapplication.core.data.model.BluetoothConnection import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart sealed interface ConnectionResult<out T> { data object Scanning : ConnectionResult<Nothing> // 기기 검색 중 data class Scanned<T>(val device: T) : ConnectionResult<T> // 기기 검색 data object Connecting : ConnectionResult<Nothing> // 기기 연결 중 data class Connected<T>(val device: T) : ConnectionResult<T> // 기기 연결 data class Error(val exception: Throwable?) : ConnectionResult<Nothing> // 예외 발생(연결 끊김 및 에러) } fun Flow<BluetoothConnection>.asConnectionResult(): Flow<ConnectionResult<BluetoothDevice>> = map { connectionState -> when (connectionState.state) { BluetoothConnectionState.ACTIVATING -> ConnectionResult.Scanning BluetoothConnectionState.SCANNING -> { connectionState.connectedDevice?.let { ConnectionResult.Scanned(it) } ?: ConnectionResult.Scanning } BluetoothConnectionState.STOPSCANNING -> ConnectionResult.Error(Exception("stop scanning")) BluetoothConnectionState.CONNECTING -> connectionState.connectedDevice?.let { ConnectionResult.Connected(it) } ?: ConnectionResult.Connecting BluetoothConnectionState.DISCONNECTING -> ConnectionResult.Error(Exception("disconnecting")) BluetoothConnectionState.DEACTIVATING -> ConnectionResult.Error(null) } }.onStart { emit(ConnectionResult.Scanning) } .catch { exception -> emit(ConnectionResult.Error(exception)) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/result/ConnectionResult.kt
3448931222
package com.sjh.myapplication.core.common.utils.extension
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/extension/extension.kt
2856385688
package com.sjh.myapplication.core.common.utils.coroutine.di import com.sjh.myapplication.core.common.utils.coroutine.Dispatcher import com.sjh.myapplication.core.common.utils.coroutine.MapseaDispatchers.Default import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import javax.inject.Qualifier import javax.inject.Singleton @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope @Module @InstallIn(SingletonComponent::class) object CoroutineScopesModule { @Provides @Singleton @ApplicationScope fun providesCoroutineScope( @Dispatcher(Default) dispatcher: CoroutineDispatcher, ): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/coroutine/di/CoroutineScopesModule.kt
1798607611
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sjh.myapplication.core.common.utils.coroutine.di import com.sjh.myapplication.core.common.utils.coroutine.Dispatcher import com.sjh.myapplication.core.common.utils.coroutine.MapseaDispatchers.Default import com.sjh.myapplication.core.common.utils.coroutine.MapseaDispatchers.IO import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @Module @InstallIn(SingletonComponent::class) object DispatchersModule { @Provides @Dispatcher(IO) fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO @Provides @Dispatcher(Default) fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/coroutine/di/DispatchersModule.kt
2027998184
package com.sjh.myapplication.core.common.utils.coroutine import javax.inject.Qualifier import kotlin.annotation.AnnotationRetention.RUNTIME @Qualifier @Retention(RUNTIME) annotation class Dispatcher(val mapseaDispatcher: MapseaDispatchers) enum class MapseaDispatchers { Default, IO, }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/coroutine/MapseaDispatchers.kt
1727594335
package com.sjh.myapplication.core.common.utils.constant import android.Manifest import android.os.Build //const val SERVICE_UUID = "00001101-0000-1000-8000-00805F9B34FB" // //// SDK 버전에 따라 요청할 블루투스 권한을 정의합니다. //val ALL_BLE_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // arrayOf( // Manifest.permission.BLUETOOTH_CONNECT, // Manifest.permission.BLUETOOTH_SCAN, // Manifest.permission.BLUETOOTH_ADVERTISE // 현재 기기를 다른 기기가 스캔하여 찾을 수 있도록함 // ) //} else { // arrayOf( // Manifest.permission.BLUETOOTH_ADMIN, // Manifest.permission.BLUETOOTH, // Manifest.permission.ACCESS_FINE_LOCATION // ) //} // const val PPLUG_BLUETOOTH_NAME = "KSNTEK-BT" // "KSNTEK-BT" // "Galaxy Buds Live (357A)" //const val REQUEST_ALL_PERMISSION = 1
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/constant/Constant.kt
165550003
package com.sjh.myapplication.core.common.utils.helper import android.app.Activity import android.app.PendingIntent import android.bluetooth.BluetoothAdapter import android.content.Intent import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import timber.log.Timber import javax.inject.Inject interface LauncherHelper { fun setRequestPermissionsLauncher( activity: ComponentActivity, accept: () -> Unit, deny: () -> Unit, ): ActivityResultLauncher<Array<String>> fun requestPermissions( requestPermissionLauncher: ActivityResultLauncher<Array<String>>, permissions: Array<String>, ) fun setRequestBluetoothLauncher( activity: ComponentActivity, setResult: (ActivityResult) -> Unit, ): ActivityResultLauncher<Intent> fun requestActivateBluetooth(startForResult: ActivityResultLauncher<Intent>) fun setRequestWifiLauncher( activity: ComponentActivity, setResult: (ActivityResult) -> Unit, ): ActivityResultLauncher<IntentSenderRequest> fun requestActivateWifi( activity: Activity, startForResult: ActivityResultLauncher<IntentSenderRequest>, ) } class LauncherHelperImpl @Inject constructor() : LauncherHelper { override fun setRequestPermissionsLauncher( activity: ComponentActivity, accept: () -> Unit, deny: () -> Unit, ): ActivityResultLauncher<Array<String>> { return activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> if (permissions.all { it.value }) { Timber.d("권한 허용") accept() } else { Timber.d("권한 거절") deny() } } } override fun requestPermissions( requestPermissionLauncher: ActivityResultLauncher<Array<String>>, permissions: Array<String>, ) { requestPermissionLauncher.launch(permissions) } override fun setRequestBluetoothLauncher( activity: ComponentActivity, setResult: (ActivityResult) -> Unit, ): ActivityResultLauncher<Intent> { return activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> Timber.d("블루투스 활성화 요청 결과 : ${result.resultCode}, ${result.data}") setResult(result) } } override fun requestActivateBluetooth(startForResult: ActivityResultLauncher<Intent>) { startForResult.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)) } override fun setRequestWifiLauncher( activity: ComponentActivity, setResult: (ActivityResult) -> Unit, ): ActivityResultLauncher<IntentSenderRequest> { return activity.registerForActivityResult( ActivityResultContracts.StartIntentSenderForResult() ) { result -> Timber.d("와이파이 활성화 요청 결과 : ${result.resultCode}, ${result.data}") setResult(result) } } override fun requestActivateWifi( activity: Activity, startForResult: ActivityResultLauncher<IntentSenderRequest>, ) { val intent = Intent(Settings.ACTION_WIFI_SETTINGS) val pendingIntent = PendingIntent.getActivity( activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val request = IntentSenderRequest.Builder(pendingIntent.intentSender).build() startForResult.launch(request) } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/helper/LauncherHelperImpl.kt
3727318123
package com.sjh.myapplication.core.common.utils.helper.di import com.sjh.myapplication.core.common.utils.helper.LauncherHelper import com.sjh.myapplication.core.common.utils.helper.LauncherHelperImpl import com.sjh.myapplication.core.common.utils.helper.PermissionHelper import com.sjh.myapplication.core.common.utils.helper.PermissionHelperImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface HelperModule { @Binds fun privdesPermission(impl: PermissionHelperImpl): PermissionHelper @Binds fun privdesLauncher(impl: LauncherHelperImpl): LauncherHelper }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/helper/di/HelperModule.kt
193164024
package com.sjh.myapplication.core.common.utils.helper import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Build import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat.requestPermissions import androidx.core.content.ContextCompat import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject interface PermissionHelper { companion object { // SDK 버전에 따라 요청할 블루투스 권한을 정의합니다. val BLUETOOTH_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { arrayOf( Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN ) } else { arrayOf( Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH, Manifest.permission.ACCESS_FINE_LOCATION ) } val WIFI_PERMISSIONS: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // sdk 29 이상 arrayOf( Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION ) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // sdk 23 이상 arrayOf( Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_COARSE_LOCATION ) } else { // sdk 23 미만 arrayOf( Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE ) } const val REQUEST_BLUETOOTH_PERMISSIONS = 1 } fun hasPermission(permission: String): Boolean fun hasPermissions(permissions: Array<String>): Boolean } class PermissionHelperImpl @Inject constructor( @ApplicationContext private val context: Context, ) : PermissionHelper { override fun hasPermission(permission: String): Boolean { return ContextCompat.checkSelfPermission( context, permission ) == PackageManager.PERMISSION_GRANTED } override fun hasPermissions(permissions: Array<String>): Boolean { return permissions.all { ContextCompat.checkSelfPermission( context, it ) == PackageManager.PERMISSION_GRANTED } } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/common/utils/helper/PermissionHelperImpl.kt
129864120
package com.sjh.myapplication.core.model import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice interface PplugDevice { } data class PBluetoothDevice( val id: Long = 0, val deviceName: String?, val deviceAddress: String, ) : PplugDevice data class PWifiDevice( val id: Long = 0, val deviceName: String?, ) : PplugDevice
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/model/PplugDevice.kt
2458686114
package com.sjh.myapplication.core.data.repository.wifi import com.sjh.myapplication.core.model.PBluetoothDevice import kotlinx.coroutines.flow.Flow import java.net.Socket interface WifiRepository { // fun getAllDevices(): Flow<List<PBluetoothDevice>> // suspend fun deleteDevice(device: PBluetoothDevice) // suspend fun insertDevice(device: PBluetoothDevice) fun getWifiData(socket: Socket): Flow<String> }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/repository/wifi/WifiRepository.kt
2774068520
package com.sjh.myapplication.core.data.repository.wifi import com.sjh.myapplication.core.source.wifi.WifiDatasource import kotlinx.coroutines.flow.Flow import java.net.Socket import javax.inject.Inject class WifiRepositoryImpl @Inject constructor( // private val bluetoothDeviceDao: BluetoothDeviceDao, private val wifiDatasource: WifiDatasource, ) : WifiRepository { // override fun getAllDevices(): Flow<List<PBluetoothDevice>> { // return bluetoothDeviceDao.getAllDevices().map { devices -> // devices.map { it.asExternalModel() } // } // } // // override suspend fun deleteDevice(device: PBluetoothDevice) { // bluetoothDeviceDao.deleteDevice( // BluetoothDeviceEntity( // deviceName = device.deviceName, deviceAddress = device.deviceAddress // ) // ) // } // // override suspend fun insertDevice(device: PBluetoothDevice) { // bluetoothDeviceDao.insertDevice( // BluetoothDeviceEntity( // deviceName = device.deviceName, deviceAddress = device.deviceAddress // ), // ) // } override fun getWifiData(socket: Socket): Flow<String> = wifiDatasource.getDataFromPpilot(socket) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/repository/wifi/WifiRepositoryImpl.kt
3904353964
package com.sjh.myapplication.core.data.repository.bluetooth import android.bluetooth.BluetoothSocket import com.sjh.myapplication.core.model.PBluetoothDevice import com.sjh.myapplication.core.source.bluetoothsocket.BluetoothDatasource import com.sjh.myapplication.core.source.database.BluetoothDeviceDao import com.sjh.myapplication.core.source.database.model.BluetoothDeviceEntity import com.sjh.myapplication.core.source.database.model.asExternalModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class BluetoothRepositoryImpl @Inject constructor( private val bluetoothDeviceDao: BluetoothDeviceDao, private val bluetoothDatasource: BluetoothDatasource, ) : BluetoothRepository { override fun getAllDevices(): Flow<List<PBluetoothDevice>> { return bluetoothDeviceDao.getAllDevices().map { devices -> devices.map { it.asExternalModel() } } } override suspend fun deleteDevice(device: PBluetoothDevice) { bluetoothDeviceDao.deleteDevice( BluetoothDeviceEntity( deviceName = device.deviceName, deviceAddress = device.deviceAddress ) ) } override suspend fun insertDevice(device: PBluetoothDevice) { bluetoothDeviceDao.insertDevice( BluetoothDeviceEntity( deviceName = device.deviceName, deviceAddress = device.deviceAddress ), ) } override fun getBluetoothData(socket: BluetoothSocket) = bluetoothDatasource.getDataFromPpilot(socket) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/repository/bluetooth/BluetoothRepositoryImpl.kt
726837443
package com.sjh.myapplication.core.data.repository.bluetooth import android.bluetooth.BluetoothSocket import com.sjh.myapplication.core.model.PBluetoothDevice import kotlinx.coroutines.flow.Flow interface BluetoothRepository { fun getAllDevices(): Flow<List<PBluetoothDevice>> suspend fun deleteDevice(device: PBluetoothDevice) suspend fun insertDevice(device: PBluetoothDevice) fun getBluetoothData(socket: BluetoothSocket) : Flow<String> }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/repository/bluetooth/BluetoothRepository.kt
1254479427
package com.sjh.myapplication.core.data.di import com.sjh.myapplication.core.data.repository.bluetooth.BluetoothRepository import com.sjh.myapplication.core.data.repository.bluetooth.BluetoothRepositoryImpl import com.sjh.myapplication.core.data.repository.wifi.WifiRepository import com.sjh.myapplication.core.data.repository.wifi.WifiRepositoryImpl import com.sjh.myapplication.core.data.utils.BluetoothController import com.sjh.myapplication.core.data.utils.BluetoothControllerImpl import com.sjh.myapplication.core.data.utils.ConnectivityManagerNetworkMonitor import com.sjh.myapplication.core.data.utils.NetworkMonitor import com.sjh.myapplication.core.data.utils.TimeZoneBroadcastMonitor import com.sjh.myapplication.core.data.utils.TimeZoneMonitor import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface DataModule { @Binds fun providesBluetoothData(impl: BluetoothRepositoryImpl): BluetoothRepository @Binds fun proivdesBluetoothController(impl: BluetoothControllerImpl): BluetoothController @Binds fun providesWifiData(impl: WifiRepositoryImpl): WifiRepository @Binds fun privdesNetworkMonitor(impl: ConnectivityManagerNetworkMonitor): NetworkMonitor @Binds fun privdesTimeZoneMonitor(impl: TimeZoneBroadcastMonitor): TimeZoneMonitor }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/di/DataModule.kt
321655513
package com.sjh.myapplication.core.data.utils import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothSocket import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.net.wifi.ScanResult import android.net.wifi.WifiConfiguration import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.net.wifi.WifiNetworkSpecifier import android.os.Build import androidx.core.content.ContextCompat import com.sjh.myapplication.core.common.utils.helper.PermissionHelper import com.sjh.myapplication.core.data.model.WifiConnection import com.sjh.myapplication.core.data.model.WifiConnectionState import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import timber.log.Timber import java.io.IOException import java.net.InetSocketAddress import java.net.Socket import javax.inject.Inject import javax.inject.Singleton import kotlin.coroutines.resumeWithException @Singleton @SuppressLint("MissingPermission") class WifiController @Inject constructor( @ApplicationContext private val context: Context, private val permissionHelper: PermissionHelper, ) { private val wifiManager: WifiManager by lazy { context.getSystemService(Context.WIFI_SERVICE) as WifiManager } val isWifiSupported: Boolean get() = context.packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI) val isWifiGranted: Boolean get() = permissionHelper.hasPermissions(PermissionHelper.WIFI_PERMISSIONS) val isWifiEnabled: Boolean get() { val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager return wifiManager.isWifiEnabled } // 스캔 결과 사용가능한 Wifi 목록 val scanResults: List<ScanResult> = wifiManager.scanResults fun observeWifiState(): Flow<WifiConnection> = callbackFlow { val receiver = WifiStateReceiver { connectionState -> trySend(connectionState) } val filter = IntentFilter().apply { addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) // Wi-Fi 스캔이 완료되었을 때 addAction(WifiManager.WIFI_STATE_CHANGED_ACTION) // Wi-Fi 상태가 변경되었을 때 } context.registerReceiver(receiver, filter) // Flow가 취소될 때 BroadcastReceiver를 해제 awaitClose { context.unregisterReceiver(receiver) } } suspend fun getConnectedWifiInfo(): WifiInfo? = suspendCancellableCoroutine { continuation -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val connectivityManager = ContextCompat.getSystemService( context, ConnectivityManager::class.java ) as ConnectivityManager val request = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build() val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { super.onCapabilitiesChanged(network, networkCapabilities) if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { val wifiInfo = networkCapabilities.transportInfo as? WifiInfo if (wifiInfo != null && !continuation.isCompleted) { connectivityManager.unregisterNetworkCallback(this) continuation.resume(wifiInfo, onCancellation = null) } } } override fun onLost(network: Network) { super.onLost(network) if (!continuation.isCompleted) { connectivityManager.unregisterNetworkCallback(this) continuation.resumeWithException(IOException("WiFi connection lost")) } } } continuation.invokeOnCancellation { if (!continuation.isCompleted) { connectivityManager.unregisterNetworkCallback(networkCallback) } } connectivityManager.registerNetworkCallback(request, networkCallback) } else { // Android 12 미만에서는 WifiManager를 사용 val wifiInfo = wifiManager.connectionInfo if (wifiInfo != null && wifiInfo.networkId != -1) { continuation.resume(wifiInfo, onCancellation = null) } else { continuation.resumeWithException(IOException("Failed to get WiFi info")) } } } fun connectToWifiSocket(ipAddress: String, port: Int): Flow<Socket?> { return flow { var socket: Socket? = null try { socket = connectToDevice(ipAddress, port) if (socket?.isConnected == true) { emit(socket) }else{ // 연결 시도 끝 연결 실패 emit(null) } } catch (e: Exception) { // 연결 시도 중 에러 발생 Timber.e("Could not connect: ${ipAddress} in BluetoothControllerImpl \n reason : ${e}") socket?.close() // Ensure the socket is closed if an exception occurs socket = null emit(socket) } }.flowOn(Dispatchers.IO) } suspend fun connectToDevice(ipAddress: String, port: Int): Socket? { return withContext(Dispatchers.IO) { try { Socket().apply { // 5000ms 타임아웃 설정 connect(InetSocketAddress(ipAddress, port), 5000) } } catch (e: IOException) { throw e } } } fun connectToWifiDevice( ssid: String, password: String, ): Flow<WifiInfo?> = callbackFlow { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder().setSsid(ssid).setWpa2Passphrase(password).build() val networkRequest = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .setNetworkSpecifier(wifiNetworkSpecifier).build() val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { val connectionInfo = wifiManager.connectionInfo trySend(connectionInfo) } override fun onUnavailable() { trySend(null) } } connectivityManager.requestNetwork(networkRequest, networkCallback) awaitClose { connectivityManager.unregisterNetworkCallback(networkCallback) } } else { // Android Q 미만 버전에서의 연결 로직 val wifiConfig = WifiConfiguration().apply { SSID = String.format("\"%s\"", ssid) preSharedKey = String.format("\"%s\"", password) } val netId: Int = wifiManager.addNetwork(wifiConfig) wifiManager.disconnect() wifiManager.enableNetwork(netId, true) val connected = wifiManager.reconnect() if (connected) { val connectionInfo = wifiManager.connectionInfo trySend(connectionInfo) } else { trySend(null) } awaitClose {} } } inner class WifiStateReceiver( private val onStateChanged: (WifiConnection) -> Unit, // 상태 변화 시 호출될 콜백 함수 ) : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { WifiManager.SCAN_RESULTS_AVAILABLE_ACTION -> { // Wi-Fi가 연결된 상태이든, 연결되지 않은 상태이든 관계없이 검색된 Wi-Fi 액세스 포인트들의 정보 val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false) if (success) { // 스캔 결과 처리 -> scanResults는 연결된 네트워크, 이전에 연결되었던(paired) 네트워크, 새로 발견된 네트워크 모두 포함 onStateChanged(WifiConnection(WifiConnectionState.SCANNING, null)) } else { // 스캔 실패 처리 onStateChanged(WifiConnection(WifiConnectionState.STOPSCANNING, null)) } } WifiManager.WIFI_STATE_CHANGED_ACTION -> { val wifiState = intent.getIntExtra( WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN ) when (wifiState) { WifiManager.WIFI_STATE_ENABLING -> { // Wi-Fi가 활성화 중 onStateChanged(WifiConnection(WifiConnectionState.ACTIVATING, null)) } WifiManager.WIFI_STATE_ENABLED -> { // Wi-Fi가 켜졌을 때 -> 자동으로 스캔 및 연결 시도 onStateChanged(WifiConnection(WifiConnectionState.CONNECTING, null)) } WifiManager.WIFI_STATE_DISABLING -> { // Wi-Fi가 비활성화 중 onStateChanged(WifiConnection(WifiConnectionState.DEACTIVATING, null)) } WifiManager.WIFI_STATE_DISABLED -> { // Wi-Fi가 꺼졌을 때 onStateChanged(WifiConnection(WifiConnectionState.DISCONNECTING, null)) } // else -> { // // **기타 상태에 대한 처리** // } } } // 네트워크 연결 상태 변경에 대한 처리는 NetworkInfo.State를 사용하여 별도로 처리합니다. // 예를 들어, ConnectivityManager를 사용하여 네트워크 상태를 확인할 수 있습니다. // Wi-Fi가 연결되었을 때 (NetworkInfo.State.CONNECTED) // Wi-Fi가 연결이 끊어졌을 때 (NetworkInfo.State.DISCONNECTED)" } } } inner class WifiDeviceReceiver( private val onStateChanged: (WifiConnection) -> Unit, // 상태 변화 시 호출될 콜백 함수 ) : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { WifiManager.SCAN_RESULTS_AVAILABLE_ACTION -> { // Wi-Fi가 연결된 상태이든, 연결되지 않은 상태이든 관계없이 검색된 Wi-Fi 액세스 포인트들의 정보 val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false) if (success) { // 스캔 결과 처리 onStateChanged(WifiConnection(WifiConnectionState.SCANNING, null)) } else { // 스캔 실패 처리 onStateChanged(WifiConnection(WifiConnectionState.STOPSCANNING, null)) } } } } } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/utils/WifiController.kt
4177471378
package com.sjh.myapplication.core.data.utils import android.annotation.SuppressLint import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothSocket import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import com.sjh.myapplication.core.common.utils.helper.PermissionHelper import com.sjh.myapplication.core.data.model.BluetoothConnection import com.sjh.myapplication.core.data.model.BluetoothConnectionState import com.sjh.myapplication.core.util.log.dLog import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import timber.log.Timber import java.io.IOException import java.util.UUID import javax.inject.Inject interface BluetoothController { val isBluetoothSupported: Boolean // 블루투스 지원 여부 val isBluetoothGranted: Boolean // 블루투스 권한 여부 val isBluetoothEnabled: Boolean // 블루투스 활성화 여부 val pairedDevices: Set<BluetoothDevice> // 블루투스 페어링 목록 fun startScan() // 블루투스 스캐닝 fun stopScan() // 블루투스 스캐닝 중지 fun searchDevice(deviceName: String): BluetoothDevice? fun checkDevice(deviceName: String, scannedDevice: BluetoothDevice): Boolean fun observeBluetoothDevice(): Flow<BluetoothDevice> fun observeBluetoothState(): Flow<BluetoothConnection> // 블루투스 연결 상태 관찰 fun connectToBluetoothSocket(device: BluetoothDevice): Flow<BluetoothSocket?> } @SuppressLint("MissingPermission") class BluetoothControllerImpl @Inject constructor( @ApplicationContext private val context: Context, private val permissionHelper: PermissionHelper, ) : BluetoothController { companion object { // UUID는 블루투스 기기를 식별하는 고유한 ID입니다. 실제 기기와 맞는 UUID를 사용해야 합니다. private val BLUETOOTH_UUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb") } private val bluetoothManager: BluetoothManager by lazy { context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager } private val bluetoothAdapter: BluetoothAdapter? by lazy { bluetoothManager.adapter } // 블루투스가 지원되는지 확인 override val isBluetoothSupported: Boolean get() = bluetoothAdapter != null // 블루투스 권한이 승인되었는지 override val isBluetoothGranted: Boolean get() = permissionHelper.hasPermissions( PermissionHelper.BLUETOOTH_PERMISSIONS ) // 블루투스가 활성화되어 있는지 확인 override val isBluetoothEnabled: Boolean get() = bluetoothAdapter?.isEnabled == true override val pairedDevices: Set<BluetoothDevice> get() = bluetoothAdapter?.bondedDevices ?: emptySet() override fun connectToBluetoothSocket(device: BluetoothDevice): Flow<BluetoothSocket?> { return flow { stopScan() // val timeoutMillis = 5000L // 타임아웃 시간 설정 (5초) // val socket = withTimeoutOrNull(timeoutMillis) { // try { // device.createRfcommSocketToServiceRecord(BLUETOOTH_UUID).apply { // connect() // } // } catch (e: IOException) { // "whatisthis".dLog(e.toString()) // null // 연결 실패 시 null 반환 // } // } // emit(socket) // 소켓 연결 결과 emit var socket: BluetoothSocket? = null try { socket = connectToDevice(device) // socket = device.createRfcommSocketToServiceRecord(BLUETOOTH_UUID) // val method = device.javaClass.getMethod("createRfcommSocket", Int::class.javaPrimitiveType) // val socket = method.invoke(device, 1) as BluetoothSocket // socket?.connect() if (socket?.isConnected == true) { emit(socket) }else{ emit(null) } } catch (e: Exception) { Timber.e("Could not connect: ${device.name} in BluetoothControllerImpl \n reason : ${e}") socket?.close() // Ensure the socket is closed if an exception occurs socket = null emit(socket) } }.flowOn(Dispatchers.IO) } private suspend fun connectToDevice(device: BluetoothDevice): BluetoothSocket? { return withContext(Dispatchers.IO) { try { device.createRfcommSocketToServiceRecord(BLUETOOTH_UUID).apply { connect() } } catch (e: IOException) { throw e // 연결 실패 시 null 반환 } } } override fun observeBluetoothDevice(): Flow<BluetoothDevice> = callbackFlow { val receiver = BluetoothDeviceReceiver { scannedDevice -> trySend(scannedDevice) } // BroadcastReceiver 등록 val filter = IntentFilter().apply { addAction(BluetoothDevice.ACTION_FOUND) // 블루투스 기기 검색 중에 새로운 기기가 발견될 때 } context.registerReceiver(receiver, filter) // Flow가 취소될 때 BroadcastReceiver를 해제 awaitClose { context.unregisterReceiver(receiver) } }.flowOn(Dispatchers.IO) // BluetoothStateReceiver의 결과를 콜백으로 처리 override fun observeBluetoothState(): Flow<BluetoothConnection> = callbackFlow { val receiver = BluetoothStateReceiver { connectionState -> trySend(connectionState) } // BroadcastReceiver 등록 val filter = IntentFilter().apply { addAction(BluetoothAdapter.ACTION_STATE_CHANGED) // 블루투스가 켜지거나 꺼질 때 발생 addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) // 블루투스 기기 검색이 시작될 때 addAction(BluetoothDevice.ACTION_FOUND) // 블루투스 기기 검색 중에 새로운 기기가 발견될 때 addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) // 블루투스 기기 검색이 완료되었을 때 addAction(BluetoothDevice.ACTION_PAIRING_REQUEST) // 블루투스 기기 연결 시도 중일 때 addAction(BluetoothDevice.ACTION_ACL_CONNECTED) // 블루투스 기기 검색이 완료되었을 때 addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) // 블루투스 기기 연결이 끊어졌을 때 } context.registerReceiver(receiver, filter) // Flow가 취소될 때 BroadcastReceiver를 해제 awaitClose { context.unregisterReceiver(receiver) } } override fun startScan() { bluetoothAdapter?.startDiscovery() } override fun stopScan() { bluetoothAdapter?.cancelDiscovery() } override fun searchDevice(deviceName: String): BluetoothDevice? = pairedDevices.find { it.name == deviceName || it.address == deviceName } override fun checkDevice(deviceName: String, scannedDevice: BluetoothDevice): Boolean = (scannedDevice.name ?: scannedDevice.address) == deviceName // override fun connectToBluetoothSocket(device: BluetoothDevice): Flow<BluetoothSocket?> { // return flow { // stopScan() // var attempt = 0 // val maxAttempts = 3 // var socket: BluetoothSocket? = null // // while (attempt < maxAttempts && socket == null) { // try { // Timber.d("Attempt $attempt to connect to Bluetooth device: ${device.name}") // socket = device.createRfcommSocketToServiceRecord(BLUETOOTH_UUID) // socket?.connect() // if (socket?.isConnected == true) { // Timber.d("Successfully connected on attempt $attempt") // emit(socket) // } else { // Timber.e("Failed to connect on attempt $attempt") // socket = null // } // } catch (e: Exception) { // Timber.e("Exception on attempt $attempt: ${e.message}") // socket?.close() // socket = null // } // attempt++ // if (socket == null && attempt < maxAttempts) { // Timber.d("Waiting before retrying...") // delay(2000) // 2초 동안 대기 // } // } // if (socket == null) { // Timber.e("Failed to connect after $maxAttempts attempts") // emit(null) // } // }.flowOn(Dispatchers.IO) // } // Bluetooth 상태 변화를 수신하는 BroadcastReceiver를 상속받은 클래스 inner class BluetoothStateReceiver( private val onStateChanged: (BluetoothConnection) -> Unit, // 상태 변화 시 호출될 콜백 함수 ) : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // 블루투스 기기 정보 val device = getDevice(intent) when (intent?.action) { // 블루투스가 켜지거나 꺼질 때 발생 BluetoothAdapter.ACTION_STATE_CHANGED -> handleStateChange(intent) // 블루투스 기기 검색이 시작될 때 BluetoothAdapter.ACTION_DISCOVERY_STARTED -> onStateChanged( BluetoothConnection( BluetoothConnectionState.SCANNING, null ) ) // 블루투스 기기 검색 중에 새로운 기기가 발견될 때 BluetoothDevice.ACTION_FOUND -> onStateChanged( BluetoothConnection( BluetoothConnectionState.SCANNING, device ) ) // 블루투스 기기 검색이 완료되었을 때 BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> onStateChanged( BluetoothConnection( BluetoothConnectionState.STOPSCANNING, null ) ) // 블루투스 기기 연결 중 때 BluetoothDevice.ACTION_PAIRING_REQUEST -> onStateChanged( BluetoothConnection( BluetoothConnectionState.CONNECTING, null ) ) // 블루투스 기기 연결되었을 때 BluetoothDevice.ACTION_ACL_CONNECTED -> onStateChanged( BluetoothConnection( BluetoothConnectionState.CONNECTING, device ) ) // 블루투스 기기 연결이 끊어졌을 때 BluetoothDevice.ACTION_ACL_DISCONNECTED -> onStateChanged( BluetoothConnection( BluetoothConnectionState.DISCONNECTING, device ) ) } } private fun handleStateChange(intent: Intent) { val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) when (state) { BluetoothAdapter.STATE_ON -> onStateChanged( BluetoothConnection( BluetoothConnectionState.ACTIVATING, null ) ) BluetoothAdapter.STATE_OFF -> onStateChanged( BluetoothConnection( BluetoothConnectionState.DEACTIVATING, null ) ) } } } // Bluetooth 상태 변화를 수신하는 BroadcastReceiver를 상속받은 클래스 inner class BluetoothDeviceReceiver( private val onDeviceDiscovered: (BluetoothDevice) -> Unit, // 상태 변화 시 호출될 콜백 함수 ) : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // 블루투스 기기 정보 val device = getDevice(intent) when (intent?.action) { // 블루투스 기기 검색 중에 새로운 기기가 발견될 때 BluetoothDevice.ACTION_FOUND -> device?.let { onDeviceDiscovered(it) } } } } private fun getDevice(intent: Intent?) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent?.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java ) } else { intent?.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) } } //override fun startScan() { // if (!hasPermission(Manifest.permission.BLUETOOTH_SCAN)) return // bluetoothAdapter?.startDiscovery() //} // //override fun stopScan() { // if (!hasPermission(Manifest.permission.BLUETOOTH_SCAN)) return // bluetoothAdapter?.cancelDiscovery() //} // override fun searchDevice( // deviceName: String, // device: BluetoothDevice, // ): Flow<BluetoothSocket?> { // return flow { // val deviceInfo = device.name ?: device.address // if (deviceInfo.trim() == deviceName) { // try { // val socket = bluetoothAdapter?.getRemoteDevice(device.address) // ?.createRfcommSocketToServiceRecord(BLUETOOTH_UUID)?.apply { // connect() // 연결 시도 // } // emit(socket) // } catch (e: IOException) { // Log.e("BluetoothController", "Could not connect to device: ${device.name}", e) // emit(null) // } // } else { // emit(null) // } // }.flowOn(Dispatchers.IO) // } // private fun hasPermission(permission: String): Boolean { // return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED // }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/utils/BluetoothController.kt
3049214120
package com.sjh.myapplication.core.data.utils import android.content.Context import android.net.ConnectivityManager import android.net.ConnectivityManager.NetworkCallback import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest.Builder import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.core.content.getSystemService import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import javax.inject.Inject interface NetworkMonitor { val isOnline: Flow<Boolean> // 네트워크 연결 상태 } // 네트워크 연결 상태를 모니터링 class ConnectivityManagerNetworkMonitor @Inject constructor( @ApplicationContext private val context: Context, ) : NetworkMonitor { // 네트워크 연결 상태 반환 override val isOnline: Flow<Boolean> = callbackFlow { val connectivityManager = context.getSystemService<ConnectivityManager>() // ConnectivityManager가 null이면 채널에 false를 보내고 콜백 플로우를 종료 if (connectivityManager == null) { channel.trySend(false) channel.close() return@callbackFlow } // 네트워크 상태 변경 감지 val callback = object : NetworkCallback() { private val networks = mutableSetOf<Network>() // 사용 가능한 네트워크 목록 // 네트워크가 사용 가능해지면 세트에 추가하고 채널에 true를 보냄 override fun onAvailable(network: Network) { val networkCapabilities = connectivityManager.getNetworkCapabilities(network) val isWifi = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true val isCellular = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true val isBluetooth = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) == true if (isWifi) { // WiFi 연결 감지됨 } else if (isCellular) { // LTE 연결 감지됨 } networks += network channel.trySend(true) } // 네트워크 연결이 끊어지면 세트에서 제거하고 채널에 네트워크가 여전히 있는지 여부(true/false)를 보냄 override fun onLost(network: Network) { networks -= network channel.trySend(networks.isNotEmpty()) } } // 인터넷 기능을 가진 네트워크에 대한 요청 생성 val request = Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build() // 네트워크 콜백 등록 connectivityManager.registerNetworkCallback(request, callback) // 현재 연결 상태를 채널에 보냄 channel.trySend(connectivityManager.isCurrentlyConnected()) // 콜백 플로우가 종료될 때 네트워크 콜백을 해제 awaitClose { connectivityManager.unregisterNetworkCallback(callback) } }.conflate() // 연속된 값 중 최신 값만 유지 // 현재 연결 상태를 확인하는 확장 함수 @Suppress("DEPRECATION") private fun ConnectivityManager.isCurrentlyConnected() = when { // 마시멜로우 이상 버전에서는 NetworkCapabilities를 사용하여 인터넷 기능을 확인 VERSION.SDK_INT >= VERSION_CODES.M -> activeNetwork?.let(::getNetworkCapabilities) ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) // 마시멜로우 미만 버전에서는 activeNetworkInfo를 사용하여 연결 상태를 확인 else -> activeNetworkInfo?.isConnected } ?: false // 네트워크 정보가 없으면 false }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/utils/ConnectivityManagerNetworkMonitor.kt
1420453346
package com.sjh.myapplication.core.data.utils import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build.VERSION import android.os.Build.VERSION_CODES import com.sjh.myapplication.core.common.utils.coroutine.Dispatcher import com.sjh.myapplication.core.common.utils.coroutine.MapseaDispatchers.IO import com.sjh.myapplication.core.common.utils.coroutine.di.ApplicationScope import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.shareIn import kotlinx.datetime.TimeZone import kotlinx.datetime.toKotlinTimeZone import java.time.ZoneId import javax.inject.Inject import javax.inject.Singleton /** * Utility for reporting current timezone the device has set. * It always emits at least once with default setting and then for each TZ change. */ interface TimeZoneMonitor { val currentTimeZone: Flow<TimeZone> } @Singleton class TimeZoneBroadcastMonitor @Inject constructor( @ApplicationContext private val context: Context, @ApplicationScope appScope: CoroutineScope, @Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher, ) : TimeZoneMonitor { override val currentTimeZone: SharedFlow<TimeZone> = callbackFlow { // Send the default time zone first. trySend(TimeZone.currentSystemDefault()) // Registers BroadcastReceiver for the TimeZone changes val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != Intent.ACTION_TIMEZONE_CHANGED) return val zoneIdFromIntent = if (VERSION.SDK_INT < VERSION_CODES.R) { null } else { // Starting Android R we also get the new TimeZone. intent.getStringExtra(Intent.EXTRA_TIMEZONE)?.let { timeZoneId -> // We need to convert it from java.util.Timezone to java.time.ZoneId val zoneId = ZoneId.of(timeZoneId, ZoneId.SHORT_IDS) // Convert to kotlinx.datetime.TimeZone zoneId.toKotlinTimeZone() } } // If there isn't a zoneId in the intent, fallback to the systemDefault, which should also reflect the change trySend(zoneIdFromIntent ?: TimeZone.currentSystemDefault()) } } context.registerReceiver(receiver, IntentFilter(Intent.ACTION_TIMEZONE_CHANGED)) // Send here again, because registering the Broadcast Receiver can take up to several milliseconds. // This way, we can reduce the likelihood that a TZ change wouldn't be caught with the Broadcast Receiver. trySend(TimeZone.currentSystemDefault()) awaitClose { context.unregisterReceiver(receiver) } } // We use to prevent multiple emissions of the same type, because we use trySend multiple times. .distinctUntilChanged() .conflate() .flowOn(ioDispatcher) // Sharing the callback to prevent multiple BroadcastReceivers being registered .shareIn(appScope, SharingStarted.WhileSubscribed(5_000), 1) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/utils/TimeZoneMonitor.kt
2016270986
package com.sjh.myapplication.core.data.model import android.bluetooth.BluetoothDevice enum class BluetoothConnectionState { ACTIVATING, // 블루투스 켬 SCANNING, // 스캐닝 중, 스캐닝 중 발견 STOPSCANNING, // 스캐닝 중지 CONNECTING, // 연결 중 DISCONNECTING, // 연결 해제 DEACTIVATING // 블루투스 끔 } data class BluetoothConnection( val state: BluetoothConnectionState, val connectedDevice: BluetoothDevice? )
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/model/BluetoothConnection.kt
1399621969
package com.sjh.myapplication.core.data.model import com.sjh.myapplication.core.model.PBluetoothDevice import com.sjh.myapplication.core.source.database.model.BluetoothDeviceEntity fun PBluetoothDevice.asEntity() = BluetoothDeviceEntity( id = id, deviceName = deviceName, deviceAddress = deviceAddress )
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/model/PplugDevice.kt
2919941148
package com.sjh.myapplication.core.data.model import android.net.wifi.WifiInfo enum class WifiConnectionState { ACTIVATING, // 와이파이 켬 SCANNING, // 스캐닝 중, 스캐닝 중 발견 STOPSCANNING, // 스캐닝 중지 CONNECTING, // 연결 중 DISCONNECTING, // 연결 해제 DEACTIVATING // 와이파이 끔 } data class WifiConnection( val state: WifiConnectionState, val connectedDevice: WifiInfo? )
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/data/model/WifiConnectionState.kt
1387972114
package com.sjh.myapplication.core.domain import com.sjh.myapplication.core.common.result.ConnectionResult import com.sjh.myapplication.core.common.result.asConnectionResult import com.sjh.myapplication.core.data.utils.BluetoothController import com.sjh.myapplication.feature.bluetoothtemp.BluetoothUiState import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class GetBluetoothStateUseCase @Inject constructor( private val bluetoothController: BluetoothController, ) { operator fun invoke(): Flow<BluetoothUiState> = flow { bluetoothController.observeBluetoothState().asConnectionResult() .collect { connectionResult -> emit(when (connectionResult) { is ConnectionResult.Scanning -> BluetoothUiState.Scanning(null) is ConnectionResult.Scanned -> if (bluetoothController.isBluetoothGranted) { BluetoothUiState.Scanning( connectionResult.device.name ?: connectionResult.device.address ) } else BluetoothUiState.Scanning(null) is ConnectionResult.Connecting -> BluetoothUiState.Connecting(null) is ConnectionResult.Connected -> if (bluetoothController.isBluetoothGranted) { BluetoothUiState.Connecting( connectionResult.device.name ?: connectionResult.device.address ) } else BluetoothUiState.Connecting(null) is ConnectionResult.Error -> connectionResult.exception?.let { (BluetoothUiState.Activating( "$it ${it.message}" )) } ?: run { (BluetoothUiState.DeActivating) } }) } } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/domain/GetBluetoothStateUseCase.kt
2912388361
package com.sjh.myapplication.core.domain import android.annotation.SuppressLint import com.sjh.myapplication.core.data.repository.wifi.WifiRepository import com.sjh.myapplication.core.data.utils.WifiController import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.flatMapConcat import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import timber.log.Timber import javax.inject.Inject class GetWifiDataUseCase @Inject constructor( private val wifiController: WifiController, private val wifiRepository: WifiRepository, ) { @SuppressLint("MissingPermission") operator fun invoke(ip: String, port: Int): Flow<String?> = channelFlow { val connectedWifiInfo = wifiController.getConnectedWifiInfo() if (connectedWifiInfo != null) { // 연결된 wifi가 있을 때 Timber.d("wifi is connected, ${connectedWifiInfo.ssid}") // 서버 연결 시도 connectToSocket(ip, port).collect { data -> if (data != null) { send(data) } else { send(null) } } } else { // 연결된 wifi가 없을 때 Timber.d("Device not found, starting scan.") send(null) } } private fun connectToSocket(ip: String, port: Int): Flow<String?> = wifiController.connectToWifiSocket(ip, port).flatMapConcat { socket -> if (socket != null && socket.isConnected) { // 소켓이 성공적으로 연결되었다면, 해당 소켓을 사용하여 데이터를 수집 wifiRepository.getWifiData(socket) } else { Timber.e("Wifi 연결 시도 결과, 연결 안됨") // 소켓 연결에 실패했거나, 연결된 소켓이 없다면 빈 Flow를 반환 flowOf(null) } }.catch { e -> // 연결 또는 데이터 수집 중 발생한 예외 처리 Timber.e("Wifi 연결 시도 중, 연결 실패 ${e.localizedMessage}") emit(null) }.flowOn(Dispatchers.IO) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/domain/GetWifiDataUseCase.kt
3414874623
package com.sjh.myapplication.core.domain import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import com.sjh.myapplication.core.data.repository.bluetooth.BluetoothRepository import com.sjh.myapplication.core.data.utils.BluetoothController import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.flatMapConcat import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import timber.log.Timber import javax.inject.Inject class GetBluetoothDataUseCase @Inject constructor( private val bluetoothController: BluetoothController, private val bluetoothRepository: BluetoothRepository, ) { @SuppressLint("MissingPermission") operator fun invoke(deviceName: String): Flow<String> = channelFlow { val device = bluetoothController.searchDevice(deviceName) if (device != null) { Timber.d("Device is founded, ${device.name}") // 이름이 같은 디바이스가 있다면 연결 connectToSocket(device).collect { data -> send(data) // 데이터를 수집하여 ChannelFlow에 보냄 } } else { // 페어링된 목록에 없다면 바로 스캐닝 Timber.d("Device not found, starting scan.") bluetoothController.startScan() bluetoothController.observeBluetoothDevice().collect { scannedDevice -> Timber.d("scan result : ${scannedDevice.name}") if (scannedDevice.name == deviceName || scannedDevice.address == deviceName) { // 스캔된 디바이스와 이름이 같다면 연결 시도 connectToSocket(scannedDevice).collect { data -> send(data) // 데이터를 수집하여 ChannelFlow에 보냄 } } } } } private fun connectToSocket(device: BluetoothDevice): Flow<String> = bluetoothController.connectToBluetoothSocket(device).flatMapConcat { socket -> if (socket != null && socket.isConnected) { // 소켓이 성공적으로 연결되었다면, 해당 소켓을 사용하여 데이터를 수집 bluetoothRepository.getBluetoothData(socket) } else { // 소켓 연결에 실패했거나, 연결된 소켓이 없다면 빈 Flow를 반환 flowOf("Bluetooth socket connection failed.") } }.catch { e -> // 연결 또는 데이터 수집 중 발생한 예외 처리 emit("Error during Bluetooth data collection: ${e.localizedMessage}") }.flowOn(Dispatchers.IO) }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/core/domain/GetBluetoothDataUseCase.kt
1759983359
package com.sjh.myapplication.feature.bluetoothtemp import com.sjh.myapplication.core.model.PplugDevice sealed interface PplugUiState { data object Loading : PplugUiState data object EmptyQuery : PplugUiState data object LoadFailed : PplugUiState data class Success( val devices: List<PplugDevice> = emptyList(), ) : PplugUiState { fun isEmpty(): Boolean = devices.isEmpty() } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/feature/bluetoothtemp/PplugUiState.kt
2268046597
package com.sjh.myapplication.feature.bluetoothtemp import com.sjh.myapplication.core.model.PplugDevice sealed interface PplugDataUiState { data object Loading : PplugDataUiState data class Success(val data: String?) : PplugDataUiState }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/feature/bluetoothtemp/PplugDataUiState.kt
1189431478
package com.sjh.myapplication.feature.bluetoothtemp /** * BluetoothUiState */ sealed interface BluetoothUiState { /** * 블루투스 켠 상태 */ data class Activating(val state: String?) : BluetoothUiState // 블루투스 검색 중 data class Scanning(val state: String?) : BluetoothUiState // 블루투스 연결 중, 연결 중이거나 연결 실패일 경우 device = null, 연결 성공일 경우에만 device != null data class Connecting(val state: String?) : BluetoothUiState // 블루투스 끈 상태 data object DeActivating : BluetoothUiState }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/feature/bluetoothtemp/BluetoothUiState.kt
1538830272
package com.sjh.myapplication.feature.bluetoothtemp import android.content.Intent import androidx.activity.ComponentActivity import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.IntentSenderRequest import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.sjh.myapplication.core.common.utils.constant.PPLUG_BLUETOOTH_NAME import com.sjh.myapplication.core.common.utils.helper.LauncherHelper import com.sjh.myapplication.core.common.utils.helper.PermissionHelper import com.sjh.myapplication.core.data.model.WifiConnectionState import com.sjh.myapplication.core.data.repository.bluetooth.BluetoothRepository import com.sjh.myapplication.core.data.utils.BluetoothController import com.sjh.myapplication.core.data.utils.WifiController import com.sjh.myapplication.core.domain.GetBluetoothDataUseCase import com.sjh.myapplication.core.domain.GetBluetoothStateUseCase import com.sjh.myapplication.core.domain.GetWifiDataUseCase import com.sjh.myapplication.core.model.PBluetoothDevice import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @HiltViewModel class BlankViewModel @Inject constructor( private val launcherHelper: LauncherHelper, private val getBluetoothDataUseCase: GetBluetoothDataUseCase, private val getBluetoothStateUseCase: GetBluetoothStateUseCase, private val getWifiDataUseCase: GetWifiDataUseCase, private val bluetoothController: BluetoothController, private val bluetoothRepository: BluetoothRepository, private val wifiController: WifiController, ) : ViewModel() { private lateinit var requestBluetoothPermissionLauncher: ActivityResultLauncher<Array<String>> private lateinit var requestBlutoothLauncher: ActivityResultLauncher<Intent> private lateinit var requestWifiPermissionLauncher: ActivityResultLauncher<Array<String>> private lateinit var requestWifiLauncher: ActivityResultLauncher<IntentSenderRequest> private var jobInViewModel: MutableList<Job> = mutableListOf() private var jobForBluetoothConnection: HashMap<String, Job> = hashMapOf() val isBluetoothEnable: Boolean get() = bluetoothController.isBluetoothEnabled val isWifiEnable: Boolean get() = wifiController.isWifiEnabled private val _bluetoothState: MutableStateFlow<BluetoothUiState> = MutableStateFlow(BluetoothUiState.Activating(null)) val bluetoothState: StateFlow<BluetoothUiState> = _bluetoothState.asStateFlow() private val _bluetoothData: MutableStateFlow<String> = MutableStateFlow("") val bluetoothData: StateFlow<String> = _bluetoothData.asStateFlow() private val _wifiState: MutableStateFlow<WifiConnectionState> = MutableStateFlow(WifiConnectionState.ACTIVATING) private val _wifiData: MutableStateFlow<String?> = MutableStateFlow("") val wifiData: StateFlow<String?> = _wifiData.asStateFlow() val wifiState: StateFlow<WifiConnectionState> get() = _wifiState fun initLauncher(activity: ComponentActivity) { // 권한 요청 결과 처리를 위한 Launcher를 설정 requestBluetoothPermissionLauncher = launcherHelper.setRequestPermissionsLauncher(activity, accept = { Timber.d("블루투스 권한 요청 허용. -> 블루투스 활성화 유뮤 : ${if (isBluetoothEnable) "활성화 되어 있음" else "활성화 안되어 있음"}") if (!isBluetoothEnable) launcherHelper.requestActivateBluetooth( requestBlutoothLauncher ) }, deny = { Timber.d("블루투스 권한 요청 거절") }) requestBlutoothLauncher = launcherHelper.setRequestBluetoothLauncher(activity) { activityResult -> if (isBluetoothEnable) { Timber.d("블루투스 활성화 허용 -> 블루투스 검색 및 연결") // // 블루투스 상태 관찰 // getBluetoothState() // // 기기 연결 시도(페어링 기기부터 시도 후 안되면 스캐닝) // fetchBluetoothData(PPLUG_BLUETOOTH_NAME) } else { Timber.d("블루투스 활성화 거절") } } requestWifiPermissionLauncher = launcherHelper.setRequestPermissionsLauncher(activity, accept = { getWifiState() Timber.d("wifi 권한 요청 허용. -> wifi 활성화 유뮤 : ${if (isWifiEnable) "활성화 되어 있음" else "활성화 안되어 있음"}") if (!isWifiEnable) launcherHelper.requestActivateWifi( activity, requestWifiLauncher ) }, deny = { Timber.d("wifi 권한 요청 거절") }) requestWifiLauncher = launcherHelper.setRequestWifiLauncher(activity) { activityResult -> if (isWifiEnable) { Timber.d("wifi 활성화 허용 -> wifi 검색 및 연결") // // 블루투스 상태 관찰 // getWifiState() } else { Timber.d("wifi 활성화 거절") } } } fun connectBluetooth( setOnNotSupported: () -> Unit, setOnNotPermmited: () -> Unit, setOnNotActivated: () -> Unit, ) { when { // 블루투스 지원 확인 !bluetoothController.isBluetoothSupported -> setOnNotSupported() // 블루투스 권한 확인 !bluetoothController.isBluetoothGranted -> { setOnNotPermmited() launcherHelper.requestPermissions( requestBluetoothPermissionLauncher, PermissionHelper.BLUETOOTH_PERMISSIONS ) } // 블루투스 활성화 확인 !bluetoothController.isBluetoothEnabled -> { setOnNotActivated() launcherHelper.requestActivateBluetooth(requestBlutoothLauncher) } else -> { // 블루투스 상태 관찰 getBluetoothState() // 기기 연결 시도(페어링 기기부터 시도 후 안되면 스캐닝) fetchBluetoothData(PPLUG_BLUETOOTH_NAME) } } } private fun getBluetoothState() { val bluetoothState = viewModelScope.launch(Dispatchers.IO) { getBluetoothStateUseCase().collect { state -> _bluetoothState.value = state } } jobInViewModel.add(bluetoothState) } // 특정 장치 이름으로 블루투스 데이터를 수신 fun fetchBluetoothData(deviceName: String) { viewModelScope.launch { getBluetoothDataUseCase(deviceName).collect { data -> // 수신된 데이터로 UI 업데이트 _bluetoothData.value = data } } } fun connectWifi( activity: FragmentActivity, setOnNotSupported: () -> Unit, setOnNotPermmited: () -> Unit, setOnNotActivated: () -> Unit, ) { when { // 와이파이 지원 확인 !wifiController.isWifiSupported -> setOnNotSupported() // 와이파이 권한 확인 !wifiController.isWifiGranted -> { setOnNotPermmited() launcherHelper.requestPermissions( requestWifiPermissionLauncher, PermissionHelper.WIFI_PERMISSIONS ) } // 와이파이 활성화 확인 !isWifiEnable -> { setOnNotActivated() launcherHelper.requestActivateWifi( activity, requestWifiLauncher ) } else -> { Timber.d("와이파이 활성화 되어 있음") // 블루투스 상태 관찰 getWifiState() fetchWifiData("192.168.1.1",8888) // // 기기 연결 시도(페어링 기기부터 시도 후 안되면 스캐닝) // connectToDevice(PPLUG_BLUETOOTH_NAME) } } } fun getWifiState() { val wifiState = viewModelScope.launch(Dispatchers.IO) { wifiController.observeWifiState().collect { connectionResult -> when (connectionResult.state) { WifiConnectionState.ACTIVATING -> { Timber.d(connectionResult.state.toString()) } WifiConnectionState.SCANNING -> { Timber.d(connectionResult.state.toString()) } WifiConnectionState.STOPSCANNING -> { Timber.d(connectionResult.state.toString()) } WifiConnectionState.CONNECTING -> { Timber.d(connectionResult.state.toString()) } WifiConnectionState.DISCONNECTING -> { Timber.d(connectionResult.state.toString()) } WifiConnectionState.DEACTIVATING -> { Timber.d(connectionResult.state.toString()) } } } } } // 특정 장치 이름으로 블루투스 데이터를 수신 fun fetchWifiData(ip: String, port: Int) { viewModelScope.launch { getWifiDataUseCase(ip, port).collect { data -> Timber.d("data : ${data}") // 수신된 데이터로 UI 업데이트 _wifiData.value = data } } } fun disConnectToAllDevice() { jobForBluetoothConnection.mapValues { it.value.cancel() } } fun disConnectToDevice(deviceName: String) { jobForBluetoothConnection.get(deviceName)?.cancel() } ///////////////////////////////////////////////////////////////////////// val pBluetoothDevices: StateFlow<PplugUiState> = bluetoothRepository.getAllDevices().map(PplugUiState::Success).stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = PplugUiState.Loading, ) fun insertPBluetoothDevice(pBluetoothDevice: PBluetoothDevice) { viewModelScope.launch { bluetoothRepository.insertDevice(pBluetoothDevice) } } fun deletePBluetoothDevice(pBluetoothDevice: PBluetoothDevice) { viewModelScope.launch { bluetoothRepository.deleteDevice(pBluetoothDevice) } } override fun onCleared() { requestWifiLauncher.unregister() requestBlutoothLauncher.unregister() bluetoothController.stopScan() jobInViewModel.map { it.cancel() } super.onCleared() } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @SuppressLint("MissingPermission") // fun getBluetoothState() { // val bluetoothState = viewModelScope.launch(Dispatchers.IO) { // bluetoothController.observeBluetoothState().asConnectionResult() // .collect { connectionResult -> // when (connectionResult) { // is ConnectionResult.Scanning -> { // _bluetoothState.value = (BluetoothUiState.Scanning(null)) // } // // is ConnectionResult.Scanned -> { // if (bluetoothController.isBluetoothGranted) { // _bluetoothState.value = (BluetoothUiState.Scanning( // connectionResult.device.name ?: connectionResult.device.address // )) // connectToDevice(PPLUG_BLUETOOTH_NAME, connectionResult.device) // } // } // // is ConnectionResult.Connecting -> { // bluetoothController.stopScan() // _bluetoothState.value = (BluetoothUiState.Connecting(null)) // } // // is ConnectionResult.Connected -> { // if (bluetoothController.isBluetoothGranted) { // _bluetoothState.value = (BluetoothUiState.Connecting( // connectionResult.device.name ?: connectionResult.device.address // )) // } // } // // is ConnectionResult.Error -> { // bluetoothController.stopScan() // // connectionResult.exception?.let { // _bluetoothState.value = // (BluetoothUiState.Activating("$it ${it.message}")) // } ?: run { // _bluetoothState.value = (BluetoothUiState.DeActivating) // } // } // } // } // } // jobInViewModel.add(bluetoothState) // } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @SuppressLint("MissingPermission") // private fun connectToSocket(device: BluetoothDevice) { // domain layer에 추가될 함수 // val connectingSocketJob = viewModelScope.launch(Dispatchers.IO) { // bluetoothController.connectToBluetoothSocket(device).collect { socket -> // if (socket != null) { // bluetoothRepository.getBluetoothData(socket).collect { data -> // _bluetoothData.value = data // } // } else { // Timber.d("Could not connect to device: ${device.name ?: device.address} in BlankViewModel") // } // } // } // jobInViewModel.add(connectingSocketJob) // jobForBluetoothConnection.put(device.name ?: device.address, connectingSocketJob) // } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @SuppressLint("MissingPermission") // fun connectToDevice(deviceName: String) { // val device = bluetoothController.pairedDevices.find { // Timber.d("Paired device ${it.name ?: it.address}") // it.name == deviceName || it.address == deviceName // } // // if (device != null) { // // 이름이 같은 디바이스가 있다면 연결 // connectToSocket(device) // } else { // // 페어링된 목록에 없다면 바로 스캐닝 // Timber.d("Device not found, starting scan.") // bluetoothController.startScan() // } // } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @SuppressLint("MissingPermission") // fun connectToDevice(deviceName: String, device: BluetoothDevice) { // // if (device.name == deviceName || device.address == deviceName) { // bluetoothController.stopScan() // connectToSocket(device) // } // }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/feature/bluetoothtemp/BlankViewModel.kt
3977773637
package com.sjh.myapplication.feature.bluetoothtemp import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.sjh.myapplication.R import com.sjh.myapplication.core.data.model.WifiConnectionState import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import timber.log.Timber @AndroidEntryPoint class BlankFragment : Fragment() { private val viewModel: BlankViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { return inflater.inflate(R.layout.fragment_blank, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) subscribeToStateUpdates() setupButtonListeners(view) } override fun onDestroy() { super.onDestroy() Timber.d("onDestroy") } private fun setupButtonListeners(view: View) { view.findViewById<TextView>(R.id.button).setOnClickListener { viewModel.connectBluetooth( setOnNotSupported = { Timber.d("블루투스 지원 불가") }, setOnNotPermmited = { Timber.d("블루투스 권한 요청해야함") }, setOnNotActivated = { Timber.d("블루투스 실행 요청해야함") }, ) } view.findViewById<TextView>(R.id.button2).setOnClickListener { viewModel.connectWifi( activity = requireActivity(), setOnNotSupported = { Timber.d("와이파이 지원 불가") }, setOnNotPermmited = { Timber.d("와이파이 권한 요청해야함") }, setOnNotActivated = { Timber.d("와이파이 실행 요청해야함") }, ) } } private fun subscribeToStateUpdates() { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { subscribeBluetoothState() } launch { subscribeWifiState() } launch { subscribeBluetoothData() } } } } private suspend fun subscribeBluetoothState() { viewModel.bluetoothState.collect { bluetoothState -> when (bluetoothState) { is BluetoothUiState.Activating -> { bluetoothState.state?.let { Timber.d(it) } ?: Timber.d("bluetooth is activating") } is BluetoothUiState.Scanning -> { bluetoothState.state?.let { Timber.d("${it} is scanned") } ?: Timber.d("bluetooth is scanning") } is BluetoothUiState.Connecting -> { bluetoothState.state?.let { Timber.d("${it} is connected") } ?: Timber.d("bluetooth is connecting") } is BluetoothUiState.DeActivating -> { Timber.d("bluetooth is deactivating") } } } } @SuppressLint("MissingPermission") private suspend fun subscribeWifiState() { viewModel.wifiState.collect { wifiConnectionState -> when (wifiConnectionState) { WifiConnectionState.ACTIVATING -> { Timber.d("wifi ACTIVATING") } WifiConnectionState.SCANNING -> { Timber.d("wifi SCANNING") } WifiConnectionState.STOPSCANNING -> { Timber.d("wifi STOPSCANNING") } WifiConnectionState.CONNECTING -> { Timber.d("wifi CONNECTING") } WifiConnectionState.DISCONNECTING -> { Timber.d("wifi DISCONNECTING") } WifiConnectionState.DEACTIVATING -> { Timber.d("wifi DEACTIVATING") } } } } private suspend fun subscribeBluetoothData() { viewModel.bluetoothData.collect { data -> Timber.d("data : \n $data") } } }
DataCommunicationAndroidArchitecture/app/src/main/java/com/sjh/myapplication/feature/bluetoothtemp/BlankFragment.kt
3001342012
package com.francoisbari.facturefacile 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.francoisbari.facturefacile", appContext.packageName) } }
facturefacile/app/src/androidTest/java/com/francoisbari/facturefacile/ExampleInstrumentedTest.kt
4076311935
package com.francoisbari.facturefacile 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) } }
facturefacile/app/src/test/java/com/francoisbari/facturefacile/ExampleUnitTest.kt
4111419965
package com.francoisbari.facturefacile.ui.contributions import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.francoisbari.facturefacile.CompositionRoot import com.francoisbari.facturefacile.databinding.FragmentContributionsBinding import com.francoisbari.facturefacile.viewmodels.ContributionsViewModel class ContributionsFragment : Fragment() { private val viewModel: ContributionsViewModel by viewModels { CompositionRoot.getContributionsViewModelFactory() } private var _binding: FragmentContributionsBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentContributionsBinding.inflate(inflater, container, false) binding.lifecycleOwner = viewLifecycleOwner binding.viewModel = viewModel return binding.root } companion object { fun newInstance(): ContributionsFragment { return ContributionsFragment() } } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/ui/contributions/ContributionsFragment.kt
4158180365
package com.francoisbari.facturefacile.ui.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.francoisbari.facturefacile.CompositionRoot import com.francoisbari.facturefacile.persistence.DataPersistenceFactory import com.francoisbari.facturefacile.persistence.models.Months import com.francoisbari.facturefacile.databinding.FragmentMainBinding import com.francoisbari.facturefacile.ui.contributions.ContributionsFragment import com.francoisbari.facturefacile.viewmodels.MainViewModel import com.francoisbari.facturefacile.viewmodels.MainViewModelFactory class MainFragment : Fragment() { companion object { fun newInstance() = MainFragment() } private val viewModel: MainViewModel by viewModels { CompositionRoot.getMainViewModelFactory() } private var _binding: FragmentMainBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMainBinding.inflate(inflater, container, false) binding.lifecycleOwner = viewLifecycleOwner binding.viewModel = viewModel viewModel.computeContributionsLiveData.observe(viewLifecycleOwner) { if (it) { // Show the ContributionsFragment val contributionsFragment = ContributionsFragment.newInstance() binding.contributionsCardView.visibility = View.VISIBLE childFragmentManager.beginTransaction().apply { replace(binding.contributionsContainerView.id, contributionsFragment) addToBackStack(null) commit() } } } setupSpinner() return binding.root } private fun setupSpinner() { val months = Months.toArrayList() val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, months) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) binding.monthSpinner.adapter = adapter } override fun onDestroyView() { super.onDestroyView() _binding = null } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/ui/main/MainFragment.kt
3512915710
package com.francoisbari.facturefacile.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.francoisbari.facturefacile.persistence.DataPersistence import com.francoisbari.facturefacile.persistence.UserInputData import com.francoisbari.facturefacile.persistence.models.Months import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MainViewModel(private val dataPersistence: DataPersistence) : ViewModel() { val nbOfDaysLiveData = MutableLiveData<String>() val tjmLiveData = MutableLiveData<String>() val yearlyTotalLiveData = dataPersistence.getYearlyTotalLiveData() private var currentMonth = Months.NONE private val _computeContributionsClicked = MutableLiveData<Boolean>() val computeContributionsLiveData: LiveData<Boolean> = _computeContributionsClicked val totalContributionsLiveData = MutableLiveData<Int>() init { loadData() } fun addOneDayClicked() { val currentDays = nbOfDaysLiveData.value?.toIntOrNull() ?: 0 nbOfDaysLiveData.value = (currentDays + 1).toString() } private fun loadData() { viewModelScope.launch(Dispatchers.IO) { val storedInfos = dataPersistence.loadLatestMonth() ?: return@launch nbOfDaysLiveData.postValue(storedInfos.nbOfDays.toString()) tjmLiveData.postValue(storedInfos.tjm.toString()) currentMonth = Months.fromId(storedInfos.monthId) } } private fun saveData() { val infosToStore = UserInputData( nbOfDays = nbOfDaysLiveData.value?.toIntOrNull() ?: 0, tjm = tjmLiveData.value?.toIntOrNull() ?: 0, monthId = currentMonth.id ) viewModelScope.launch(Dispatchers.IO) { dataPersistence.saveMonth(infosToStore) } } val totalLiveData: LiveData<Int> = MediatorLiveData<Int>().apply { addSource(nbOfDaysLiveData) { value = computeTotal() } addSource(tjmLiveData) { value = computeTotal() } // Save the data each time total is computed. addSource(this) { saveData() } } private fun computeTotal(): Int { val nbOfDays = nbOfDaysLiveData.value?.toIntOrNull() ?: 0 val tjm = tjmLiveData.value?.toIntOrNull() ?: 0 return nbOfDays * tjm } fun computeContributionsClicked() { if (nbOfDaysLiveData.value.isNullOrBlank() || tjmLiveData.value.isNullOrBlank()) return _computeContributionsClicked.value = true val totalEarned = totalLiveData.value ?: 0 val totalContributions = totalEarned * 0.22 // TODO totalContributionsLiveData.value = totalContributions.toInt() } fun selectMonth(month: String) { // Save the data of the current month. val infosToStorePerMonth = UserInputData( nbOfDays = nbOfDaysLiveData.value?.toIntOrNull() ?: 0, tjm = tjmLiveData.value?.toIntOrNull() ?: 0, monthId = currentMonth.id ) viewModelScope.launch(Dispatchers.IO) { dataPersistence.saveMonth(infosToStorePerMonth) } // Get the data from the selected month. currentMonth = Months.fromString(month) viewModelScope.launch(Dispatchers.IO) { val storedInfosPerMonth = dataPersistence.getDataFromMonth(currentMonth.id) ?: return@launch nbOfDaysLiveData.postValue(storedInfosPerMonth.nbOfDays.toString()) tjmLiveData.postValue(storedInfosPerMonth.tjm.toString()) } } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/viewmodels/MainViewModel.kt
3179865780
package com.francoisbari.facturefacile.viewmodels import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.map import androidx.lifecycle.viewModelScope import com.francoisbari.facturefacile.persistence.DataPersistence import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ContributionsViewModel( private val contributionsCalculator: ContributionCalculator, private val dataPersistence: DataPersistence ) : ViewModel() { val isLoading = MutableLiveData<Boolean>() private val _totalContributionsLiveData = MediatorLiveData<Int?>() val totalContributionsLiveData = _totalContributionsLiveData.map { it ?: 0 } init { _totalContributionsLiveData.addSource(dataPersistence.getYearlyTotalLiveData()) { if (it >= 0) { computeContributions(it) } else { _totalContributionsLiveData.value = null } } } private fun computeContributions(totalAmountEarned: Int) { viewModelScope.launch(Dispatchers.IO) { isLoading.postValue(true) val totalAmount = contributionsCalculator.getContributions(totalAmountEarned) _totalContributionsLiveData.postValue(totalAmount) isLoading.postValue(false) } } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/viewmodels/ContributionsViewModel.kt
1194165829
package com.francoisbari.facturefacile.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.francoisbari.facturefacile.persistence.DataPersistence class MainViewModelFactory(private val dataPersistence: DataPersistence) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) return MainViewModel(dataPersistence) as T throw IllegalArgumentException("Unknown ViewModel class") } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/viewmodels/MainViewModelFactory.kt
3420417955
package com.francoisbari.facturefacile.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.francoisbari.facturefacile.persistence.DataPersistence class ContributionsViewModelFactory( private val dataPersistence: DataPersistence, private val contributionsCalculator: ContributionCalculator ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(ContributionsViewModel::class.java)) return ContributionsViewModel(contributionsCalculator, dataPersistence) as T throw IllegalArgumentException("Unknown ViewModel class") } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/viewmodels/ContributionsViewModelFactory.kt
1783204215
package com.francoisbari.facturefacile.viewmodels interface ContributionCalculator { suspend fun getContributions(totalAmountEarned: Int): Int }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/viewmodels/ContributionCalculator.kt
3385362223
package com.francoisbari.facturefacile import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.francoisbari.facturefacile.ui.main.MainFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.container, MainFragment.newInstance()) .commitNow() } } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/MainActivity.kt
2917101450
package com.francoisbari.facturefacile import android.annotation.SuppressLint import android.content.Context import androidx.lifecycle.ViewModelProvider import com.francoisbari.facturefacile.persistence.DataPersistence import com.francoisbari.facturefacile.persistence.DataPersistenceFactory import com.francoisbari.facturefacile.remote.UrssafConnector import com.francoisbari.facturefacile.viewmodels.ContributionCalculator import com.francoisbari.facturefacile.viewmodels.ContributionsViewModelFactory import com.francoisbari.facturefacile.viewmodels.MainViewModelFactory @SuppressLint("StaticFieldLeak") object CompositionRoot { private lateinit var context: Context private val dataPersistence: DataPersistence by lazy { DataPersistenceFactory.create( context, DataPersistenceFactory.DataPersistenceType.ROOM ) } private val contributionsCalculator: ContributionCalculator by lazy { UrssafConnector() } fun init(context: Context) { this.context = context } fun getMainViewModelFactory(): ViewModelProvider.Factory { return MainViewModelFactory(dataPersistence) } fun getContributionsViewModelFactory(): ViewModelProvider.Factory { return ContributionsViewModelFactory(dataPersistence, contributionsCalculator) } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/CompositionRoot.kt
2516577583
package com.francoisbari.facturefacile import android.app.Application class ApplicationClass : Application() { override fun onCreate() { super.onCreate() CompositionRoot.init(this) } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/ApplicationClass.kt
856943325
package com.francoisbari.facturefacile.persistence import com.francoisbari.facturefacile.persistence.models.Months data class UserInputData(var nbOfDays: Int = 0, var tjm: Int = 0, var monthId: Int = Months.NONE.id)
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/UserInputData.kt
3429011780
package com.francoisbari.facturefacile.persistence.room import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update @Dao interface RoomDataDao { @Query("SELECT * FROM UserInputEntity ORDER BY monthId DESC LIMIT 1") fun loadLatestMonth(): UserInputEntity? @Insert(onConflict = OnConflictStrategy.IGNORE) fun saveData(userInputEntity: UserInputEntity): Long @Query("SELECT * FROM UserInputEntity WHERE monthId = :monthId LIMIT 1") fun getDataFromMonth(monthId: Int): UserInputEntity? @Update fun updateData(userInputEntity: UserInputEntity) @Query("SELECT SUM(tjm * nbOfDays) FROM UserInputEntity") fun getYearlyTotal(): LiveData<Int> }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/room/RoomDataDao.kt
540711075
package com.francoisbari.facturefacile.persistence.room import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.francoisbari.facturefacile.persistence.UserInputData @Entity data class UserInputEntity( @PrimaryKey(autoGenerate = true) val uid: Int = 0, val nbOfDays: Int, val tjm: Int, @ColumnInfo(index = true) val monthId: Int ) fun UserInputEntity.toData() = UserInputData(nbOfDays, tjm, monthId) fun UserInputData.toEntity() = UserInputEntity(nbOfDays = nbOfDays, tjm = tjm, monthId = monthId)
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/room/UserInputEntity.kt
1486529242
package com.francoisbari.facturefacile.persistence.room import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [UserInputEntity::class], version = 2) abstract class AppDatabase : RoomDatabase() { abstract fun userInputDao(): RoomDataDao }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/room/AppDatabase.kt
2358417875
package com.francoisbari.facturefacile.persistence.room import android.content.Context import androidx.lifecycle.LiveData import androidx.room.Room import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.francoisbari.facturefacile.persistence.DataPersistence import com.francoisbari.facturefacile.persistence.UserInputData class RoomDataPersistence(context: Context) : DataPersistence { private val database = Room .databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) .addMigrations(MIGRATION_1_2) .build() object MIGRATION_1_2 : Migration(1, 2) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE UserInputEntity ADD COLUMN monthId INTEGER NOT NULL DEFAULT 0") } } override suspend fun loadLatestMonth(): UserInputData { val userInputEntity = database.userInputDao().loadLatestMonth() ?: return UserInputData() return userInputEntity.toData() } override suspend fun saveMonth(userInputDataPerMonth: UserInputData) { val userInputFromMonth = database.userInputDao().getDataFromMonth(userInputDataPerMonth.monthId) if (userInputFromMonth != null) { val updatedEntity = userInputFromMonth.copy( nbOfDays = userInputDataPerMonth.nbOfDays, tjm = userInputDataPerMonth.tjm ) database.userInputDao().updateData(updatedEntity) } else { database.userInputDao().saveData(userInputDataPerMonth.toEntity()) } } override suspend fun getDataFromMonth(monthId: Int): UserInputData { val userInputEntity = database.userInputDao().getDataFromMonth(monthId) ?: return UserInputData() return userInputEntity.toData() } override fun getYearlyTotalLiveData(): LiveData<Int> { return database.userInputDao().getYearlyTotal() } companion object { private const val DATABASE_NAME = "RoomDataPersistence" } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/room/RoomDataPersistence.kt
172353000
package com.francoisbari.facturefacile.persistence.firestore import android.util.Log import androidx.lifecycle.LiveData import com.francoisbari.facturefacile.persistence.DataPersistence import com.francoisbari.facturefacile.persistence.UserInputData import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.toObject import kotlinx.coroutines.tasks.await class FirestoreDataPersistence(private val db: FirebaseFirestore) : DataPersistence { override suspend fun loadLatestMonth(): UserInputData { Log.d(TAG, "loadData: ") val documentSnapshot = db.collection("userInput").document("FBa").get().await() return documentSnapshot.toObject<UserInputData>() ?: UserInputData() } override suspend fun saveMonth(userInputDataPerMonth: UserInputData) { db.collection("userInput").document("FBa").set(userInputDataPerMonth).await() } override suspend fun getDataFromMonth(monthId: Int): UserInputData { TODO("Not yet implemented") } override fun getYearlyTotalLiveData(): LiveData<Int> { TODO("Not yet implemented") } companion object { private const val TAG = "FirestoreDataPersistenc" } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/firestore/FirestoreDataPersistence.kt
3182253970
package com.francoisbari.facturefacile.persistence.models enum class Months(val id: Int, val stringValue: String) { JANUARY(1, "Janvier"), FEBRUARY(2, "Février"), MARCH(3, "Mars"), APRIL(4, "Avril"), MAY(5, "Mai"), JUNE(6, "Juin"), JULY(7, "Juillet"), AUGUST(8, "Août"), SEPTEMBER(9, "Septembre"), OCTOBER(10, "Octobre"), NOVEMBER(11, "Novembre"), DECEMBER(12, "Décembre"), NONE(0, "None"); companion object { fun toArrayList(): Array<String> { // returns the string value of the Month to an array. return entries.map { it.stringValue } .filter { it != NONE.stringValue } .toTypedArray() } fun fromId(monthId: Int): Months { // returns the month with id as input. return when (monthId) { JANUARY.id -> JANUARY FEBRUARY.id -> FEBRUARY MARCH.id -> MARCH APRIL.id -> APRIL MAY.id -> MAY JUNE.id -> JUNE JULY.id -> JULY AUGUST.id -> AUGUST SEPTEMBER.id -> SEPTEMBER OCTOBER.id -> OCTOBER NOVEMBER.id -> NOVEMBER DECEMBER.id -> DECEMBER else -> NONE } } fun fromString(month: String): Months { // returns the month with stringValue as input. return when (month) { JANUARY.stringValue -> JANUARY FEBRUARY.stringValue -> FEBRUARY MARCH.stringValue -> MARCH APRIL.stringValue -> APRIL MAY.stringValue -> MAY JUNE.stringValue -> JUNE JULY.stringValue -> JULY AUGUST.stringValue -> AUGUST SEPTEMBER.stringValue -> SEPTEMBER OCTOBER.stringValue -> OCTOBER NOVEMBER.stringValue -> NOVEMBER DECEMBER.stringValue -> DECEMBER else -> NONE } } } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/models/Months.kt
3123255256
package com.francoisbari.facturefacile.persistence.sharedprefs import android.content.Context import androidx.lifecycle.LiveData import com.francoisbari.facturefacile.persistence.DataPersistence import com.francoisbari.facturefacile.persistence.UserInputData class SharedPreferencesDataPersistence(private val context: Context) : DataPersistence { companion object { private const val PREFS_NAME = "com.francoisbari.facturefacile.data.sharedprefs" private const val PREFS_KEY_NB_OF_DAYS = "nb_of_days" private const val PREFS_KEY_TJM = "tjm" } override suspend fun loadLatestMonth(): UserInputData { val sharedPref = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) val nbOfDays = sharedPref.getInt(PREFS_KEY_NB_OF_DAYS, 0) val tjm = sharedPref.getInt(PREFS_KEY_TJM, 0) return UserInputData(nbOfDays, tjm) } override suspend fun saveMonth(userInputDataPerMonth: UserInputData) { val sharedPref = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) with(sharedPref.edit()) { putInt(PREFS_KEY_NB_OF_DAYS, userInputDataPerMonth.nbOfDays) putInt(PREFS_KEY_TJM, userInputDataPerMonth.tjm) apply() } } override suspend fun getDataFromMonth(monthId: Int): UserInputData { TODO("Not yet implemented") } override fun getYearlyTotalLiveData(): LiveData<Int> { TODO("Not yet implemented") } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/sharedprefs/SharedPreferencesDataPersistence.kt
859907589
package com.francoisbari.facturefacile.persistence import androidx.lifecycle.LiveData interface DataPersistence { suspend fun loadLatestMonth(): UserInputData? suspend fun saveMonth(userInputDataPerMonth: UserInputData) suspend fun getDataFromMonth(monthId: Int): UserInputData? fun getYearlyTotalLiveData(): LiveData<Int> }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/DataPersistence.kt
3279942913
package com.francoisbari.facturefacile.persistence import android.content.Context import com.francoisbari.facturefacile.persistence.firestore.FirestoreDataPersistence import com.francoisbari.facturefacile.persistence.room.RoomDataPersistence import com.francoisbari.facturefacile.persistence.sharedprefs.SharedPreferencesDataPersistence import com.google.firebase.Firebase import com.google.firebase.firestore.firestore class DataPersistenceFactory { companion object { fun create(context: Context, type: DataPersistenceType): DataPersistence { return when (type) { DataPersistenceType.SHARED_PREFERENCES -> SharedPreferencesDataPersistence(context) DataPersistenceType.ROOM -> RoomDataPersistence(context) DataPersistenceType.FIRESTORE -> FirestoreDataPersistence(Firebase.firestore) } } } enum class DataPersistenceType { SHARED_PREFERENCES, ROOM, FIRESTORE } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/persistence/DataPersistenceFactory.kt
2622369399
package com.francoisbari.facturefacile.remote.unsafeokhttpclient import android.annotation.SuppressLint import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager object UnsafeOkHttpClient { private val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager { @SuppressLint("TrustAllX509TrustManager") override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { } @SuppressLint("TrustAllX509TrustManager") override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { } override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } }) private val unsafeSslContext = SSLContext.getInstance("SSL") .apply { init(null, trustAllCerts, java.security.SecureRandom()) } private val interceptor = okhttp3.logging.HttpLoggingInterceptor().apply { level = okhttp3.logging.HttpLoggingInterceptor.Level.BODY } fun getUnsafeOkHttpClient(): okhttp3.OkHttpClient { return okhttp3.OkHttpClient.Builder() .sslSocketFactory( unsafeSslContext.socketFactory, trustAllCerts[0] as X509TrustManager ) .addInterceptor(interceptor) .hostnameVerifier { _, _ -> true } .build() } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/remote/unsafeokhttpclient/UnsafeOkHttpClient.kt
1884153265
package com.francoisbari.facturefacile.remote import com.francoisbari.facturefacile.remote.models.Expression import com.francoisbari.facturefacile.remote.models.MonEntrepriseApi import com.francoisbari.facturefacile.remote.models.PostRequestBody import com.francoisbari.facturefacile.remote.models.Situation import com.francoisbari.facturefacile.remote.unsafeokhttpclient.UnsafeOkHttpClient import com.francoisbari.facturefacile.viewmodels.ContributionCalculator import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class UrssafConnector : ContributionCalculator { override suspend fun getContributions(totalAmountEarned: Int): Int { val requestBody = PostRequestBody( situation = Situation( imposition = "IR", chiffreAffaires = totalAmountEarned, charges = 0, activiteNatureLiberaleReglementee = "non", activiteNature = "'libérale'", associes = "'unique'", categorieJuridique = "'SARL'" ), expressions = listOf( Expression( valeur = "dirigeant . indépendant . cotisations et contributions", unite = "€/an" ) ) ) val response = getRetrofitInstance().evaluate(requestBody) // The response is a list of Evaluate objects, order corresponds to the one sent. return response.evaluate.first().nodeValue } private fun getRetrofitInstance(): MonEntrepriseApi { // Todo stop using unsafeOkHttpClient as soon as issue with SSL certificate is resolved // https://stackoverflow.com/questions/6825226/trust-anchor-not-found-for-android-ssl-connection return Retrofit.Builder() .baseUrl(URSSAF_API_URL) .client(UnsafeOkHttpClient.getUnsafeOkHttpClient()) .addConverterFactory(MoshiConverterFactory.create()) .build() .create(MonEntrepriseApi::class.java) } companion object { private const val URSSAF_API_URL = "https://mon-entreprise.urssaf.fr" } }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/remote/UrssafConnector.kt
4116944392
package com.francoisbari.facturefacile.remote.models import retrofit2.http.Body import retrofit2.http.Headers import retrofit2.http.POST internal interface MonEntrepriseApi { @Headers("Content-Type: application/json") @POST("api/v1/evaluate") suspend fun evaluate(@Body body: PostRequestBody): ResponseData }
facturefacile/app/src/main/java/com/francoisbari/facturefacile/remote/models/MonEntrepriseApi.kt
746137210
package com.francoisbari.facturefacile.remote.models internal data class ResponseData( val responseCachedAt: Long, val cacheExpiresAt: Long, val evaluate: List<Evaluate>, val warnings: List<Warning> ) internal data class Evaluate( val nodeValue: Int, val unit: Unit, val missingVariables: Map<String, Int> ) internal data class Unit( val numerators: List<String>, val denominators: List<String> ) internal data class Warning( val message: String )
facturefacile/app/src/main/java/com/francoisbari/facturefacile/remote/models/PostResponseData.kt
1806143435
package com.francoisbari.facturefacile.remote.models import com.squareup.moshi.Json internal data class PostRequestBody( @field:Json(name = "situation") val situation: Situation, @field:Json(name = "expressions") val expressions: List<Expression> ) internal data class Situation( @field:Json(name = "entreprise . imposition") val imposition: String, @field:Json(name = "entreprise . chiffre d'affaires") var chiffreAffaires: Int, // This field is mutable @field:Json(name = "entreprise . charges") val charges: Int, @field:Json(name = "entreprise . activité . nature . libérale . réglementée") val activiteNatureLiberaleReglementee: String, @field:Json(name = "entreprise . activité . nature") val activiteNature: String, @field:Json(name = "entreprise . associés") val associes: String, @field:Json(name = "entreprise . catégorie juridique") val categorieJuridique: String ) internal data class Expression( @field:Json(name = "valeur") val valeur: String, @field:Json(name = "unité") val unite: String )
facturefacile/app/src/main/java/com/francoisbari/facturefacile/remote/models/PostRequestBody.kt
2984676611
package com.blundell.devpost.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)
AndroidGeminiApiOCR/app/src/main/java/com/blundell/devpost/ui/theme/Color.kt
3443595974
package com.blundell.devpost.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 BlundellTheme( 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 ) }
AndroidGeminiApiOCR/app/src/main/java/com/blundell/devpost/ui/theme/Theme.kt
3509608998
package com.blundell.devpost.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 ) */ )
AndroidGeminiApiOCR/app/src/main/java/com/blundell/devpost/ui/theme/Type.kt
1151694870
package com.blundell.devpost import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import com.blundell.devpost.ui.theme.BlundellTheme import com.google.ai.client.generativeai.GenerativeModel import com.google.ai.client.generativeai.type.ResponseStoppedException import com.google.ai.client.generativeai.type.ServerException import com.google.ai.client.generativeai.type.content import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch private val modelName = listOf( "gemini-pro", "gemini-pro-vision", ) class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BlundellTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, ) { Text("Gemini Android") Image( painterResource(id = R.drawable.image), contentDescription = "", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth(), ) var answer by remember { mutableStateOf("") } Button(onClick = { answer = "loading..." CoroutineScope( context = Dispatchers.IO + CoroutineExceptionHandler { _, throwable -> throwable.printStackTrace() }, ).launch { answer = analyseImage( image = BitmapFactory.decodeResource(resources, R.drawable.image), question = "Extract the " + "power consumption (in watts), " + "temperature (in degrees celsius) " + "and relative humidity (RH %) from the image. " + "Answer with a JSON object." ) } }) { Text(text = "Analyse with Gemini") } Text( text = answer, ) } } } } } private suspend fun analyseImage(image: Bitmap, question: String): String { val generativeModel = GenerativeModel( modelName = modelName[1], apiKey = BuildConfig.apiKey, ) val inputContent = content { image(image) text(question) } Log.d("TUT", "Generating content") try { val response = generativeModel.generateContent(inputContent) Log.e("TUT", "${response.text}") return response.text ?: "No answer." } catch (e: ResponseStoppedException) { Log.e("TUT", "Caught 'A request was stopped during generation for some reason.'", e) return "Error ${e.message}" } catch (e: ServerException) { Log.e("TUT", "Caught 'The server responded with a non 200 response code.'", e) return "Error ${e.message}" } catch (e: Exception) { Log.e("TUT", "Caught 'General Exception'", e) throw e } } }
AndroidGeminiApiOCR/app/src/main/java/com/blundell/devpost/MainActivity.kt
4188160575
package com.example.finalproject 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.finalproject", appContext.packageName) } }
CS374Final/Project/app/src/androidTest/java/com/example/finalproject/ExampleInstrumentedTest.kt
2444704717
package com.example.finalproject 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) } }
CS374Final/Project/app/src/test/java/com/example/finalproject/ExampleUnitTest.kt
2444994732
package com.example.finalproject import android.os.Bundle import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import android.view.Menu import android.view.MenuItem import com.example.finalproject.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) val navController = findNavController(R.id.nav_host_fragment_content_main) appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
CS374Final/Project/app/src/main/java/com/example/finalproject/MainActivity.kt
1080482010
package com.example.finalproject import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.finalproject.databinding.FragmentFirstBinding /** * A simple [Fragment] subclass as the default destination in the navigation. */ class FirstFragment : Fragment() { private var _binding: FragmentFirstBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFirstBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonFirst.setOnClickListener { findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment) } binding.buttonFourth.setOnClickListener { findNavController().navigate(R.id.action_FirstFragment_to_ScrollingFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
CS374Final/Project/app/src/main/java/com/example/finalproject/FirstFragment.kt
2893269233
package com.example.finalproject import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.finalproject.databinding.FragmentDiscountBinding import com.example.finalproject.databinding.FragmentSecondBinding /** * A simple [Fragment] subclass as the second destination in the navigation. */ class ScrollingFragment : Fragment() { private var _binding: FragmentDiscountBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDiscountBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.button1.setOnClickListener { findNavController().navigate(R.id.action_ScrollingFragment_to_FirstFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
CS374Final/Project/app/src/main/java/com/example/finalproject/ScrollingFragment.kt
248456824
package com.example.finalproject import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.finalproject.databinding.FragmentSecondBinding /** * A simple [Fragment] subclass as the second destination in the navigation. */ class SecondFragment : Fragment() { private var _binding: FragmentSecondBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSecondBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonSecond.setOnClickListener { findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
CS374Final/Project/app/src/main/java/com/example/finalproject/SecondFragment.kt
2470058987
package app.sanao1006.tsundoku import org.junit.Assert.assertEquals import org.junit.Test /** * 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) } }
Tsundoku/app/src/test/java/app/sanao1006/tsundoku/ExampleUnitTest.kt
282981028
package app.sanao1006.tsundoku import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import app.sanao1006.tsundoku.data.desiginsystem.TsundokuTheme import app.sanao1006.tsundoku.data.model.InputForCreateTsundoku import app.sanao1006.tsundoku.feature.create.TsundokuCreateScreen import app.sanao1006.tsundoku.feature.create.TsundokuCreateViewModel import app.sanao1006.tsundoku.feature.detail.TsundokuDetailScreen import app.sanao1006.tsundoku.feature.detail.TsundokuDetailScreenViewModel import app.sanao1006.tsundoku.feature.mainscreen.TsundokuScreen import app.sanao1006.tsundoku.feature.mainscreen.TsundokuScreenViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TsundokuTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { TsundokuApp() } } } } } @Composable private fun TsundokuApp( tsundokuScreenViewModel: TsundokuScreenViewModel = hiltViewModel(), tsundokuCreateViewModel: TsundokuCreateViewModel = hiltViewModel(), tsundokuDetailScreenViewModel: TsundokuDetailScreenViewModel = hiltViewModel() ) { val navController = rememberNavController() NavHost(navController = navController, startDestination = "tsundokus") { composable(route = "tsundokus") { TsundokuScreen( viewModel = tsundokuScreenViewModel, onFabClick = { navController.navigate("create") }, onItemClick = { navController.navigate("books/$it") } ) } composable( route = "books/{book_id}", arguments = listOf( navArgument("book_id") { type = NavType.IntType } ) ) { entry -> val bookId = entry.arguments?.getInt("book_id") tsundokuDetailScreenViewModel.getBook(bookId!!) val tsundoku by tsundokuDetailScreenViewModel.book.collectAsState() TsundokuDetailScreen( book = tsundoku, onBackButtonClick = { navController.popBackStack() } ) } composable("create") { val title by tsundokuCreateViewModel.title.collectAsState() val description by tsundokuCreateViewModel.description.collectAsState() val totalPage by tsundokuCreateViewModel.totalPage.collectAsState() TsundokuCreateScreen( input = InputForCreateTsundoku( title = title, description = description, totalPage = totalPage, ), onBackButtonClick = { navController.popBackStack() }, onTitleValueChange = tsundokuCreateViewModel::onTitleValueChange, onDescriptionValueChange = tsundokuCreateViewModel::onDescriptionValueChange, onTotalPageValueChange = tsundokuCreateViewModel::onTotalPageValueChange, onCreateButtonClick = { tsundokuCreateViewModel.insertTsundoku() navController.popBackStack() } ) } } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/MainActivity.kt
3464363035
package app.sanao1006.tsundoku import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class TsundokuApplication : Application()
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/TsundokuApplication.kt
2151818922
package app.sanao1006.tsundoku.feature.mainscreen import androidx.compose.foundation.layout.Column import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun TsundokuInfo( title: String, description: String, modifier: Modifier, horizontalAlignment: Alignment.Horizontal = Alignment.Start ) { Column(modifier = modifier, horizontalAlignment = horizontalAlignment) { Text( text = title, style = MaterialTheme.typography.h6 ) if (!description.isNullOrBlank()) { Text( text = description, style = MaterialTheme.typography.body2 ) } } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/mainscreen/TsundokuInfo.kt
3329878852
package app.sanao1006.tsundoku.feature.mainscreen import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material.Card import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.MenuBook import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import app.sanao1006.tsundoku.data.model.Book @Composable fun TsundokuItem( book: Book, onDeleteButtonClick: () -> Unit, onItemClick: (id: Int) -> Unit ) { Card( elevation = 4.dp, modifier = Modifier .padding(8.dp) .clickable { onItemClick(book.id) } ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(8.dp) ) { TsundokuIcon(Icons.Default.MenuBook, Modifier.weight(0.15f)) TsundokuInfo( truncateString(book.title, maxLength = 23), truncateString(book.description), Modifier.weight(0.7f) ) TsundokuIcon( icon = Icons.Default.Delete, onIconClick = onDeleteButtonClick, modifier = Modifier.weight(0.15f) ) } } } @Composable fun TsundokuIcon(icon: ImageVector, modifier: Modifier, onIconClick: () -> Unit = { }) { Image( imageVector = icon, contentDescription = "", modifier = modifier .padding(8.dp) .clickable { onIconClick() } ) } private fun truncateString(input: String, maxLength: Int = 32): String { return if (input.length <= maxLength) { input } else { input.substring(0, maxLength) + "..." } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/mainscreen/TsundokuItem.kt
3312705665
package app.sanao1006.tsundoku.feature.mainscreen import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.PostAdd import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import app.sanao1006.tsundoku.data.desiginsystem.Typography import io.sanao1006.tsundoku.R import kotlinx.coroutines.launch @Composable fun TsundokuScreen( viewModel: TsundokuScreenViewModel, onFabClick: () -> Unit, onItemClick: (id: Int) -> Unit, ) { val state by viewModel.tsundokuState.collectAsState() val rememberCoroutineScope = rememberCoroutineScope() Scaffold( topBar = { TopAppBar( backgroundColor = Color(0xFFE5F7FF), elevation = 0.dp ) {} }, floatingActionButton = { FloatingActionButton(onClick = onFabClick) { Icon(imageVector = Icons.Default.Add, contentDescription = "") } } ) { innerPadding -> Box( contentAlignment = if (state.tsundokus.isEmpty()) { Alignment.Center } else { Alignment.TopCenter }, modifier = Modifier .padding(innerPadding) .fillMaxSize(), ) { if (state.tsundokus.isEmpty()) { Column { Icon( imageVector = Icons.Default.PostAdd, contentDescription = "", modifier = Modifier .align(Alignment.CenterHorizontally) .size(64.dp) ) Text( text = stringResource(R.string.description_when_tsundoku_empty), style = Typography.h6 ) } } else { LazyColumn( contentPadding = PaddingValues( vertical = 8.dp, horizontal = 8.dp ) ) { items(state.tsundokus) { book -> TsundokuItem( book = book, onDeleteButtonClick = { rememberCoroutineScope.launch { viewModel.deleteBook(bookId = book.id) } }, onItemClick = { id -> onItemClick(id) } ) } } } if (state.isLoading) CircularProgressIndicator() if (!state.error.isNullOrEmpty()) Text(state.error ?: "") } } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/mainscreen/TsundokuScreen.kt
2125849878
package app.sanao1006.tsundoku.feature.mainscreen import app.sanao1006.tsundoku.data.model.Book data class TsundokuMainScreenState( val tsundokus: List<Book>, val isLoading: Boolean, val error: String? = null, )
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/mainscreen/TsundokuMainScreenState.kt
1106562886
package app.sanao1006.tsundoku.feature.mainscreen import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.sanao1006.tsundoku.data.di.TsundokuRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TsundokuScreenViewModel @Inject constructor( private val tsundokuRepository: TsundokuRepository ) : ViewModel() { private val _tsundokuState = MutableStateFlow( TsundokuMainScreenState( tsundokus = listOf(), isLoading = true ) ) val tsundokuState = _tsundokuState.asStateFlow() init { getBooks() } private fun getBooks() { viewModelScope.launch { tsundokuRepository.getBooks().collect { _tsundokuState.value = TsundokuMainScreenState( tsundokus = it, isLoading = false, ) } } } suspend fun deleteBook(bookId: Int) = tsundokuRepository.deleteBook(bookId = bookId) }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/mainscreen/TsundokuScreenViewModel.kt
4017988509
package app.sanao1006.tsundoku.feature.detail import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.sanao1006.tsundoku.data.di.TsundokuRepository import app.sanao1006.tsundoku.data.model.Book import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TsundokuDetailScreenViewModel @Inject constructor( private val tsundokuRepository: TsundokuRepository ) : ViewModel() { private val _book = MutableStateFlow( Book( id = 0, title = "", description = "", totalPage = 0, createAt = "", updatedAt = "" ) ) val book = _book.asStateFlow() fun getBook(bookId: Int) = viewModelScope.launch { tsundokuRepository.getBook(bookId = bookId).collect { _book.value = it } } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/detail/TsundokuDetailScreenViewModel.kt
1055449081
package app.sanao1006.tsundoku.feature.detail 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.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.MenuBook import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import app.sanao1006.tsundoku.data.desiginsystem.Typography import app.sanao1006.tsundoku.data.model.Book import io.sanao1006.tsundoku.R @Composable fun TsundokuDetailScreen( book: Book, onBackButtonClick: () -> Unit, modifier: Modifier = Modifier ) { Scaffold( topBar = { TopAppBar( title = { Text(stringResource(id = R.string.title_detail_tsundoku)) }, navigationIcon = { IconButton(onClick = onBackButtonClick) { Icon(Icons.Default.ArrowBack, "") } }, backgroundColor = Color(0xfff2fbff) ) }, ) { innerPadding -> Box( modifier = modifier .fillMaxWidth() .padding(innerPadding), ) { Column( modifier = modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Icon( imageVector = Icons.Default.MenuBook, contentDescription = "", modifier = Modifier .size(64.dp) .align(Alignment.CenterHorizontally) ) Spacer(modifier = Modifier.size(8.dp)) Column( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(Color.White) ) { Column(modifier = Modifier.padding(12.dp)) { Text( text = stringResource(id = R.string.book_title), color = Color(0xFF18864B), fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.width(8.dp)) Text(text = book.title, style = Typography.h1) Divider( color = Color.Gray, modifier = Modifier .height(1.dp) .fillMaxWidth() ) } if (!book.description.isNullOrBlank()) { Column( modifier = Modifier.padding(12.dp), horizontalAlignment = Alignment.Start ) { Text( text = stringResource(id = R.string.book_description), color = Color(0xFF18864B), fontWeight = FontWeight.Bold ) Text(book.description) Divider( color = Color.Gray, modifier = Modifier .height(1.dp) .fillMaxWidth() ) Spacer(modifier = Modifier.size(8.dp)) } } } Column( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(Color.White), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.size(4.dp)) Text( text = stringResource(id = R.string.book_progress_percent), fontWeight = FontWeight.Bold, style = Typography.h5, textAlign = TextAlign.Center ) Row(verticalAlignment = Alignment.CenterVertically) { Text( text = stringResource( id = R.string.reading_progress, (book.nowPage.toDouble() / book.totalPage.toDouble()) * 100.0 ), style = Typography.h6 ) Spacer(modifier = Modifier.size(4.dp)) Text( text = stringResource( id = R.string.book_pages, book.nowPage, book.totalPage.toString() ) ) } Spacer(modifier = Modifier.size(16.dp)) Column( horizontalAlignment = Alignment.Start ) { Text(stringResource(id = R.string.date_last_updated, book.updatedAt)) Text(stringResource(id = R.string.date_created, book.createAt)) } Spacer(modifier = Modifier.size(4.dp)) } } } } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/detail/TsundokuDetailScreen.kt
1269670582
package app.sanao1006.tsundoku.feature.create import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.sanao1006.tsundoku.domain.InsertTsundokuUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.datetime.Clock import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import javax.inject.Inject @HiltViewModel class TsundokuCreateViewModel @Inject constructor( private val insertTsundokuUseCase: InsertTsundokuUseCase ) : ViewModel() { private val _title = MutableStateFlow("") var title = _title.asStateFlow() private val _description = MutableStateFlow("") var description = _description.asStateFlow() private val _totalPage = MutableStateFlow("") var totalPage = _totalPage.asStateFlow() fun insertTsundoku() = viewModelScope.launch { insertTsundokuUseCase( title = _title.value, description = _description.value, totalPage = _totalPage.value.toInt(), createAt = getCurrentTime(), updatedAt = getCurrentTime(), ) clear() } private fun clear() { _title.value = "" _description.value = "" _totalPage.value = "" } fun onTitleValueChange(title: String) { _title.value = title } fun onDescriptionValueChange(des: String) { _description.value = des } fun onTotalPageValueChange(totalPage: String) { _totalPage.value = totalPage } private fun getCurrentTime(): String { val currentInstant = Clock.System.now() val currentLocalDateTIme = currentInstant.toLocalDateTime(TimeZone.currentSystemDefault()) return currentLocalDateTIme.date.toString() } }
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/create/TsundokuCreateViewModel.kt
3579219795