Compare commits

..
3 Commits
Author SHA1 Message Date
gogacoder a956bc3564 First commit 2023-08-19 22:04:05 +07:00
gogacoder 833f8a99c1 .gitignore 2023-08-19 22:03:47 +07:00
gogacoder d43982d8f7 Initial commit 2023-08-19 21:58:28 +07:00
62 changed files with 1519 additions and 1165 deletions
+12 -328
View File
@@ -1,331 +1,15 @@
### Android ###
# Built application files
*.apk
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml *.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/caches
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# Google Services (e.g. APIs or Firebase)
google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
### Android Patch ###
gen-external-apklibs
### AndroidStudio ###
# Covers files to be ignored for android development using Android Studio.
# Built application files
# Files for the ART/Dalvik VM
# Java class files
# Generated files
# Gradle files
.gradle .gradle
/local.properties
# Signing files /.idea/caches
.signing/ /.idea/libraries
/.idea/modules.xml
# Local configuration file (sdk path, etc) /.idea/workspace.xml
/.idea/navEditor.xml
# Proguard folder generated by Eclipse /.idea/assetWizardSettings.xml
# Log Files
# Android Studio
/*/build/
/*/local.properties
/*/out
/*/*/build
/*/*/production
*.ipr
*~
*.swp
# Android Patch
# External native build folder generated in Android Studio 2.2 and later
# NDK
obj/
# IntelliJ IDEA
*.iws
/out/
# User-specific configurations
.idea/caches/
.idea/libraries/
.idea/shelf/
.idea/.name
.idea/compiler.xml
.idea/copyright/profiles_settings.xml
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/vcs.xml
.idea/jsLibraryMappings.xml
.idea/datasources.xml
.idea/dataSources.ids
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# OS-specific files
.DS_Store .DS_Store
.DS_Store? /build
._* /captures
.Spotlight-V100 .externalNativeBuild
.Trashes .cxx
ehthumbs.db local.properties
Thumbs.db
# Legacy Eclipse project files
.classpath
.project
.cproject
.settings/
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.war
*.ear
# virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
hs_err_pid*
## Plugin-specific files:
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Mongo Explorer plugin
.idea/mongoSettings.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### AndroidStudio Patch ###
!/gradle/wrapper/gradle-wrapper.jar
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
# IntelliJ
# mpeltonen/sbt-idea plugin
# JIRA plugin
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Java ###
# Compiled class file
# Log file
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
# Package Files #
*.jar
*.nar
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
### Linux ###
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.TemporaryItems
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Windows ###
# Windows thumbnail cache files
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
Generated
+1
View File
@@ -0,0 +1 @@
pilot
-123
View File
@@ -1,123 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="XML">
<option name="FORCE_REARRANGE_MODE" value="1" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</codeStyleSettings>
</code_scheme>
</component>
-5
View File
@@ -1,5 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
</project>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="jbr-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
+41
View File
@@ -0,0 +1,41 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PreviewAnnotationInFunctionWithParameters" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewApiLevelMustBeValid" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewDimensionRespectsLimit" enabled="true" level="WARNING" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewFontScaleMustBeGreaterThanZero" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewMultipleParameterProviders" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewMustBeTopLevelFunction" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewNeedsComposableAnnotation" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewNotSupportedInUnitTestFiles" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewPickerAnnotation" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
</profile>
</component>
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="KotlinJpsPluginSettings"> <component name="KotlinJpsPluginSettings">
<option name="version" value="1.8.20" /> <option name="version" value="1.8.10" />
</component> </component>
</project> </project>
+9
View File
@@ -0,0 +1,9 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
-52
View File
@@ -1,52 +0,0 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
signingConfigs {
debug {
storeFile file('/home/gogacoder/AndroidStudioProjects/keychain/key.jks')
storePassword '123456'
keyPassword '123456'
keyAlias 'key0'
}
}
namespace 'com.listerk.helible'
compileSdk 34
defaultConfig {
applicationId "com.listerk.helible"
minSdk 30
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.10.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
+74
View File
@@ -0,0 +1,74 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("kotlin-parcelize")
}
android {
namespace = "com.helible.pilot"
compileSdk = 33
defaultConfig {
applicationId = "com.helible.pilot"
minSdk = 28
targetSdk = 33
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.4.3"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1")
implementation("androidx.activity:activity-compose:1.7.2")
implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1")
implementation("androidx.constraintlayout:constraintlayout-compose:1.0.1")
implementation("androidx.navigation:navigation-compose:2.6.0")
implementation("com.google.code.gson:gson:2.10.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}
Binary file not shown.
@@ -4,8 +4,8 @@
"type": "APK", "type": "APK",
"kind": "Directory" "kind": "Directory"
}, },
"applicationId": "com.listerk.helible", "applicationId": "com.helible.pilot",
"variantName": "debug", "variantName": "release",
"elements": [ "elements": [
{ {
"type": "SINGLE", "type": "SINGLE",
@@ -13,7 +13,7 @@
"attributes": [], "attributes": [],
"versionCode": 1, "versionCode": 1,
"versionName": "1.0", "versionName": "1.0",
"outputFile": "app-debug.apk" "outputFile": "app-release.apk"
} }
], ],
"elementType": "File" "elementType": "File"
@@ -1,4 +1,4 @@
package com.listerk.helible package com.helible.pilot
import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -19,6 +19,6 @@ class ExampleInstrumentedTest {
fun useAppContext() { fun useAppContext() {
// Context of the app under test. // Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.listerk.helible", appContext.packageName) assertEquals("com.gogacoder.testblue", appContext.packageName)
} }
} }
+12 -14
View File
@@ -2,19 +2,19 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<!-- Legacy permissions (API 30 and below) --> <!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/> <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
<!--<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="30"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" android:maxSdkVersion="30"/>-->
<!-- Request Bluetooth permissions for API level 31+ -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation"/> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:minSdkVersion="31"
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> android:usesPermissionFlags="neverForLocation" tools:targetApi="s" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" android:minSdkVersion="31"
android:usesPermissionFlags="neverForLocation" tools:targetApi="s" />
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/> <uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
<uses-feature android:name="android.hardware.bluetooth_le" />
<application <application
android:allowBackup="true" android:allowBackup="true"
@@ -24,16 +24,14 @@
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.HeliBLE"> android:theme="@style/Theme.Testblue"
tools:targetApi="31">
<activity <activity
android:name=".ControlActivity" android:name="com.helible.pilot.MainActivity"
android:exported="false" /> android:exported="true"
<activity android:theme="@style/Theme.Testblue">
android:name=".MainActivity"
android:exported="true">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
@@ -0,0 +1,70 @@
package com.helible.pilot
import android.annotation.SuppressLint
import android.bluetooth.BluetoothSocket
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import java.io.IOException
import java.util.UUID
sealed interface ConnectionResult {
object ConnectionEstablished: ConnectionResult
data class Error(val message: String) : ConnectionResult
}
interface BluetoothController {
val isConnected: StateFlow<Boolean>
val errors: SharedFlow<String>
fun connectToDevice(device: Device?): Flow<ConnectionResult>
fun closeConnection()
}
class AndroidBluetoothController : BluetoothController {
private val _isConnected: MutableStateFlow<Boolean> = MutableStateFlow(false)
override val isConnected: StateFlow<Boolean>
get() = _isConnected.asStateFlow()
private val _errors = MutableSharedFlow<String>()
override val errors: SharedFlow<String>
get() = _errors.asSharedFlow()
private var currentClientSocket: BluetoothSocket? = null
companion object {
const val SERVICE_UUID = "af7cc14b-cffa-4a3d-b677-01b0ff0a93d7"
}
@SuppressLint("MissingPermission")
override fun connectToDevice(device: Device?): Flow<ConnectionResult> {
return flow {
currentClientSocket = device?.bluetoothDevice?.createRfcommSocketToServiceRecord(
UUID.fromString(SERVICE_UUID)
)
currentClientSocket?.let { socket ->
try {
socket.connect()
emit(ConnectionResult.ConnectionEstablished)
} catch (e: IOException) {
closeConnection()
emit(ConnectionResult.Error("Connection was interrupted"))
}
}
}.onCompletion { closeConnection() }.flowOn(Dispatchers.IO)
}
override fun closeConnection() {
currentClientSocket?.close()
currentClientSocket = null
}
}
@@ -0,0 +1,249 @@
package com.helible.pilot
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.helible.pilot.components.BluetoothScannerScreen
import com.helible.pilot.components.PreferencesCacheImpl
import com.helible.pilot.components.SavedPreferences
import com.helible.pilot.ui.theme.TestblueTheme
import java.util.concurrent.Executors
@SuppressLint("MissingPermission")
class MainActivity : ComponentActivity() {
// TODO: delegate part of Intent filters logic to BluetoothController
// TODO: move bluetooth states and stateFlow to new BluetoothViewModel
// TODO: replace field bluetoothDevice in Device to deviceAddress field
// TODO: replace some mutableStates to stateFlows
// TODO: share selected device via PersistentViewModel
// TODO: check permissions inside other classes (and throw an exception, if one of this isn't granted)
// TODO: add stub instead of the DevicesList, if there aren't nearby devices
// TODO: add Bluetooth data transfer...
// TODO: add text strings to resource
val mainViewModel: MainViewModel = MainViewModel(AndroidBluetoothController())
private val bluetoothManager: BluetoothManager by lazy {
getSystemService(BluetoothManager::class.java)
}
private val bluetoothAdapter: BluetoothAdapter? by lazy {
bluetoothManager.adapter
}
private var permissionsViewModel = PermissionDialogViewModel()
private lateinit var permissionLauncher: ManagedActivityResultLauncher<Array<String>, Map<String, Boolean>>
private val permissionsToRequest: Array<String> by lazy {
if (Build.VERSION.SDK_INT <= 30) {
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION
)
} else {
arrayOf(
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_ADMIN
)
}
}
private val locationManager: LocationManager by lazy {
getSystemService(LOCATION_SERVICE) as LocationManager
}
private val preferencesCache by lazy {
PreferencesCacheImpl(getSharedPreferences(packageName, Context.MODE_PRIVATE))
}
private val preferencesViewModel by lazy {
PersistentViewModel(preferencesCache)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainViewModel.bluetoothTurnOnState.value = bluetoothAdapter?.isEnabled
mainViewModel.locationTurnOnState.value =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
setContent {
this.permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestMultiplePermissions(),
onResult = { perms ->
permissionsToRequest.forEach { permission ->
permissionsViewModel.onPermissionResult(
permission = permission,
isGranted = perms[permission] == true
)
}
}
)
val state by mainViewModel.state.collectAsState()
LaunchedEffect(key1 = state.errorMessage) {
state.errorMessage?.let { message ->
Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()
}
}
LaunchedEffect(key1 = state) {
if (state.isConnected) {
Toast.makeText(applicationContext, "Подключение завершено", Toast.LENGTH_LONG)
.show()
}
}
val navController = rememberNavController()
TestblueTheme {
Surface(color = MaterialTheme.colorScheme.background) {
PermissionsRequest(
dismissCurrentDialog = { permissionsViewModel.dismissDialog() },
visiblePermissionDialogQueue = permissionsViewModel.visiblePermissionDialogQueue,
activity = this,
permissionLauncher = permissionLauncher
)
RequestHardwareFeatures(
activity = this,
turnOnLocation = Manifest.permission.ACCESS_FINE_LOCATION in permissionsToRequest,
bluetoothTurnOnState = mainViewModel.bluetoothTurnOnState,
locationTurnOnState = mainViewModel.locationTurnOnState
)
NavHost(navController = navController, startDestination = "scanner") {
composable("scanner") {
BluetoothScannerScreen(
devices = mainViewModel.devices,
selectedDevice = mainViewModel.selectedDevice,
bluetoothIsDiscoveringState = mainViewModel.isBluetoothDiscoveryRunning,
bluetoothAdapter = bluetoothAdapter,
onScreenChanged = {
bluetoothAdapter?.cancelDiscovery()
preferencesViewModel.savePreferences(
SavedPreferences(
mainViewModel.selectedDevice.value?.bluetoothDevice?.address
)
)
navController.navigate("flight")
Log.i(
"ScanActivity",
"Preferences: ${preferencesViewModel.preferences}"
)
}
)
}
composable("flight") {
LaunchedEffect(Unit) {
// TODO: refactor
val device: Device = mainViewModel.selectedDevice.value!!
mainViewModel.connectToDevice(device)
}
when {
state.isConnecting -> {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
CircularProgressIndicator()
Text(text = "Подключение...", textAlign = TextAlign.Center)
}
}
else -> {
Text(
text = "Device name: ${mainViewModel.selectedDevice.value?.bluetoothDevice?.name}",
modifier = Modifier.fillMaxSize(),
textAlign = TextAlign.Center
)
}
}
}
}
}
}
}
registerIntentFilters(this, receiver)
requestPermissions()
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
receiveIntentChanges(
intent,
mainViewModel,
bluetoothAdapter,
locationManager
)
}
}
private fun requestPermissions() {
Executors.newSingleThreadExecutor().execute {
Handler(Looper.getMainLooper()).post {
permissionLauncher.launch(permissionsToRequest)
}
}
}
override fun onDestroy() {
unregisterReceiver(receiver)
super.onDestroy()
Log.i("ScanActivity", "ACTIVITY DESTROYED")
bluetoothAdapter?.cancelDiscovery()
try {
unregisterReceiver(receiver)
} catch (e: IllegalArgumentException) {
Log.e(
"ScanActivity",
"Receiver wasn't registered ${e.localizedMessage}\nStackTrace: ${e.stackTrace}"
)
}
}
override fun onStart() {
super.onStart()
if (bluetoothAdapter?.isDiscovering != true)
bluetoothAdapter?.startDiscovery()
Log.i("ScanActivity", "ACTIVITY STARTED")
}
override fun onStop() {
super.onStop()
bluetoothAdapter?.cancelDiscovery()
mainViewModel.devices.clear()
mainViewModel.selectedDevice.value = null
Log.i("ScanActivity", "ACTIVITY STOPPED")
}
}
@@ -0,0 +1,133 @@
package com.helible.pilot
import android.bluetooth.BluetoothDevice
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helible.pilot.components.SavedPreferences
import com.helible.pilot.components.SavedPreferencesCache
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
data class Device(
val bluetoothDevice: BluetoothDevice,
val rssi: Short,
)
data class BluetoothUiState(
val isConnected: Boolean = false,
val isConnecting: Boolean = false,
val errorMessage: String? = null
)
class MainViewModel(
private val bluetoothController: BluetoothController
) : ViewModel() {
val devices: MutableList<Device> = mutableStateListOf()
val selectedDevice: MutableState<Device?> = mutableStateOf(null)
val bluetoothTurnOnState: MutableState<Boolean?> = mutableStateOf(false)
val locationTurnOnState: MutableState<Boolean?> = mutableStateOf(null)
val isBluetoothDiscoveryRunning: MutableState<Boolean> = mutableStateOf(false)
private val _bluetoothState = MutableStateFlow(BluetoothUiState())
val state: StateFlow<BluetoothUiState>
get() = _bluetoothState.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), _bluetoothState.value)
init {
bluetoothController.isConnected.onEach {
isConnected -> _bluetoothState.update { it.copy(isConnected = isConnected) }
}.launchIn(viewModelScope)
bluetoothController.errors.onEach { error ->
_bluetoothState.update {
it.copy(errorMessage = error)
}
}.launchIn(viewModelScope)
}
private fun Flow<ConnectionResult>.listen(): Job {
return onEach { result ->
when(result) {
ConnectionResult.ConnectionEstablished -> {
_bluetoothState.update {
it.copy(
isConnected = true,
isConnecting = false,
errorMessage = null
)
}
}
is ConnectionResult.Error -> {
_bluetoothState.update { it.copy(
isConnected = false,
isConnecting = false,
errorMessage = result.message
) }
}
}
}
.catch { throwable ->
bluetoothController.closeConnection()
_bluetoothState.update {
it.copy(
isConnected = false,
isConnecting = false
)
}
}
.launchIn(viewModelScope)
}
private var deviceConnectionJob: Job? = null
fun connectToDevice(device: Device) {
_bluetoothState.update {it.copy(isConnecting = true)}
deviceConnectionJob = bluetoothController
.connectToDevice(device)
.listen()
}
fun disconnectFromDevice() {
deviceConnectionJob?.cancel()
bluetoothController.closeConnection()
_bluetoothState.update {
it.copy(
isConnecting = false,
isConnected = false
)
}
}
}
class PermissionDialogViewModel: ViewModel() {
val visiblePermissionDialogQueue = mutableStateListOf<String>()
fun dismissDialog() {
visiblePermissionDialogQueue.removeFirst()
}
fun onPermissionResult(permission: String, isGranted: Boolean) {
if(!isGranted && !visiblePermissionDialogQueue.contains(permission)){
visiblePermissionDialogQueue.add(permission)
}
}
}
class PersistentViewModel(
private val preferencesCache: SavedPreferencesCache,
) : ViewModel() {
val preferences get() = preferencesCache.getPreferences()
fun savePreferences(savedPreferences: SavedPreferences) {
preferencesCache.savePreferences(
preferences = savedPreferences
)
}
}
@@ -0,0 +1,70 @@
package com.helible.pilot
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.compose.runtime.Composable
import androidx.compose.runtime.snapshots.SnapshotStateList
import com.helible.pilot.components.BluetoothAdminPermissionTextProvider
import com.helible.pilot.components.BluetoothConnectPermissionTextProvider
import com.helible.pilot.components.BluetoothScanPermissionTextProvider
import com.helible.pilot.components.LocationPermissionTextProvider
import com.helible.pilot.components.PermissionDialog
@Composable
fun PermissionsRequest(
visiblePermissionDialogQueue: SnapshotStateList<String>,
dismissCurrentDialog: () -> Unit,
activity: Activity,
permissionLauncher: ManagedActivityResultLauncher<Array<String>, Map<String, Boolean>>
) {
/* Create Dialog windows, which requests all permissions */
visiblePermissionDialogQueue.reversed()
.forEach { permission ->
PermissionDialog(
permissionTextProvider = when (permission) {
Manifest.permission.ACCESS_FINE_LOCATION -> {
LocationPermissionTextProvider()
}
Manifest.permission.BLUETOOTH_SCAN -> {
BluetoothScanPermissionTextProvider()
}
Manifest.permission.BLUETOOTH_CONNECT -> {
BluetoothConnectPermissionTextProvider()
}
Manifest.permission.BLUETOOTH_ADMIN -> {
BluetoothAdminPermissionTextProvider()
}
else -> return@forEach
},
isPermanentDeclined = !activity.shouldShowRequestPermissionRationale(permission),
onDismiss = {
if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED)
dismissCurrentDialog()
},
onOkClick = {
dismissCurrentDialog()
permissionLauncher.launch(arrayOf(permission))
},
onContinueClick = {
if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED)
dismissCurrentDialog()
},
onGoToAppSettingsClick = {
val intent = Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", activity.packageName, null)
)
activity.startActivity(intent)
}
)
}
}
@@ -0,0 +1,86 @@
package com.helible.pilot
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.location.LocationManager
import android.os.Build
import android.util.Log
fun registerIntentFilters(activity: Activity, receiver: BroadcastReceiver) {
activity.registerReceiver(receiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
activity.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED))
activity.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
activity.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
if (Build.VERSION.SDK_INT <= 30)
activity.registerReceiver(receiver, IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION))
}
@SuppressLint("MissingPermission")
fun receiveIntentChanges(
intent: Intent,
mainViewModel: MainViewModel,
bluetoothAdapter: BluetoothAdapter?,
locationManager: LocationManager,
) {
when (intent.action) {
BluetoothDevice.ACTION_FOUND -> {
val device = if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE,
BluetoothDevice::class.java
)
} else {
@Suppress("DEPRECATION") intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
}
val rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE)
if (device?.name != null)
mainViewModel.devices.add(Device(device, rssi))
Log.i(
"ScanActivity",
"Found new device: ${device?.name} ${device?.address} $rssi"
)
}
BluetoothAdapter.ACTION_STATE_CHANGED -> {
val state: Int = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
Log.i("ScanActvity", "Bluetooth state: $state")
when (state) {
BluetoothAdapter.STATE_ON -> {
Log.i("ScanActvity", "Bluetooth turned on")
mainViewModel.bluetoothTurnOnState.value = true
mainViewModel.devices.clear()
bluetoothAdapter?.startDiscovery()
}
BluetoothAdapter.STATE_OFF -> {
Log.i("ScanActvity", "Bluetooth turned off")
mainViewModel.bluetoothTurnOnState.value = false
}
}
}
LocationManager.PROVIDERS_CHANGED_ACTION -> {
mainViewModel.locationTurnOnState.value = locationManager.isLocationEnabled
if (mainViewModel.locationTurnOnState.value == true) {
Log.i("ScanActivity", "LOCATION IS ON")
} else if (mainViewModel.locationTurnOnState.value == false)
Log.i("ScanActivity", "LOCATION IS OFF")
}
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
mainViewModel.isBluetoothDiscoveryRunning.value = false
Log.i("ScanActivity", "DISCOVERY FINISHED")
}
BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
mainViewModel.isBluetoothDiscoveryRunning.value = true
Log.i("ScanActivity", "DISCOVERY STARTED")
}
}
}
@@ -0,0 +1,46 @@
package com.helible.pilot
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.provider.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import com.helible.pilot.components.RequiredHardwareFeatures
@SuppressLint("MissingPermission")
@Composable
fun RequestHardwareFeatures(
activity: Activity,
turnOnLocation: Boolean,
bluetoothTurnOnState: MutableState<Boolean?>,
locationTurnOnState: MutableState<Boolean?>
)
{
RequiredHardwareFeatures(
title = "Включите Bluetooth",
description = "Для работы приложения требуется Bluetooth",
confirmButtonText = "Включить Bluetooth",
featureState = bluetoothTurnOnState,
requestFeature = {
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
activity.startActivity(intent)
},
onDismissRequest = {}
)
if (turnOnLocation) {
RequiredHardwareFeatures(
title = "Пожалуйста, включите геолокацию",
description = "Для работы с Bluetooth на устройствах с Android 11 и более ранних версиях, " +
"требуется геолокация.",
confirmButtonText = "Включить геолокацию",
featureState = locationTurnOnState,
requestFeature = {
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
activity.startActivity(intent)
}
) {}
}
}
@@ -0,0 +1,118 @@
package com.helible.pilot.components
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledIconToggleButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.helible.pilot.Device
@SuppressLint("MissingPermission")
@Composable
fun BluetoothScannerScreen(
devices: MutableList<Device>,
selectedDevice: MutableState<Device?>,
bluetoothIsDiscoveringState: MutableState<Boolean>,
bluetoothAdapter: BluetoothAdapter?,
onScreenChanged: () -> Unit,
modifier: Modifier = Modifier
) {
Surface(
modifier = modifier,
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (title, devicesList, controls) = createRefs()
Title(
text = "Поиск устройств",
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp)
.constrainAs(title) {}
)
DiscoveredDevicesList(
devices = devices,
selectedDevice = selectedDevice,
modifier = Modifier
.constrainAs(devicesList) {
top.linkTo(title.bottom)
bottom.linkTo(controls.top)
height = Dimension.fillToConstraints
}
)
if (devices.isEmpty() && bluetoothIsDiscoveringState.value) {
Box(
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
Row(
modifier = Modifier
.padding(5.dp)
.constrainAs(controls) {
bottom.linkTo(parent.bottom)
width = Dimension.matchParent
height = Dimension.fillToConstraints
},
horizontalArrangement = Arrangement.Center
) {
FilledIconToggleButton(
checked = bluetoothIsDiscoveringState.value,
onCheckedChange = {
selectedDevice.value = null
if (bluetoothIsDiscoveringState.value)
bluetoothAdapter?.cancelDiscovery()
else {
devices.clear()
bluetoothAdapter?.startDiscovery()
}
}, modifier = Modifier
.align(Alignment.Bottom)
.padding(5.dp)
) {
Icon(
if (bluetoothIsDiscoveringState.value) Icons.Filled.Close
else Icons.Filled.Refresh,
contentDescription = null
)
}
Button(
onClick = {
onScreenChanged()
},
modifier = Modifier
.align(Alignment.Bottom)
.padding(5.dp),
enabled = selectedDevice.value != null,
) {
Text(text = "Далее")
}
}
}
}
}
@@ -0,0 +1,71 @@
package com.helible.pilot.components
import android.annotation.SuppressLint
import android.widget.TextView
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.text.HtmlCompat
import com.helible.pilot.Device
import com.helible.pilot.R
@SuppressLint("MissingPermission")
@Composable
fun DeviceItem(deviceInfo: Device, selectedDevice: MutableState<Device?>, modifier: Modifier) {
ElevatedCard(
modifier=modifier.clickable {
selectedDevice.value = deviceInfo
},
colors = CardDefaults.elevatedCardColors(containerColor = if (deviceInfo.bluetoothDevice == selectedDevice.value?.bluetoothDevice)
MaterialTheme.colorScheme.secondaryContainer
else MaterialTheme.colorScheme.surface
)
) {
Row(modifier=Modifier.padding(8.dp)) {
Column(verticalArrangement = Arrangement.Center) {
Text(text=deviceInfo.bluetoothDevice.name, fontWeight = FontWeight.Bold, softWrap = true)
AndroidView(factory = { context ->
TextView(context).apply {
// Using old TextView for text formatting
text = HtmlCompat.fromHtml("<b>MAC</b>: ${deviceInfo.bluetoothDevice.address}", HtmlCompat.FROM_HTML_MODE_LEGACY)
}
})
}
Box(contentAlignment = Alignment.CenterEnd, modifier = Modifier.fillMaxSize()) {
Icon(
painterResource(id = getSignalIconForRssiValue(deviceInfo.rssi)),
contentDescription = null,
modifier = Modifier
.fillMaxHeight()
.padding(10.dp),
tint = MaterialTheme.colorScheme.primary
)
}
}
}
}
fun getSignalIconForRssiValue(rssi: Short): Int{
if (rssi >= -80) return R.drawable.signal_icon4
else if (rssi >= -90) return R.drawable.signal_icon3
else if (rssi >= -100) return R.drawable.signal_icon2
return R.drawable.signal_icon1
}
@@ -0,0 +1,28 @@
package com.helible.pilot.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.helible.pilot.Device
@Composable
fun DiscoveredDevicesList(devices: MutableList<Device>, selectedDevice: MutableState<Device?>, modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier) {
items(devices) { device ->
DeviceItem(
deviceInfo = device,
selectedDevice = selectedDevice,
modifier = Modifier
.fillMaxWidth()
.padding(
5.dp
)
)
}
}
}
@@ -0,0 +1,38 @@
package com.helible.pilot.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
@Composable
fun RequiredHardwareFeatures(
title: String,
description: String,
confirmButtonText: String,
featureState: MutableState<Boolean?>,
requestFeature: () -> Unit,
onDismissRequest: () -> Unit
) {
if (featureState.value == false || featureState.value == null) {
AlertDialog(
confirmButton = {
Divider()
TextButton(onClick = requestFeature, modifier = Modifier.fillMaxWidth()) {
Text(text=confirmButtonText)
}
},
onDismissRequest = onDismissRequest,
text = {
Text(
text = description
)
},
title = { Text(text = title)}
)
}
}
@@ -0,0 +1,130 @@
package com.helible.pilot.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@Composable
fun PermissionDialog(
permissionTextProvider: PermissionTextProvider,
isPermanentDeclined: Boolean,
onDismiss: () -> Unit,
onOkClick: () -> Unit,
onContinueClick: () -> Unit,
onGoToAppSettingsClick: () -> Unit,
modifier: Modifier = Modifier
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(text = "Требуется разрешение") },
confirmButton = {
Column(
modifier = Modifier.fillMaxWidth()
) {
Divider()
Text(
text = if (isPermanentDeclined) {
"Выдать разрешение"
} else {
"OK"
},
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.clickable {
if (isPermanentDeclined) {
onGoToAppSettingsClick()
} else {
onOkClick()
}
}
.padding(16.dp)
)
}
},
dismissButton = {if(isPermanentDeclined)
Box(modifier=Modifier.fillMaxWidth()){
Divider()
Text(
text = "Снова проверить наличие разрешения",
modifier = Modifier
.fillMaxWidth()
.padding(paddingValues = PaddingValues(top=10.dp))
.clickable {onContinueClick()},
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)}
else
Unit},
text = {
Text(text = permissionTextProvider.getDescription(
isPermanentDeclined = isPermanentDeclined
))
},
modifier = modifier
)
}
interface PermissionTextProvider {
fun getDescription(isPermanentDeclined: Boolean): String
}
class LocationPermissionTextProvider : PermissionTextProvider {
override fun getDescription(isPermanentDeclined: Boolean): String {
return if (isPermanentDeclined){
"Похоже вы навсегда запретили приложению доступ к геолокации. " +
"Вы можете зайти в настройки, чтобы выдать это разрешение."
} else {
"Приложению необходимо разрешение для определения местоположения " +
"для работы с Bluetooth на устройствах с Android 11 и ниже."
}
}
}
class BluetoothScanPermissionTextProvider : PermissionTextProvider {
override fun getDescription(isPermanentDeclined: Boolean): String {
return if (isPermanentDeclined){
"Похоже вы навсегда запретили приложению доступ к сканированию по Bluetooth. " +
"Вы можете зайти в настройки, чтобы выдать это разрешение."
} else {
"Приложению необходимо разрешение для к сканированию по Bluetooth " +
"для работы с Bluetooth на устройствах с Android 11 и ниже"
}
}
}
class BluetoothConnectPermissionTextProvider : PermissionTextProvider {
override fun getDescription(isPermanentDeclined: Boolean): String {
return if (isPermanentDeclined){
"Похоже вы навсегда запретили приложению доступ к подключению по Bluetooth." +
"Вы можете зайти в настройки, чтобы выдать это разрешение."
} else {
"Приложению необходимо разрешение для к подключению по Bluetooth." +
"для работы с Bluetooth на устройствах с Android 11 и ниже"
}
}
}
class BluetoothAdminPermissionTextProvider : PermissionTextProvider {
override fun getDescription(isPermanentDeclined: Boolean): String {
return if (isPermanentDeclined){
"Похоже вы навсегда запретили приложению доступ к управлению настройками Bluetooth. " +
"Вы можете зайти в настройки, чтобы выдать это разрешение."
} else {
"Приложению необходимо разрешение для к управлению настройками Bluetooth " +
"для работы с Bluetooth на устройствах с Android 11 и ниже"
}
}
}
@@ -0,0 +1,37 @@
package com.helible.pilot.components
import android.content.SharedPreferences
import android.os.Parcelable
import com.google.gson.Gson
import kotlinx.parcelize.Parcelize
@Parcelize
data class SavedPreferences(
val deviceAddress: String?
): Parcelable
interface SavedPreferencesCache {
fun getPreferences(): SavedPreferences?
fun savePreferences(preferences: SavedPreferences)
fun clearPreferences()
}
class PreferencesCacheImpl(private val sharedPreferences: SharedPreferences) : SavedPreferencesCache {
override fun getPreferences(): SavedPreferences? {
val json = sharedPreferences.getString("preferences", null) ?: return null
return Gson().fromJson(json, SavedPreferences::class.java)
}
override fun savePreferences(preferences: SavedPreferences)
{
sharedPreferences.edit()
.putString("preferences", Gson().toJson(preferences))
.apply()
}
override fun clearPreferences()
{
sharedPreferences.edit().remove("preferences").apply()
}
}
@@ -0,0 +1,19 @@
package com.helible.pilot.components
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
@Composable
fun Title(text: String, modifier: Modifier = Modifier) {
Text(
text = text,
textAlign = TextAlign.Center,
modifier = modifier,
fontSize = 23.sp,
fontWeight = FontWeight.Bold
)
}
@@ -0,0 +1,11 @@
package com.helible.pilot.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)
@@ -0,0 +1,70 @@
package com.helible.pilot.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 TestblueTheme(
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
)
}
@@ -0,0 +1,34 @@
package com.helible.pilot.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
)
*/
)
@@ -1,5 +0,0 @@
package com.listerk.helible
object AppState {
lateinit var bleDevice: BleDevice
}
@@ -1,3 +0,0 @@
package com.listerk.helible
data class BleDevice(val name: String, val address: String, var rssi: Int)
@@ -1,50 +0,0 @@
package com.listerk.helible
//import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
//import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
//import org.w3c.dom.Text
class BleDeviceAdapter(private val devices: List<BleDevice>, private val gotoControlBtn: Button) :
RecyclerView.Adapter<BleDeviceAdapter.BleDeviceViewHolder>() {
private lateinit var itemView: View
private var selectedPosition = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BleDeviceViewHolder {
itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_ble_device, parent, false)
return BleDeviceViewHolder(itemView)
}
override fun getItemCount(): Int = devices.size
override fun onBindViewHolder(holder: BleDeviceViewHolder, position: Int) {
holder.nameView.text = devices[position].name
holder.addressView.text = devices[position].address
if (devices[position].rssi >= -80) holder.rssiView.setImageResource(R.drawable.signal_icon4)
else if (devices[position].rssi >= -90) holder.rssiView.setImageResource(R.drawable.signal_icon3)
else if (devices[position].rssi >= -100) holder.rssiView.setImageResource(R.drawable.signal_icon2)
else holder.rssiView.setImageResource(R.drawable.signal_icon1)
holder.cardView.isSelected = position == selectedPosition
holder.cardView.setOnClickListener {
AppState.bleDevice = devices[position]
gotoControlBtn.isEnabled = true
notifyItemChanged(selectedPosition)
selectedPosition = holder.adapterPosition
notifyItemChanged(selectedPosition)
}
}
class BleDeviceViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val cardView: View = itemView.rootView
val nameView: TextView = itemView.findViewById(R.id.deviceName)
val addressView: TextView = itemView.findViewById(R.id.deviceAddress)
val rssiView: ImageView = itemView.findViewById(R.id.deviceRssi)
}
}
@@ -1,55 +0,0 @@
package com.listerk.helible
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.SeekBar
import android.widget.TextView
class ControlActivity : AppCompatActivity() {
private var sliderR1Value = 0
private var sliderR2Value = 0
private var sliderR3Value = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_control)
val deviceNameText = findViewById<TextView>(R.id.controlDeviceName)
deviceNameText.text = getString(R.string.control_device_text, AppState.bleDevice.name)
val sliderR1ValueText = findViewById<TextView>(R.id.sliderR1Value)
val sliderR2ValueText = findViewById<TextView>(R.id.sliderR2Value)
val sliderR3ValueText = findViewById<TextView>(R.id.sliderR3Value)
val sliderR1 = findViewById<SeekBar>(R.id.sliderR1)
val sliderR2 = findViewById<SeekBar>(R.id.sliderR2)
val sliderR3 = findViewById<SeekBar>(R.id.sliderR3)
sliderR1.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
sliderR1Value = progress
sliderR1ValueText.text = getString(R.string.r_slider_text, 1, progress)
}
override fun onStartTrackingTouch(p0: SeekBar?) {}
override fun onStopTrackingTouch(p0: SeekBar?) {}
})
sliderR2.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
sliderR2Value = progress
sliderR2ValueText.text = getString(R.string.r_slider_text, 2, progress)
}
override fun onStartTrackingTouch(p0: SeekBar?) {}
override fun onStopTrackingTouch(p0: SeekBar?) {}
})
sliderR3.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
sliderR3Value = progress
sliderR3ValueText.text = getString(R.string.r_slider_text, 3, progress)
}
override fun onStartTrackingTouch(p0: SeekBar?) {}
override fun onStopTrackingTouch(p0: SeekBar?) {}
})
}
}
@@ -1,140 +0,0 @@
package com.listerk.helible
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Animatable
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
//import android.os.Handler
import android.view.View
import android.widget.Button
import android.widget.ImageView
//import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
@SuppressLint("MissingPermission")
class MainActivity : AppCompatActivity() {
private val bluetoothAdapter: BluetoothAdapter by lazy {
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.adapter
}
private val bleScanner: BluetoothLeScanner by lazy {
bluetoothAdapter.bluetoothLeScanner
}
private val requiredPermissions: MutableSet<String> = mutableSetOf(Manifest.permission.BLUETOOTH_SCAN)
private val foundDevices = mutableListOf<BleDevice>()
private val leScanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
val bleDevicesView = findViewById<RecyclerView>(R.id.bleDevicesView)
val loader = findViewById<ImageView>(R.id.bleDevicesLoader)
if (result.device.name.isNullOrBlank()) {
return
}
if (loader.visibility == View.VISIBLE) {
(loader.drawable as? Animatable)?.stop()
loader.visibility = View.GONE
}
var deviceIndex: Int = foundDevices.indexOfFirst { it.address == result.device.address }
if (deviceIndex < 0) {
deviceIndex = foundDevices.size
foundDevices.add(BleDevice(result.device.name, result.device.address, result.rssi))
} else {
foundDevices[deviceIndex].rssi = result.rssi
}
bleDevicesView.adapter?.notifyItemChanged(deviceIndex)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val gotoControlButton = findViewById<Button>(R.id.gotoControlButton)
gotoControlButton.setOnClickListener {
val intent = Intent(this@MainActivity, ControlActivity::class.java)
startActivity(intent)
}
val loader = findViewById<ImageView>(R.id.bleDevicesLoader)
(loader.drawable as? Animatable)?.start()
val bleDevicesView = findViewById<RecyclerView>(R.id.bleDevicesView)
bleDevicesView.layoutManager = LinearLayoutManager(this)
bleDevicesView.adapter = BleDeviceAdapter(foundDevices, gotoControlButton)
bleDevicesView.itemAnimator = null
if (ActivityCompat.checkSelfPermission(this@MainActivity, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
{
Log.e("StartActivity", "We have denied permissions")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
{
ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 2)
return
}
}
/*if(Build.VERSION.SDK_INT < 31) {
requiredPermissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION)
requiredPermissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION)
requiredPermissions.add(android.Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}
requestPermissions()*/
}
override fun onResume() {
super.onResume()
/*if (!hasNecessaryPermissions()) {
requestPermissions()
} else {*/
bleScanner.startScan(leScanCallback)
//}
}
override fun onPause() {
super.onPause()
/*if (!hasNecessaryPermissions()) {
requestPermissions()
} else {*/
bleScanner.stopScan(leScanCallback)
//}
}
private fun hasNecessaryPermissions(): Boolean
{
for (it in requiredPermissions) {
if (ActivityCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED) {
Log.i("ScanActivity", "Permission isn't allowed: $it")
return false
}
}
return true
}
private fun requestPermissions()
{
Log.i("ScanActivity", "Trying to request permissions: $requiredPermissions")
ActivityCompat.requestPermissions(this@MainActivity, requiredPermissions.toTypedArray(), 1)
if(!hasNecessaryPermissions())
{
Log.e("ScanActivity", "Failed to get all permissions")
} else {
Log.i("ScanActivity", "App got permissions: $requiredPermissions")
}
}
}
@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<shape>
<solid android:color="?attr/selectedBlockColor" />
<corners android:radius="20dp"/>
</shape>
</item>
<item android:state_selected="false">
<shape>
<solid android:color="?attr/baseBlockColor" />
<corners android:radius="20dp"/>
</shape>
</item>
</selector>
@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#000000"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M17.6,11.48 L19.44,8.3a0.63,0.63 0,0 0,-1.09 -0.63l-1.88,3.24a11.43,11.43 0,0 0,-8.94 0L5.65,7.67a0.63,0.63 0,0 0,-1.09 0.63L6.4,11.48A10.81,10.81 0,0 0,1 20L23,20A10.81,10.81 0,0 0,17.6 11.48ZM7,17.25A1.25,1.25 0,1 1,8.25 16,1.25 1.25,0 0,1 7,17.25ZM17,17.25A1.25,1.25 0,1 1,18.25 16,1.25 1.25,0 0,1 17,17.25Z"/>
</vector>
-72
View File
@@ -1,72 +0,0 @@
<animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt">
<aapt:attr name="android:drawable">
<vector
android:name="vector"
android:width="60dp"
android:height="15dp"
android:viewportWidth="40"
android:viewportHeight="10">
<path
android:name="path"
android:pathData="M 5 0 C 3.674 0 2.402 0.527 1.464 1.464 C 0.527 2.402 0 3.674 0 5 C 0 6.326 0.527 7.598 1.464 8.536 C 2.402 9.473 3.674 10 5 10 C 6.326 10 7.598 9.473 8.536 8.536 C 9.473 7.598 10 6.326 10 5 C 10 3.674 9.473 2.402 8.536 1.464 C 7.598 0.527 6.326 0 5 0 Z"
android:fillColor="?android:textColorPrimary"
android:fillAlpha="0"
android:strokeWidth="1"/>
<path
android:name="path_1"
android:pathData="M 20 0 C 18.674 0 17.402 0.527 16.464 1.464 C 15.527 2.402 15 3.674 15 5 C 15 6.326 15.527 7.598 16.464 8.536 C 17.402 9.473 18.674 10 20 10 C 21.326 10 22.598 9.473 23.536 8.536 C 24.473 7.598 25 6.326 25 5 C 25 3.674 24.473 2.402 23.536 1.464 C 22.598 0.527 21.326 0 20 0 Z"
android:fillColor="?android:textColorPrimary"
android:fillAlpha="0"
android:strokeWidth="1"/>
<path
android:name="path_2"
android:pathData="M 35 0 C 33.674 0 32.402 0.527 31.464 1.464 C 30.527 2.402 30 3.674 30 5 C 30 6.326 30.527 7.598 31.464 8.536 C 32.402 9.473 33.674 10 35 10 C 36.326 10 37.598 9.473 38.536 8.536 C 39.473 7.598 40 6.326 40 5 C 40 3.674 39.473 2.402 38.536 1.464 C 37.598 0.527 36.326 0 35 0 Z"
android:fillColor="?android:textColorPrimary"
android:fillAlpha="0"
android:strokeWidth="1"/>
</vector>
</aapt:attr>
<target android:name="path">
<aapt:attr name="android:animation">
<objectAnimator
android:propertyName="fillAlpha"
android:duration="500"
android:valueFrom="0"
android:valueTo="1"
android:valueType="floatType"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:interpolator="@android:anim/linear_interpolator"/>
</aapt:attr>
</target>
<target android:name="path_1">
<aapt:attr name="android:animation">
<objectAnimator
android:propertyName="fillAlpha"
android:startOffset="200"
android:duration="500"
android:valueFrom="0"
android:valueTo="1"
android:valueType="floatType"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:interpolator="@android:anim/linear_interpolator"/>
</aapt:attr>
</target>
<target android:name="path_2">
<aapt:attr name="android:animation">
<objectAnimator
android:propertyName="fillAlpha"
android:startOffset="400"
android:duration="500"
android:valueFrom="0"
android:valueTo="1"
android:valueType="floatType"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:interpolator="@android:anim/linear_interpolator"/>
</aapt:attr>
</target>
</animated-vector>
+3 -3
View File
@@ -4,12 +4,12 @@
android:fillColor="?android:colorPrimary" android:fillColor="?android:colorPrimary"
android:pathData="M 15 340 L 80 340 Q 95 340 95 355 L 95 485 Q 95 500 80 500 L 15 500 Q 0 500 0 485 L 0 355 Q 0 340 15 340 Z" /> android:pathData="M 15 340 L 80 340 Q 95 340 95 355 L 95 485 Q 95 500 80 500 L 15 500 Q 0 500 0 485 L 0 355 Q 0 340 15 340 Z" />
<path <path
android:fillColor="?android:colorButtonNormal" android:fillColor="?android:colorControlHighlight"
android:pathData="M 150 220 L 215 220 Q 230 220 230 235 L 230 485 Q 230 500 215 500 L 150 500 Q 135 500 135 485 L 135 235 Q 135 220 150 220 Z" /> android:pathData="M 150 220 L 215 220 Q 230 220 230 235 L 230 485 Q 230 500 215 500 L 150 500 Q 135 500 135 485 L 135 235 Q 135 220 150 220 Z" />
<path <path
android:fillColor="?android:colorButtonNormal" android:fillColor="?android:colorControlHighlight"
android:pathData="M 285 120 L 350 120 Q 365 120 365 135 L 365 485 Q 365 500 350 500 L 285 500 Q 270 500 270 485 L 270 135 Q 270 120 285 120 Z" /> android:pathData="M 285 120 L 350 120 Q 365 120 365 135 L 365 485 Q 365 500 350 500 L 285 500 Q 270 500 270 485 L 270 135 Q 270 120 285 120 Z" />
<path <path
android:fillColor="?android:colorButtonNormal" android:fillColor="?android:colorControlHighlight"
android:pathData="M 420 0 L 485 0 Q 500 0 500 15 L 500 485 Q 500 500 485 500 L 420 500 Q 405 500 405 485 L 405 15 Q 405 0 420 0 Z" /> android:pathData="M 420 0 L 485 0 Q 500 0 500 15 L 500 485 Q 500 500 485 500 L 420 500 Q 405 500 405 485 L 405 15 Q 405 0 420 0 Z" />
</vector> </vector>
+2 -2
View File
@@ -12,9 +12,9 @@
android:fillColor="?android:colorPrimary" android:fillColor="?android:colorPrimary"
android:pathData="M 150 220 L 215 220 Q 230 220 230 235 L 230 485 Q 230 500 215 500 L 150 500 Q 135 500 135 485 L 135 235 Q 135 220 150 220 Z" /> android:pathData="M 150 220 L 215 220 Q 230 220 230 235 L 230 485 Q 230 500 215 500 L 150 500 Q 135 500 135 485 L 135 235 Q 135 220 150 220 Z" />
<path <path
android:fillColor="?android:colorButtonNormal" android:fillColor="?android:colorControlHighlight"
android:pathData="M 285 120 L 350 120 Q 365 120 365 135 L 365 485 Q 365 500 350 500 L 285 500 Q 270 500 270 485 L 270 135 Q 270 120 285 120 Z" /> android:pathData="M 285 120 L 350 120 Q 365 120 365 135 L 365 485 Q 365 500 350 500 L 285 500 Q 270 500 270 485 L 270 135 Q 270 120 285 120 Z" />
<path <path
android:fillColor="?android:colorButtonNormal" android:fillColor="?android:colorControlHighlight"
android:pathData="M 420 0 L 485 0 Q 500 0 500 15 L 500 485 Q 500 500 485 500 L 420 500 Q 405 500 405 485 L 405 15 Q 405 0 420 0 Z" /> android:pathData="M 420 0 L 485 0 Q 500 0 500 15 L 500 485 Q 500 500 485 500 L 420 500 Q 405 500 405 485 L 405 15 Q 405 0 420 0 Z" />
</vector> </vector>
+1 -1
View File
@@ -15,6 +15,6 @@
android:fillColor="?android:colorPrimary" android:fillColor="?android:colorPrimary"
android:pathData="M 285 120 L 350 120 Q 365 120 365 135 L 365 485 Q 365 500 350 500 L 285 500 Q 270 500 270 485 L 270 135 Q 270 120 285 120 Z" /> android:pathData="M 285 120 L 350 120 Q 365 120 365 135 L 365 485 Q 365 500 350 500 L 285 500 Q 270 500 270 485 L 270 135 Q 270 120 285 120 Z" />
<path <path
android:fillColor="?android:colorButtonNormal" android:fillColor="?android:colorControlHighlight"
android:pathData="M 420 0 L 485 0 Q 500 0 500 15 L 500 485 Q 500 500 485 500 L 420 500 Q 405 500 405 485 L 405 15 Q 405 0 420 0 Z" /> android:pathData="M 420 0 L 485 0 Q 500 0 500 15 L 500 485 Q 500 500 485 500 L 420 500 Q 405 500 405 485 L 405 15 Q 405 0 420 0 Z" />
</vector> </vector>
@@ -1,73 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/controlDeviceName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Устройство не задано"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="@+id/sliderR1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:max="65535"
app:layout_constraintTop_toBottomOf="@+id/controlDeviceName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/sliderR1Value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="R1: 0 / 65536"
app:layout_constraintTop_toBottomOf="@+id/sliderR1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<SeekBar
android:id="@+id/sliderR2"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:max="65535"
app:layout_constraintTop_toBottomOf="@+id/sliderR1Value"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/sliderR2Value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="R2: 0 / 65536"
app:layout_constraintTop_toBottomOf="@+id/sliderR2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<SeekBar
android:id="@+id/sliderR3"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:max="65535"
app:layout_constraintTop_toBottomOf="@+id/sliderR2Value"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/sliderR3Value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="R3: 0 / 65536"
app:layout_constraintTop_toBottomOf="@+id/sliderR3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
-53
View File
@@ -1,53 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ControlActivity">
<TextView
android:id="@+id/devicesTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="12dp"
android:textSize="24sp"
android:textStyle="bold"
android:text="Устройства" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/bleDevicesView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/devicesTitle"
tools:listitem="@layout/item_ble_device" />
<ImageView
android:id="@+id/bleDevicesLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/loader"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/bleDevicesView" />
<Button
android:id="@+id/gotoControlButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Далее"
android:enabled="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="12dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
@@ -1,41 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="12dp"
android:layout_marginVertical="4dp"
android:paddingHorizontal="12dp"
android:paddingVertical="8dp"
android:background="@drawable/ble_device_bg">
<TextView
android:id="@+id/deviceName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:textSize="18sp"
android:textStyle="bold"
android:text="Helicopter BLE" />
<TextView
android:id="@+id/deviceAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/deviceName"
android:textSize="14sp"
android:text="C3:7A:F4:6E:2F:D6" />
<ImageView
android:id="@+id/deviceRssi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:src="@drawable/signal_icon4" />
</androidx.constraintlayout.widget.ConstraintLayout>
-7
View File
@@ -1,7 +0,0 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.HeliBLE" parent="Theme.Material3.DayNight.NoActionBar">
<item name="baseBlockColor">@color/material_dynamic_neutral30</item>
<item name="selectedBlockColor">@color/material_dynamic_neutral20</item>
</style>
</resources>
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="baseBlockColor" type="reference" />
<attr name="selectedBlockColor" type="reference" />
</resources>
+5
View File
@@ -1,5 +1,10 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color> <color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color> <color name="white">#FFFFFFFF</color>
</resources> </resources>
+1 -3
View File
@@ -1,5 +1,3 @@
<resources> <resources>
<string name="app_name">HeliBLE</string> <string name="app_name">Digital Pilot</string>
<string name="r_slider_text">R%1$d: %2$d / 65536</string>
<string name="control_device_text">Устройство: %1$s</string>
</resources> </resources>
+3 -7
View File
@@ -1,9 +1,5 @@
<resources xmlns:tools="http://schemas.android.com/tools"> <?xml version="1.0" encoding="utf-8"?>
<!-- Base application theme. --> <resources>
<style name="Base.Theme.HeliBLE" parent="Theme.Material3.DayNight.NoActionBar">
<item name="baseBlockColor">@color/material_dynamic_neutral90</item>
<item name="selectedBlockColor">@color/material_dynamic_neutral80</item>
</style>
<style name="Theme.HeliBLE" parent="Base.Theme.HeliBLE" /> <style name="Theme.Testblue" parent="android:Theme.Material.Light.NoActionBar" />
</resources> </resources>
@@ -1,4 +1,4 @@
package com.listerk.helible package com.helible.pilot
import org.junit.Test import org.junit.Test
-6
View File
@@ -1,6 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.1.0' apply false
id 'com.android.library' version '8.1.0' apply false
id 'org.jetbrains.kotlin.android' version '1.8.20' apply false
}
+6
View File
@@ -0,0 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id("com.android.application") version "8.1.0" apply false
id("org.jetbrains.kotlin.android") version "1.8.10" apply false
id("org.jetbrains.kotlin.jvm") version "1.8.10" apply false
}
Binary file not shown.
+1 -1
View File
@@ -1,4 +1,4 @@
#Fri May 05 21:22:26 NOVT 2023 #Sun Aug 13 15:00:54 KRAT 2023
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
Vendored Regular → Executable
View File
+3 -2
View File
@@ -12,5 +12,6 @@ dependencyResolutionManagement {
mavenCentral() mavenCentral()
} }
} }
rootProject.name = "HeliBLE"
include ':app' rootProject.name = "pilot"
include(":app")