├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── colors.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ └── drawable
│ │ │ │ ├── ic_launcher_foreground.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── tdcolvin
│ │ │ │ └── bleserver
│ │ │ │ ├── ui
│ │ │ │ └── theme
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── BluetoothCTFServer.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── tdcolvin
│ │ │ └── bleserver
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── tdcolvin
│ │ └── bleserver
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── .idea
├── .gitignore
├── compiler.xml
├── kotlinc.xml
├── vcs.xml
├── studiobot.xml
├── AndroidProjectSystem.xml
├── migrations.xml
├── deploymentTargetSelector.xml
├── misc.xml
├── gradle.xml
└── runConfigurations.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle.kts
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BLEServer
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tdcolvin/BLEServer/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/studiobot.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/AndroidProjectSystem.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetSelector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tdcolvin/bleserver/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "BLEServer"
17 | include(":app")
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/test/java/com/tdcolvin/bleserver/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/tdcolvin/bleserver/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.tdcolvin.bleserver", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tdcolvin/bleserver/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tdcolvin/bleserver/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = Purple80,
20 | secondary = PurpleGrey80,
21 | tertiary = Pink80
22 | )
23 |
24 | private val LightColorScheme = lightColorScheme(
25 | primary = Purple40,
26 | secondary = PurpleGrey40,
27 | tertiary = Pink40
28 |
29 | /* Other default colors to override
30 | background = Color(0xFFFFFBFE),
31 | surface = Color(0xFFFFFBFE),
32 | onPrimary = Color.White,
33 | onSecondary = Color.White,
34 | onTertiary = Color.White,
35 | onBackground = Color(0xFF1C1B1F),
36 | onSurface = Color(0xFF1C1B1F),
37 | */
38 | )
39 |
40 | @Composable
41 | fun BLEServerTheme(
42 | darkTheme: Boolean = isSystemInDarkTheme(),
43 | // Dynamic color is available on Android 12+
44 | dynamicColor: Boolean = true,
45 | content: @Composable () -> Unit
46 | ) {
47 | val colorScheme = when {
48 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
49 | val context = LocalContext.current
50 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
51 | }
52 |
53 | darkTheme -> DarkColorScheme
54 | else -> LightColorScheme
55 | }
56 | val view = LocalView.current
57 | if (!view.isInEditMode) {
58 | SideEffect {
59 | val window = (view.context as Activity).window
60 | window.statusBarColor = colorScheme.primary.toArgb()
61 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
62 | }
63 | }
64 |
65 | MaterialTheme(
66 | colorScheme = colorScheme,
67 | typography = Typography,
68 | content = content
69 | )
70 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
7 |
9 |
11 |
13 |
14 |
15 |
19 |
21 |
23 |
25 |
26 |
27 |
28 |
31 |
32 |
33 |
43 |
44 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.application")
3 | id("org.jetbrains.kotlin.android")
4 | }
5 |
6 | android {
7 | namespace = "com.tdcolvin.bleserver"
8 | compileSdk = 35
9 |
10 | defaultConfig {
11 | applicationId = "com.tdcolvin.bleserver"
12 | minSdk = 28
13 | targetSdk = 35
14 | versionCode = 1
15 | versionName = "1.0"
16 |
17 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
18 | vectorDrawables {
19 | useSupportLibrary = true
20 | }
21 | }
22 |
23 | buildTypes {
24 | release {
25 | isMinifyEnabled = false
26 | proguardFiles(
27 | getDefaultProguardFile("proguard-android-optimize.txt"),
28 | "proguard-rules.pro"
29 | )
30 | }
31 | }
32 | compileOptions {
33 | sourceCompatibility = JavaVersion.VERSION_11
34 | targetCompatibility = JavaVersion.VERSION_11
35 | }
36 | kotlinOptions {
37 | jvmTarget = "11"
38 | }
39 | buildFeatures {
40 | compose = true
41 | }
42 | composeOptions {
43 | kotlinCompilerExtensionVersion = "1.5.15"
44 | }
45 | packaging {
46 | resources {
47 | excludes += "/META-INF/{AL2.0,LGPL2.1}"
48 | }
49 | }
50 | }
51 |
52 | dependencies {
53 |
54 | implementation("androidx.core:core-ktx:1.15.0")
55 | implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
56 | implementation("androidx.activity:activity-compose:1.10.1")
57 | implementation(platform("androidx.compose:compose-bom:2025.03.01"))
58 | implementation("androidx.compose.ui:ui")
59 | implementation("androidx.compose.ui:ui-graphics")
60 | implementation("androidx.compose.ui:ui-tooling-preview")
61 | implementation("androidx.compose.material3:material3")
62 | implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
63 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
64 | implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
65 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
66 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
67 | testImplementation("junit:junit:4.13.2")
68 | androidTestImplementation("androidx.test.ext:junit:1.2.1")
69 | androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
70 | androidTestImplementation(platform("androidx.compose:compose-bom:2025.03.01"))
71 | androidTestImplementation("androidx.compose.ui:ui-test-junit4")
72 | debugImplementation("androidx.compose.ui:ui-tooling")
73 | debugImplementation("androidx.compose.ui:ui-test-manifest")
74 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tdcolvin/bleserver/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver
2 |
3 | import android.Manifest
4 | import android.annotation.SuppressLint
5 | import android.app.Application
6 | import android.content.Context
7 | import android.content.pm.PackageManager
8 | import android.os.Build
9 | import android.os.Bundle
10 | import android.util.Log
11 | import androidx.activity.ComponentActivity
12 | import androidx.activity.compose.rememberLauncherForActivityResult
13 | import androidx.activity.compose.setContent
14 | import androidx.activity.result.contract.ActivityResultContracts
15 | import androidx.annotation.RequiresPermission
16 | import androidx.compose.foundation.layout.Column
17 | import androidx.compose.foundation.layout.fillMaxSize
18 | import androidx.compose.foundation.layout.safeContentPadding
19 | import androidx.compose.foundation.lazy.LazyColumn
20 | import androidx.compose.foundation.lazy.items
21 | import androidx.compose.material3.Button
22 | import androidx.compose.material3.MaterialTheme
23 | import androidx.compose.material3.Surface
24 | import androidx.compose.material3.Text
25 | import androidx.compose.runtime.Composable
26 | import androidx.compose.runtime.getValue
27 | import androidx.compose.runtime.mutableStateOf
28 | import androidx.compose.runtime.remember
29 | import androidx.compose.runtime.setValue
30 | import androidx.compose.ui.Modifier
31 | import androidx.compose.ui.platform.LocalContext
32 | import androidx.lifecycle.AndroidViewModel
33 | import androidx.lifecycle.compose.collectAsStateWithLifecycle
34 | import androidx.lifecycle.viewModelScope
35 | import androidx.lifecycle.viewmodel.compose.viewModel
36 | import com.tdcolvin.bleserver.ui.theme.BLEServerTheme
37 | import kotlinx.coroutines.Dispatchers
38 | import kotlinx.coroutines.Job
39 | import kotlinx.coroutines.delay
40 | import kotlinx.coroutines.flow.MutableStateFlow
41 | import kotlinx.coroutines.flow.asStateFlow
42 | import kotlinx.coroutines.flow.update
43 | import kotlinx.coroutines.launch
44 |
45 | class MainActivity : ComponentActivity() {
46 | private val allPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
47 | arrayOf(
48 | Manifest.permission.BLUETOOTH_CONNECT,
49 | Manifest.permission.BLUETOOTH_ADVERTISE
50 | )
51 | }
52 | else {
53 | arrayOf(
54 | Manifest.permission.BLUETOOTH_ADMIN,
55 | Manifest.permission.BLUETOOTH
56 | )
57 | }
58 |
59 | private fun haveAllPermissions(context: Context): Boolean {
60 | return allPermissions
61 | .all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
62 | }
63 |
64 | override fun onCreate(savedInstanceState: Bundle?) {
65 | super.onCreate(savedInstanceState)
66 | setContent {
67 | BLEServerTheme {
68 | // A surface container using the 'background' color from the theme
69 | Surface(
70 | modifier = Modifier.safeContentPadding().fillMaxSize(),
71 | color = MaterialTheme.colorScheme.background
72 | ) {
73 | ServerScreen()
74 | }
75 | }
76 | }
77 | }
78 |
79 | @SuppressLint("MissingPermission")
80 | @Composable
81 | fun ServerScreen(viewModel: ServerViewModel = viewModel()) {
82 | val context = LocalContext.current
83 | var allPermissionsGranted by remember {
84 | mutableStateOf (haveAllPermissions(context))
85 | }
86 |
87 | val uiState by viewModel.uiState.collectAsStateWithLifecycle()
88 |
89 | Column {
90 | if (allPermissionsGranted) {
91 | ServerStatus(
92 | serverRunning = uiState.serverRunning,
93 | onStartServer = { viewModel.startServer() },
94 | onStopServer = { viewModel.stopServer() }
95 | )
96 | NamesReceived(names = uiState.namesReceived)
97 | }
98 | else {
99 | val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestMultiplePermissions()) { granted ->
100 | allPermissionsGranted = granted.values.all { it }
101 | }
102 | Button(onClick = { launcher.launch(allPermissions)}) {
103 | Text("Grant Permission")
104 | }
105 | }
106 | }
107 | }
108 |
109 | @Composable
110 | fun ServerStatus(serverRunning: Boolean, onStartServer: () -> Unit, onStopServer: () -> Unit) {
111 | if (serverRunning) {
112 | Text("Server running")
113 | Button(onClick = onStopServer) {
114 | Text("Stop server")
115 | }
116 | }
117 | else {
118 | Text("Server not running")
119 | Button(onClick = onStartServer) {
120 | Text("Start server")
121 | }
122 | }
123 | }
124 |
125 | @Composable
126 | fun NamesReceived(names: List) {
127 | LazyColumn {
128 | items(names) { name ->
129 | Text(name)
130 | }
131 | }
132 | }
133 | }
134 |
135 | class ServerViewModel(application: Application): AndroidViewModel(application) {
136 | private val _uiState = MutableStateFlow(ServerUIState())
137 | val uiState = _uiState.asStateFlow()
138 |
139 | private val server: BluetoothCTFServer = BluetoothCTFServer(application)
140 |
141 | init {
142 | viewModelScope.launch {
143 | server.namesReceived.collect { names ->
144 | _uiState.update { it.copy(namesReceived = names) }
145 | }
146 | }
147 | }
148 |
149 | @RequiresPermission(allOf = [PERMISSION_BLUETOOTH_ADVERTISE, PERMISSION_BLUETOOTH_CONNECT])
150 | fun startServer() {
151 | viewModelScope.launch {
152 | server.startServer()
153 | startSendingNotifications()
154 | _uiState.update { it.copy(serverRunning = true) }
155 | }
156 | }
157 |
158 | @RequiresPermission(allOf = [PERMISSION_BLUETOOTH_ADVERTISE, PERMISSION_BLUETOOTH_CONNECT])
159 | fun stopServer() {
160 | viewModelScope.launch {
161 | sendingNotificationsJob?.cancel()
162 | server.stopServer()
163 | _uiState.update { it.copy(serverRunning = false) }
164 | }
165 | }
166 |
167 | private var sendingNotificationsJob: Job? = null
168 |
169 | @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
170 | private fun startSendingNotifications() {
171 | sendingNotificationsJob?.cancel()
172 |
173 | sendingNotificationsJob = viewModelScope.launch(Dispatchers.IO) {
174 | val notificationValues = listOf(
175 | "FLAG2 (1/3): it's",
176 | "FLAG2 (2/3): hammer",
177 | "FLAG2 (3/3): time",
178 | )
179 |
180 | var position = 0
181 | while(true) {
182 | try {
183 | server.sendNotification(notificationValues[position % notificationValues.size])
184 | }
185 | catch (e: Exception) {
186 | Log.e("Notification", "Error sending notification", e)
187 | return@launch
188 | }
189 |
190 | delay(5000)
191 | position++
192 | }
193 | }
194 | }
195 | }
196 |
197 | data class ServerUIState(
198 | val serverRunning: Boolean = false,
199 | val namesReceived: List = emptyList()
200 | )
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 | # SPDX-License-Identifier: Apache-2.0
19 | #
20 |
21 | ##############################################################################
22 | #
23 | # Gradle start up script for POSIX generated by Gradle.
24 | #
25 | # Important for running:
26 | #
27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28 | # noncompliant, but you have some other compliant shell such as ksh or
29 | # bash, then to run this script, type that shell name before the whole
30 | # command line, like:
31 | #
32 | # ksh Gradle
33 | #
34 | # Busybox and similar reduced shells will NOT work, because this script
35 | # requires all of these POSIX shell features:
36 | # * functions;
37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39 | # * compound commands having a testable exit status, especially «case»;
40 | # * various built-in commands including «command», «set», and «ulimit».
41 | #
42 | # Important for patching:
43 | #
44 | # (2) This script targets any POSIX shell, so it avoids extensions provided
45 | # by Bash, Ksh, etc; in particular arrays are avoided.
46 | #
47 | # The "traditional" practice of packing multiple parameters into a
48 | # space-separated string is a well documented source of bugs and security
49 | # problems, so this is (mostly) avoided, by progressively accumulating
50 | # options in "$@", and eventually passing that to Java.
51 | #
52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54 | # see the in-line comments for details.
55 | #
56 | # There are tweaks for specific operating systems such as AIX, CygWin,
57 | # Darwin, MinGW, and NonStop.
58 | #
59 | # (3) This script is generated from the Groovy template
60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61 | # within the Gradle project.
62 | #
63 | # You can find Gradle at https://github.com/gradle/gradle/.
64 | #
65 | ##############################################################################
66 |
67 | # Attempt to set APP_HOME
68 |
69 | # Resolve links: $0 may be a link
70 | app_path=$0
71 |
72 | # Need this for daisy-chained symlinks.
73 | while
74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75 | [ -h "$app_path" ]
76 | do
77 | ls=$( ls -ld "$app_path" )
78 | link=${ls#*' -> '}
79 | case $link in #(
80 | /*) app_path=$link ;; #(
81 | *) app_path=$APP_HOME$link ;;
82 | esac
83 | done
84 |
85 | # This is normally unused
86 | # shellcheck disable=SC2034
87 | APP_BASE_NAME=${0##*/}
88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
90 | ' "$PWD" ) || exit
91 |
92 | # Use the maximum available, or set MAX_FD != -1 to use that value.
93 | MAX_FD=maximum
94 |
95 | warn () {
96 | echo "$*"
97 | } >&2
98 |
99 | die () {
100 | echo
101 | echo "$*"
102 | echo
103 | exit 1
104 | } >&2
105 |
106 | # OS specific support (must be 'true' or 'false').
107 | cygwin=false
108 | msys=false
109 | darwin=false
110 | nonstop=false
111 | case "$( uname )" in #(
112 | CYGWIN* ) cygwin=true ;; #(
113 | Darwin* ) darwin=true ;; #(
114 | MSYS* | MINGW* ) msys=true ;; #(
115 | NONSTOP* ) nonstop=true ;;
116 | esac
117 |
118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
119 |
120 |
121 | # Determine the Java command to use to start the JVM.
122 | if [ -n "$JAVA_HOME" ] ; then
123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
124 | # IBM's JDK on AIX uses strange locations for the executables
125 | JAVACMD=$JAVA_HOME/jre/sh/java
126 | else
127 | JAVACMD=$JAVA_HOME/bin/java
128 | fi
129 | if [ ! -x "$JAVACMD" ] ; then
130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
131 |
132 | Please set the JAVA_HOME variable in your environment to match the
133 | location of your Java installation."
134 | fi
135 | else
136 | JAVACMD=java
137 | if ! command -v java >/dev/null 2>&1
138 | then
139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
140 |
141 | Please set the JAVA_HOME variable in your environment to match the
142 | location of your Java installation."
143 | fi
144 | fi
145 |
146 | # Increase the maximum file descriptors if we can.
147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
148 | case $MAX_FD in #(
149 | max*)
150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
151 | # shellcheck disable=SC2039,SC3045
152 | MAX_FD=$( ulimit -H -n ) ||
153 | warn "Could not query maximum file descriptor limit"
154 | esac
155 | case $MAX_FD in #(
156 | '' | soft) :;; #(
157 | *)
158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
159 | # shellcheck disable=SC2039,SC3045
160 | ulimit -n "$MAX_FD" ||
161 | warn "Could not set maximum file descriptor limit to $MAX_FD"
162 | esac
163 | fi
164 |
165 | # Collect all arguments for the java command, stacking in reverse order:
166 | # * args from the command line
167 | # * the main class name
168 | # * -classpath
169 | # * -D...appname settings
170 | # * --module-path (only if needed)
171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
172 |
173 | # For Cygwin or MSYS, switch paths to Windows format before running java
174 | if "$cygwin" || "$msys" ; then
175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
177 |
178 | JAVACMD=$( cygpath --unix "$JAVACMD" )
179 |
180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
181 | for arg do
182 | if
183 | case $arg in #(
184 | -*) false ;; # don't mess with options #(
185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
186 | [ -e "$t" ] ;; #(
187 | *) false ;;
188 | esac
189 | then
190 | arg=$( cygpath --path --ignore --mixed "$arg" )
191 | fi
192 | # Roll the args list around exactly as many times as the number of
193 | # args, so each arg winds up back in the position where it started, but
194 | # possibly modified.
195 | #
196 | # NB: a `for` loop captures its iteration list before it begins, so
197 | # changing the positional parameters here affects neither the number of
198 | # iterations, nor the values presented in `arg`.
199 | shift # remove old arg
200 | set -- "$@" "$arg" # push replacement arg
201 | done
202 | fi
203 |
204 |
205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
207 |
208 | # Collect all arguments for the java command:
209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
210 | # and any embedded shellness will be escaped.
211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
212 | # treated as '${Hostname}' itself on the command line.
213 |
214 | set -- \
215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
216 | -classpath "$CLASSPATH" \
217 | org.gradle.wrapper.GradleWrapperMain \
218 | "$@"
219 |
220 | # Stop when "xargs" is not available.
221 | if ! command -v xargs >/dev/null 2>&1
222 | then
223 | die "xargs is not available"
224 | fi
225 |
226 | # Use "xargs" to parse quoted args.
227 | #
228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
229 | #
230 | # In Bash we could simply go:
231 | #
232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
233 | # set -- "${ARGS[@]}" "$@"
234 | #
235 | # but POSIX shell has neither arrays nor command substitution, so instead we
236 | # post-process each arg (as a line of input to sed) to backslash-escape any
237 | # character that might be a shell metacharacter, then use eval to reverse
238 | # that process (while maintaining the separation between arguments), and wrap
239 | # the whole thing up as a single "set" statement.
240 | #
241 | # This will of course break if any of these variables contains a newline or
242 | # an unmatched quote.
243 | #
244 |
245 | eval "set -- $(
246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
247 | xargs -n1 |
248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
249 | tr '\n' ' '
250 | )" '"$@"'
251 |
252 | exec "$JAVACMD" "$@"
253 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tdcolvin/bleserver/BluetoothCTFServer.kt:
--------------------------------------------------------------------------------
1 | package com.tdcolvin.bleserver
2 |
3 | import android.Manifest
4 | import android.bluetooth.BluetoothDevice
5 | import android.bluetooth.BluetoothGatt
6 | import android.bluetooth.BluetoothGattCharacteristic
7 | import android.bluetooth.BluetoothGattDescriptor
8 | import android.bluetooth.BluetoothGattServer
9 | import android.bluetooth.BluetoothGattServerCallback
10 | import android.bluetooth.BluetoothGattService
11 | import android.bluetooth.BluetoothManager
12 | import android.bluetooth.le.AdvertiseCallback
13 | import android.bluetooth.le.AdvertiseData
14 | import android.bluetooth.le.AdvertiseSettings
15 | import android.bluetooth.le.BluetoothLeAdvertiser
16 | import android.content.Context
17 | import androidx.annotation.RequiresPermission
18 | import kotlinx.coroutines.Dispatchers
19 | import kotlinx.coroutines.flow.MutableStateFlow
20 | import kotlinx.coroutines.flow.update
21 | import kotlinx.coroutines.withContext
22 | import java.util.UUID
23 | import kotlin.coroutines.resume
24 | import kotlin.coroutines.suspendCoroutine
25 |
26 | const val CTF_SERVICE_UUID = "8c380000-10bd-4fdb-ba21-1922d6cf860d"
27 | const val PASSWORD_CHARACTERISTIC_UUID = "8c380001-10bd-4fdb-ba21-1922d6cf860d"
28 | const val NAME_CHARACTERISTIC_UUID = "8c380002-10bd-4fdb-ba21-1922d6cf860d"
29 | const val FLAG_2_CHARACTERISTIC_UUID = "8c380003-10bd-4fdb-ba21-1922d6cf860d"
30 |
31 | // client characteristic configuration descriptor
32 | const val CCCD_UUID = "00002902-0000-1000-8000-00805f9b34fb"
33 |
34 | //These fields are marked as API >= 31 in the Manifest class, so we can't use those without warning.
35 | //So we create our own, which prevents over-suppression of the Linter
36 | const val PERMISSION_BLUETOOTH_ADVERTISE = "android.permission.BLUETOOTH_ADVERTISE"
37 | const val PERMISSION_BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT"
38 |
39 | class BluetoothCTFServer(private val context: Context) {
40 | private val bluetooth = context.getSystemService(Context.BLUETOOTH_SERVICE)
41 | as? BluetoothManager
42 | ?: throw Exception("This device doesn't support Bluetooth")
43 |
44 | private val serviceUuid = UUID.fromString(CTF_SERVICE_UUID)
45 | private val passwordCharUuid = UUID.fromString(PASSWORD_CHARACTERISTIC_UUID)
46 | private val nameCharUuid = UUID.fromString(NAME_CHARACTERISTIC_UUID)
47 | private val flag2CharUuid = UUID.fromString(FLAG_2_CHARACTERISTIC_UUID)
48 |
49 | private var server: BluetoothGattServer? = null
50 | private var ctfService: BluetoothGattService? = null
51 |
52 | private var advertiseCallback: AdvertiseCallback? = null
53 | private val isServerListening: MutableStateFlow = MutableStateFlow(null)
54 | private val devicesToNotify: MutableSet = mutableSetOf()
55 |
56 | private val preparedWrites = HashMap()
57 |
58 | val namesReceived = MutableStateFlow(emptyList())
59 |
60 | @RequiresPermission(allOf = [PERMISSION_BLUETOOTH_CONNECT, PERMISSION_BLUETOOTH_ADVERTISE])
61 | suspend fun startServer() = withContext(Dispatchers.IO) {
62 | //If server already exists, we don't need to create one
63 | if (server != null) {
64 | return@withContext
65 | }
66 |
67 | startHandlingIncomingConnections()
68 | startAdvertising()
69 | }
70 |
71 | @RequiresPermission(allOf = [PERMISSION_BLUETOOTH_CONNECT, PERMISSION_BLUETOOTH_ADVERTISE])
72 | suspend fun stopServer() = withContext(Dispatchers.IO) {
73 | //if no server, nothing to do
74 | if (server == null) {
75 | return@withContext
76 | }
77 |
78 | devicesToNotify.clear()
79 |
80 | stopAdvertising()
81 | stopHandlingIncomingConnections()
82 | }
83 |
84 | @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
85 | suspend fun sendNotification(notification: String) = withContext(Dispatchers.IO) {
86 | val characteristic = ctfService?.getCharacteristic(flag2CharUuid)
87 | ?: throw Exception("Characteristic not found")
88 |
89 | characteristic.value = notification.encodeToByteArray()
90 |
91 | devicesToNotify.forEach { device ->
92 | server?.notifyCharacteristicChanged(
93 | device,
94 | characteristic,
95 | false
96 | )
97 | }
98 | }
99 |
100 | @RequiresPermission(PERMISSION_BLUETOOTH_ADVERTISE)
101 | private suspend fun startAdvertising() {
102 | val advertiser: BluetoothLeAdvertiser = bluetooth.adapter.bluetoothLeAdvertiser
103 | ?: throw Exception("This device is not able to advertise")
104 |
105 | //if already advertising, ignore
106 | if (advertiseCallback != null) {
107 | return
108 | }
109 |
110 | val settings = AdvertiseSettings.Builder()
111 | .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
112 | .setConnectable(true)
113 | .setTimeout(0)
114 | .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
115 | .build()
116 |
117 | val data = AdvertiseData.Builder()
118 | .setIncludeDeviceName(true)
119 | .setIncludeTxPowerLevel(false)
120 | // .addServiceUuid(ParcelUuid(serviceUuid))
121 | .build()
122 |
123 | advertiseCallback = suspendCoroutine { continuation ->
124 | val advertiseCallback = object: AdvertiseCallback() {
125 | override fun onStartSuccess(settingsInEffect: AdvertiseSettings?) {
126 | super.onStartSuccess(settingsInEffect)
127 | continuation.resume(this)
128 | }
129 |
130 | override fun onStartFailure(errorCode: Int) {
131 | super.onStartFailure(errorCode)
132 | throw Exception("Unable to start advertising, errorCode: $errorCode")
133 | }
134 | }
135 | advertiser.startAdvertising(settings, data, advertiseCallback)
136 | }
137 | }
138 |
139 | @RequiresPermission(PERMISSION_BLUETOOTH_ADVERTISE)
140 | private fun stopAdvertising() {
141 | val advertiser: BluetoothLeAdvertiser = bluetooth.adapter.bluetoothLeAdvertiser
142 | ?: throw Exception("This device is not able to advertise")
143 |
144 | //if not currently advertising, ignore
145 | advertiseCallback?.let {
146 | advertiser.stopAdvertising(it)
147 | advertiseCallback = null
148 | }
149 | }
150 |
151 | @RequiresPermission(PERMISSION_BLUETOOTH_CONNECT)
152 | private fun startHandlingIncomingConnections() {
153 | server = bluetooth.openGattServer(context, object: BluetoothGattServerCallback() {
154 | override fun onConnectionStateChange(
155 | device: BluetoothDevice,
156 | status: Int,
157 | newState: Int
158 | ) {
159 | super.onConnectionStateChange(device, status, newState)
160 |
161 | if (newState == BluetoothGatt.STATE_DISCONNECTED) {
162 | devicesToNotify.remove(device)
163 | }
164 | }
165 |
166 | override fun onServiceAdded(status: Int, service: BluetoothGattService?) {
167 | super.onServiceAdded(status, service)
168 | isServerListening.value = true
169 | }
170 |
171 | @RequiresPermission(PERMISSION_BLUETOOTH_CONNECT)
172 | override fun onCharacteristicReadRequest(
173 | device: BluetoothDevice?,
174 | requestId: Int,
175 | offset: Int,
176 | characteristic: BluetoothGattCharacteristic?
177 | ) {
178 | super.onCharacteristicReadRequest(device, requestId, offset, characteristic)
179 | server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, "FLAG1:kangaroo".encodeToByteArray())
180 | }
181 |
182 | @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
183 | override fun onDescriptorWriteRequest(
184 | device: BluetoothDevice,
185 | requestId: Int,
186 | descriptor: BluetoothGattDescriptor,
187 | preparedWrite: Boolean,
188 | responseNeeded: Boolean,
189 | offset: Int,
190 | value: ByteArray
191 | ) {
192 | super.onDescriptorWriteRequest(
193 | device,
194 | requestId,
195 | descriptor,
196 | preparedWrite,
197 | responseNeeded,
198 | offset,
199 | value
200 | )
201 |
202 | if (
203 | descriptor.uuid == UUID.fromString(CCCD_UUID) &&
204 | descriptor.characteristic.uuid == flag2CharUuid
205 | ) {
206 | if (value.contentEquals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) {
207 | devicesToNotify.add(device)
208 | }
209 | else if (value.contentEquals(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) {
210 | devicesToNotify.remove(device)
211 | }
212 | else {
213 | server?.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null)
214 | return
215 | }
216 |
217 | if (responseNeeded) {
218 | server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null)
219 | return
220 | }
221 | }
222 | else {
223 | server?.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null)
224 | return
225 | }
226 | }
227 |
228 | @RequiresPermission(PERMISSION_BLUETOOTH_CONNECT)
229 | override fun onCharacteristicWriteRequest(
230 | device: BluetoothDevice,
231 | requestId: Int,
232 | characteristic: BluetoothGattCharacteristic,
233 | preparedWrite: Boolean,
234 | responseNeeded: Boolean,
235 | offset: Int,
236 | value: ByteArray
237 | ) {
238 | super.onCharacteristicWriteRequest(
239 | device,
240 | requestId,
241 | characteristic,
242 | preparedWrite,
243 | responseNeeded,
244 | offset,
245 | value
246 | )
247 | super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value)
248 |
249 | if(preparedWrite) {
250 | val bytes = preparedWrites.getOrDefault(requestId, byteArrayOf())
251 | preparedWrites[requestId] = bytes.plus(value)
252 | }
253 | else {
254 | namesReceived.update { it.plus(String(value)) }
255 | }
256 |
257 | if(responseNeeded) {
258 | server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, byteArrayOf())
259 | }
260 | }
261 |
262 | override fun onExecuteWrite(
263 | device: BluetoothDevice?,
264 | requestId: Int,
265 | execute: Boolean
266 | ) {
267 | super.onExecuteWrite(device, requestId, execute)
268 | val bytes = preparedWrites.remove(requestId)
269 | if (execute && bytes != null) {
270 | namesReceived.update { it.plus(String(bytes)) }
271 | }
272 | }
273 | })
274 |
275 | val service = BluetoothGattService(serviceUuid, BluetoothGattService.SERVICE_TYPE_PRIMARY)
276 |
277 | val passwordCharacteristic = BluetoothGattCharacteristic(
278 | passwordCharUuid,
279 | BluetoothGattCharacteristic.PROPERTY_READ,
280 | BluetoothGattCharacteristic.PERMISSION_READ
281 | )
282 |
283 | val nameCharacteristic = BluetoothGattCharacteristic(
284 | nameCharUuid,
285 | BluetoothGattCharacteristic.PROPERTY_WRITE,
286 | BluetoothGattCharacteristic.PERMISSION_WRITE
287 | )
288 |
289 | val flag2Characteristic = BluetoothGattCharacteristic(
290 | flag2CharUuid,
291 | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
292 | BluetoothGattCharacteristic.PERMISSION_READ
293 | )
294 | val cccDescriptor = BluetoothGattDescriptor(
295 | UUID.fromString(CCCD_UUID),
296 | BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE
297 | )
298 | flag2Characteristic.addDescriptor(cccDescriptor)
299 |
300 | service.addCharacteristic(passwordCharacteristic)
301 | service.addCharacteristic(nameCharacteristic)
302 | service.addCharacteristic(flag2Characteristic)
303 |
304 | server?.addService(service)
305 | ctfService = service
306 | }
307 |
308 | @RequiresPermission(PERMISSION_BLUETOOTH_CONNECT)
309 | private fun stopHandlingIncomingConnections() {
310 | ctfService?.let {
311 | server?.removeService(it)
312 | ctfService = null
313 | }
314 | }
315 | }
--------------------------------------------------------------------------------