├── .circleci └── config.yml ├── .gitignore ├── .idea ├── codeStyles │ └── Project.xml ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml ├── modules.xml └── vcs.xml ├── Bluetooth-LE-Library---Android.iml ├── LICENSE ├── README.md ├── apkdetails.sh ├── bluetooth-le-library.iml ├── build.gradle ├── buildconstants ├── android-sdk-versions.gradle └── dependency-versions.gradle ├── buildsystem ├── android-defaults.gradle ├── apkdetails │ └── apkdetails-1.2.2.jar ├── codequality │ └── lint.xml ├── common-methods.gradle ├── generate_dependency_hashfile.sh ├── kover.gradle ├── multidex │ └── multidex.pro ├── printcoverage.gradle ├── proguard-rules │ ├── dagger2-rules.pro │ ├── gson-rules.pro │ └── kotlin-rules.pro └── signing_keys │ └── debug.keystore ├── circle.yml ├── dist ├── BluetoothLeLibrary-0.0.1-javadoc.jar └── BluetoothLeLibrary-0.0.1.jar ├── documents ├── Bluetooth_UUIDs.ods └── COMPANY_IDENTIFIERS.ods ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── image_assets ├── feature_graphic.png ├── screenshots │ ├── phone_screenshot_1.png │ ├── phone_screenshot_2.png │ ├── phone_screenshot_3.png │ └── phone_screenshot_4.png └── web_hi_res_512.png ├── library ├── .gitignore ├── build.gradle ├── ic_launcher-web.png ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── dev │ │ └── alt236 │ │ └── bluetoothlelib │ │ ├── device │ │ ├── BluetoothLeDevice.java │ │ ├── BluetoothService.java │ │ ├── adrecord │ │ │ ├── AdRecord.java │ │ │ └── AdRecordStore.java │ │ └── beacon │ │ │ ├── BeaconDevice.java │ │ │ ├── BeaconManufacturerData.java │ │ │ ├── BeaconType.java │ │ │ ├── BeaconUtils.java │ │ │ └── ibeacon │ │ │ ├── IBeaconConstants.java │ │ │ ├── IBeaconDevice.java │ │ │ ├── IBeaconDistanceDescriptor.java │ │ │ ├── IBeaconManufacturerData.java │ │ │ └── IBeaconUtils.java │ │ ├── resolvers │ │ ├── BluetoothClassResolver.java │ │ ├── CompanyIdentifierResolver.java │ │ └── GattAttributeResolver.java │ │ └── util │ │ ├── AdRecordUtils.java │ │ ├── ByteUtils.java │ │ └── LimitedLinkHashMap.java │ └── test │ └── java │ └── dev │ └── alt236 │ └── bluetoothlelib │ ├── device │ └── beacon │ │ ├── BeaconUtilsTest.java │ │ └── ibeacon │ │ ├── IBeaconManufacturerDataTest.java │ │ └── IBeaconUtilsTest.java │ ├── resolvers │ └── GattAttributeResolverTest.java │ └── util │ ├── AdRecordUtilsTest.java │ └── ByteUtilsTest.java ├── sample_app ├── .gitignore ├── apk_v1.1.1.apk ├── app_v1.1.0.apk ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── uk │ │ │ └── co │ │ │ └── alt236 │ │ │ └── btlescan │ │ │ ├── containers │ │ │ └── BluetoothLeDeviceStore.kt │ │ │ ├── kt │ │ │ └── ByteArrayExt.kt │ │ │ ├── permission │ │ │ ├── BluetoothPermissionCheck.kt │ │ │ └── PermissionDeniedDialogFragment.kt │ │ │ ├── services │ │ │ ├── BluetoothLeService.java │ │ │ ├── LocalBinder.kt │ │ │ └── State.kt │ │ │ ├── ui │ │ │ ├── common │ │ │ │ ├── IntentReceiverCompat.kt │ │ │ │ ├── Navigation.kt │ │ │ │ └── recyclerview │ │ │ │ │ ├── BaseRecyclerViewAdapter.kt │ │ │ │ │ ├── BaseViewBinder.kt │ │ │ │ │ ├── BaseViewHolder.kt │ │ │ │ │ ├── RecyclerViewBinderCore.java │ │ │ │ │ └── RecyclerViewItem.kt │ │ │ ├── control │ │ │ │ ├── DeviceControlActivity.java │ │ │ │ ├── Exporter.java │ │ │ │ ├── GattDataAdapterFactory.java │ │ │ │ ├── State.kt │ │ │ │ └── View.kt │ │ │ ├── details │ │ │ │ ├── DetailsRecyclerAdapter.kt │ │ │ │ ├── DeviceDetailsActivity.java │ │ │ │ ├── RecyclerViewCoreFactory.java │ │ │ │ └── recyclerview │ │ │ │ │ ├── binder │ │ │ │ │ ├── AdRecordBinder.kt │ │ │ │ │ ├── DeviceInfoBinder.kt │ │ │ │ │ ├── HeaderBinder.kt │ │ │ │ │ ├── IBeaconBinder.kt │ │ │ │ │ ├── RssiBinder.kt │ │ │ │ │ └── TextBinder.kt │ │ │ │ │ ├── holder │ │ │ │ │ ├── AdRecordHolder.kt │ │ │ │ │ ├── DeviceInfoHolder.kt │ │ │ │ │ ├── HeaderHolder.kt │ │ │ │ │ ├── IBeaconHolder.kt │ │ │ │ │ ├── RssiInfoHolder.kt │ │ │ │ │ └── TextHolder.kt │ │ │ │ │ └── model │ │ │ │ │ ├── AdRecordItem.kt │ │ │ │ │ ├── DeviceInfoItem.kt │ │ │ │ │ ├── HeaderItem.kt │ │ │ │ │ ├── IBeaconItem.kt │ │ │ │ │ ├── RssiItem.kt │ │ │ │ │ └── TextItem.kt │ │ │ └── main │ │ │ │ ├── DeviceRecyclerAdapter.kt │ │ │ │ ├── DialogFactory.java │ │ │ │ ├── MainActivity.java │ │ │ │ ├── RecyclerViewCoreFactory.java │ │ │ │ ├── View.kt │ │ │ │ ├── recyclerview │ │ │ │ ├── binder │ │ │ │ │ ├── CommonBinding.java │ │ │ │ │ ├── IBeaconBinder.java │ │ │ │ │ └── LeDeviceBinder.kt │ │ │ │ ├── holder │ │ │ │ │ ├── CommonDeviceHolder.kt │ │ │ │ │ ├── IBeaconHolder.kt │ │ │ │ │ └── LeDeviceHolder.kt │ │ │ │ └── model │ │ │ │ │ ├── IBeaconItem.kt │ │ │ │ │ └── LeDeviceItem.kt │ │ │ │ └── share │ │ │ │ ├── CsvFileWriter.kt │ │ │ │ ├── CsvWriterHelper.java │ │ │ │ └── Sharer.java │ │ │ └── util │ │ │ ├── BluetoothAdapterWrapper.kt │ │ │ ├── BluetoothLeScanner.kt │ │ │ ├── Constants.java │ │ │ ├── TimeFormatter.java │ │ │ └── UtcDateFormatter.kt │ └── res │ │ ├── drawable-hdpi │ │ ├── ic_action_share.png │ │ └── ic_bluetooth.png │ │ ├── drawable-mdpi │ │ ├── ic_action_share.png │ │ └── ic_bluetooth.png │ │ ├── drawable-xhdpi │ │ ├── ic_action_share.png │ │ ├── ic_bluetooth.png │ │ ├── ic_bluetooth_on.png │ │ └── ic_device_ibeacon.png │ │ ├── drawable-xxhdpi │ │ ├── ic_action_share.png │ │ └── ic_bluetooth.png │ │ ├── drawable-xxxhdpi │ │ ├── ic_action_share.png │ │ └── ic_bluetooth.png │ │ ├── layout │ │ ├── actionbar_progress_indeterminate.xml │ │ ├── activity_details.xml │ │ ├── activity_gatt_services.xml │ │ ├── activity_main.xml │ │ ├── dialog_textview.xml │ │ ├── list_item_device_ibeacon.xml │ │ ├── list_item_device_le.xml │ │ ├── list_item_view_adrecord.xml │ │ ├── list_item_view_device_info.xml │ │ ├── list_item_view_header.xml │ │ ├── list_item_view_ibeacon_details.xml │ │ ├── list_item_view_rssi_info.xml │ │ ├── list_item_view_textview.xml │ │ └── viewpart_list_item_device_common.xml │ │ ├── menu │ │ ├── details.xml │ │ ├── gatt_services.xml │ │ └── main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-sw600dp │ │ └── dimens.xml │ │ ├── values-sw720dp-land │ │ └── dimens.xml │ │ ├── values-v21 │ │ └── styles.xml │ │ ├── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ │ └── xml │ │ └── share_provider_filepaths.xml │ └── test │ └── java │ └── uk │ └── co │ └── alt236 │ └── btlescan │ └── containers │ └── BluetoothLeDeviceStoreTest.java └── settings.gradle /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | xmlns:android 14 | 15 | ^$ 16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 | 24 | xmlns:.* 25 | 26 | ^$ 27 | 28 | 29 | BY_NAME 30 | 31 |
32 |
33 | 34 | 35 | 36 | .*:id 37 | 38 | http://schemas.android.com/apk/res/android 39 | 40 | 41 | 42 |
43 |
44 | 45 | 46 | 47 | .*:name 48 | 49 | http://schemas.android.com/apk/res/android 50 | 51 | 52 | 53 |
54 |
55 | 56 | 57 | 58 | name 59 | 60 | ^$ 61 | 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | style 70 | 71 | ^$ 72 | 73 | 74 | 75 |
76 |
77 | 78 | 79 | 80 | .* 81 | 82 | ^$ 83 | 84 | 85 | BY_NAME 86 | 87 |
88 |
89 | 90 | 91 | 92 | .* 93 | 94 | http://schemas.android.com/apk/res/android 95 | 96 | 97 | ANDROID_ATTRIBUTE_ORDER 98 | 99 |
100 |
101 | 102 | 103 | 104 | .* 105 | 106 | .* 107 | 108 | 109 | BY_NAME 110 | 111 |
112 |
113 |
114 |
115 |
116 |
-------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | Android 51 | 52 | 53 | Android > Lint > Correctness 54 | 55 | 56 | Android > Lint > Performance 57 | 58 | 59 | CorrectnessLintAndroid 60 | 61 | 62 | General 63 | 64 | 65 | LintAndroid 66 | 67 | 68 | 69 | 70 | Android 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 82 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Bluetooth-LE-Library---Android.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /apkdetails.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | set -o xtrace 5 | java -jar ./buildsystem/apkdetails/apkdetails-1.2.2.jar "$@" 6 | set +o xtrace -------------------------------------------------------------------------------- /bluetooth-le-library.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | apply from: "${project.rootDir}/buildconstants/android-sdk-versions.gradle" 5 | apply from: "${project.rootDir}/buildconstants/dependency-versions.gradle" 6 | 7 | repositories { 8 | google() 9 | mavenCentral() 10 | gradlePluginPortal() 11 | } 12 | 13 | dependencies { 14 | classpath libs.android.build.tools.gradle 15 | classpath libs.kotlin.gradle.plugin 16 | } 17 | } 18 | 19 | plugins { 20 | alias(libs.plugins.hilt.android) apply false 21 | alias(libs.plugins.kotlin.android) apply false 22 | alias(libs.plugins.gradle.ktlint) 23 | alias(libs.plugins.test.logger) 24 | alias(libs.plugins.kover) 25 | } 26 | 27 | apply from: "$rootDir/buildsystem/kover.gradle" 28 | apply from: "$rootDir/buildsystem/printcoverage.gradle" 29 | 30 | allprojects { 31 | repositories { 32 | google() 33 | mavenCentral() 34 | } 35 | 36 | apply plugin: "org.jlleitschuh.gradle.ktlint" 37 | apply plugin: "com.adarshr.test-logger" 38 | 39 | testlogger { 40 | showStandardStreams true 41 | } 42 | 43 | ktlint { 44 | version.set("1.4.1") 45 | } 46 | 47 | apply from: "${project.rootDir}/buildconstants/android-sdk-versions.gradle" 48 | apply from: "${project.rootDir}/buildconstants/dependency-versions.gradle" 49 | apply from: "${project.rootDir}/buildsystem/common-methods.gradle" 50 | } 51 | -------------------------------------------------------------------------------- /buildconstants/android-sdk-versions.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | min_sdk_version = 21 3 | target_sdk_version = 34 4 | compile_sdk_version = 34 5 | } -------------------------------------------------------------------------------- /buildconstants/dependency-versions.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | jacoco_version = "0.8.8" 3 | } -------------------------------------------------------------------------------- /buildsystem/android-defaults.gradle: -------------------------------------------------------------------------------- 1 | // The versions are defined in "${project.rootDir}/buildconstants/android-sdk-versions.gradle" 2 | 3 | apply plugin: 'jacoco' 4 | 5 | jacoco { 6 | toolVersion = jacoco_version 7 | } 8 | 9 | android { 10 | compileSdkVersion compile_sdk_version 11 | 12 | defaultConfig { 13 | minSdkVersion min_sdk_version 14 | targetSdkVersion target_sdk_version 15 | 16 | multiDexEnabled false 17 | multiDexKeepProguard file("${project.rootDir}/buildsystem/multidex/multidex.pro") 18 | 19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 20 | } 21 | 22 | buildTypes { 23 | release { 24 | minifyEnabled true 25 | 26 | // PROGUARD 27 | def proguardRuleFiles = collectCommonProguardRules() 28 | proguardRuleFiles.add(0, getDefaultProguardFile('proguard-android.txt')) 29 | proguardRuleFiles.add(1, 'proguard-rules.pro') 30 | logger.warn("Common proguard files: $proguardRuleFiles") 31 | 32 | proguardFiles proguardRuleFiles.toArray() 33 | } 34 | 35 | debug { 36 | minifyEnabled false 37 | 38 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 39 | } 40 | } 41 | 42 | compileOptions { 43 | sourceCompatibility JavaVersion.VERSION_17 44 | targetCompatibility JavaVersion.VERSION_17 45 | } 46 | 47 | kotlinOptions { 48 | jvmTarget = 17 49 | } 50 | 51 | androidResources { 52 | noCompress 'zip' 53 | } 54 | lint { 55 | lintConfig file("$rootDir/buildsystem/codequality/lint.xml") 56 | } 57 | 58 | testOptions { 59 | execution 'ANDROIDX_TEST_ORCHESTRATOR' 60 | animationsDisabled = true 61 | 62 | unitTests { 63 | //returnDefaultValues = true 64 | includeAndroidResources = true 65 | } 66 | } 67 | 68 | } 69 | 70 | task jacocoTestReport2(type: JacocoReport) { 71 | 72 | reports { 73 | xml.required.set(true) 74 | html.required.set(true) 75 | } 76 | 77 | def fileFilter = ['jdk.internal.*', 78 | 'android/**/*.*', 79 | '**/R.class', 80 | '**/R$*.class', 81 | '**/BuildConfig.*', 82 | '**/Manifest*.*', 83 | '**/*Test*.*', 84 | '**/*$ViewInjector*.*', 85 | '**/*$ViewBinder*.*', 86 | // DAGGER 2 87 | '**/*_*Factory*.*', 88 | '**/*_MembersInjector*.*', 89 | '**/*_MembersInjector.class', 90 | '**/*Module*.*', 91 | '**/Dagger*Component$Builder.class', 92 | '**/Dagger*Component*.*'] 93 | 94 | def mainSrc = "$project.projectDir/src/main/java" 95 | 96 | def javaClasses = fileTree( 97 | dir: "$buildDir/intermediates/classes/", 98 | excludes: fileFilter 99 | ) 100 | 101 | def kotlinClasses = fileTree( 102 | dir: "$buildDir/tmp/kotlin-classes/", 103 | excludes: fileFilter 104 | ) 105 | 106 | classDirectories.setFrom(files([javaClasses], [kotlinClasses])) 107 | sourceDirectories.setFrom(files(mainSrc)) 108 | executionData.setFrom(fileTree(dir: "$buildDir", 109 | includes: ['jacoco/*.exec', 'connected/*.ec'] 110 | )) 111 | 112 | reports { 113 | xml.required.set(true) 114 | html.required.set(true) 115 | } 116 | } 117 | 118 | tasks.withType(Test) { 119 | jacoco.includeNoLocationClasses = false 120 | } 121 | -------------------------------------------------------------------------------- /buildsystem/apkdetails/apkdetails-1.2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/buildsystem/apkdetails/apkdetails-1.2.2.jar -------------------------------------------------------------------------------- /buildsystem/codequality/lint.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /buildsystem/common-methods.gradle: -------------------------------------------------------------------------------- 1 | def execGitHashShort() { 2 | return cleanString('git rev-parse --short HEAD'.execute().text) 3 | } 4 | 5 | def execGitHash() { 6 | return cleanString('git rev-parse HEAD'.execute().text) 7 | } 8 | 9 | def execGitBranch() { 10 | return cleanString('git show -s --pretty=%d HEAD'.execute().text) 11 | } 12 | 13 | def execGitCommitDate() { 14 | final String cmd = "git show -s --format=%ci " + this.execGitHash() 15 | return cleanString(cmd.execute().text) 16 | } 17 | 18 | def execGitLog(int items) { 19 | final String cmd = "git log -n " + items + " --abbrev-commit --pretty=oneline" 20 | return cmd.execute().text 21 | } 22 | 23 | def getBuildNumber() { 24 | def buildNumberVariable = "CIRCLE_BUILD_NUM" 25 | def buildNumberValue = System.getenv(buildNumberVariable) 26 | 27 | if (buildNumberValue != null && !buildNumberValue.isEmpty()) { 28 | return buildNumberValue as Integer 29 | } else { 30 | return 1 31 | } 32 | } 33 | 34 | def isRunningOnCi() { 35 | def envVariable = "CI" 36 | return Boolean.parseBoolean(System.getenv(envVariable) ?: "false") 37 | } 38 | 39 | def cleanString(final String text) { 40 | return text.trim().replaceAll('/', '_').replaceAll('-', '_') 41 | } 42 | 43 | def quoteString(final String str) { 44 | final String quote = "\"" 45 | 46 | if (str.length() > 0) { 47 | if (str.startsWith(quote) && str.endsWith(quote)) { 48 | return str 49 | } else { 50 | return quote + str + quote 51 | } 52 | } else { 53 | return quote + quote 54 | } 55 | } 56 | 57 | 58 | 59 | def getLastGitCommitMessage() { 60 | return 'git log -1 --pretty=%B'.execute().text.trim() 61 | } 62 | 63 | def collectCommonProguardRules() { 64 | def proguardFileDirectory = "${project.rootDir}/buildsystem/proguard-rules/" 65 | 66 | def proguardFileSet = fileTree(proguardFileDirectory).filter { it.isFile() }.files 67 | if(proguardFileSet.isEmpty()) { 68 | throw new IllegalStateException("No proguard rules found in $proguardFileDirectory") 69 | } 70 | 71 | return proguardFileSet.toList().sort() 72 | } 73 | 74 | 75 | def getPropertySafe(prop, fallback) { 76 | rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback 77 | } 78 | 79 | ext { 80 | execGitHashShort = this.&execGitHashShort 81 | execGitHash = this.&execGitHash 82 | execGitBranch = this.&execGitBranch 83 | execGitCommitDate = this.&execGitCommitDate 84 | execGitLog = this.&execGitLog 85 | isRunningOnCi = this.&isRunningOnCi 86 | getLibVersions = this.&getLibVersions 87 | quoteString = this."eString 88 | getBuildNumber = this.&getBuildNumber 89 | getLastGitCommitMessage = this.&getLastGitCommitMessage 90 | shouldSkipFlakyRobolectricTests = this.&shouldSkipFlakyRobolectricTests 91 | collectCommonProguardRules = this.&collectCommonProguardRules 92 | getPropertySafe = this.&getPropertySafe 93 | } -------------------------------------------------------------------------------- /buildsystem/generate_dependency_hashfile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # This script scans the directory passed as the first parameter and hashes all gradlefiles it finds/ 5 | # It then outputs the hashes into the file passed as the second parameter 6 | # 7 | 8 | SOURCE_DIR=$1 9 | HASH_FILE=$2 10 | REGEX_PATTERN_GRADLE="*\.gradle" 11 | REGEX_PATTERN_ROBOLECTRIC="*robolectric.properties" 12 | REGEX_PATTERN_VERSION_CATALOG="*libs\.versions\.toml" 13 | 14 | find "${SOURCE_DIR}" -type f \( -iname "$REGEX_PATTERN_GRADLE" -o -iname "$REGEX_PATTERN_ROBOLECTRIC" -o -iname "$REGEX_PATTERN_VERSION_CATALOG" \) -exec md5sum {} \; | sort -k2 -b > "${HASH_FILE}" 15 | -------------------------------------------------------------------------------- /buildsystem/kover.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'kover' 2 | 3 | def koverExcludes = [] 4 | 5 | koverMerged { 6 | enable() 7 | filters { 8 | classes { 9 | excludes.addAll(koverExcludes) 10 | } 11 | } 12 | } 13 | 14 | subprojects { 15 | apply plugin: "kover" 16 | kover { 17 | filters { 18 | classes { 19 | excludes.addAll(koverExcludes) 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /buildsystem/multidex/multidex.pro: -------------------------------------------------------------------------------- 1 | -keep class **Test { *; } 2 | -keep class **Module { *; } -------------------------------------------------------------------------------- /buildsystem/proguard-rules/dagger2-rules.pro: -------------------------------------------------------------------------------- 1 | -dontwarn com.google.errorprone.annotations.** -------------------------------------------------------------------------------- /buildsystem/proguard-rules/gson-rules.pro: -------------------------------------------------------------------------------- 1 | # Source: https://github.com/google/gson/blob/master/examples/android-proguard-example/proguard.cfg 2 | 3 | ##---------------Begin: proguard configuration for Gson ---------- 4 | # Gson uses generic type information stored in a class file when working with fields. Proguard 5 | # removes such information by default, so configure it to keep all of it. 6 | -keepattributes Signature 7 | 8 | # For using GSON @Expose annotation 9 | -keepattributes *Annotation* 10 | 11 | # Gson specific classes 12 | -dontwarn sun.misc.** 13 | #-keep class com.google.gson.stream.** { *; } 14 | 15 | # Application classes that will be serialized/deserialized over Gson 16 | -keep class com.google.gson.examples.android.model.** { *; } 17 | 18 | # Prevent proguard from stripping interface information from TypeAdapterFactory, 19 | # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter) 20 | -keep class * implements com.google.gson.TypeAdapterFactory 21 | -keep class * implements com.google.gson.JsonSerializer 22 | -keep class * implements com.google.gson.JsonDeserializer 23 | 24 | ##---------------End: proguard configuration for Gson ---------- -------------------------------------------------------------------------------- /buildsystem/proguard-rules/kotlin-rules.pro: -------------------------------------------------------------------------------- 1 | -keep class kotlin.reflect.jvm.internal.** { *; } 2 | -keep class kotlin.Metadata { *; } -------------------------------------------------------------------------------- /buildsystem/signing_keys/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/buildsystem/signing_keys/debug.keystore -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | test: 2 | override: 3 | - (echo "Running JUnit tests!") 4 | - ./gradlew test -PdisablePreDex 5 | post: 6 | - mkdir -p $CIRCLE_TEST_REPORTS/junit/ 7 | - find . -type f -regex ".*/build/test-results/.*xml" -exec cp {} $CIRCLE_TEST_REPORTS/junit/ \; 8 | -------------------------------------------------------------------------------- /dist/BluetoothLeLibrary-0.0.1-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/dist/BluetoothLeLibrary-0.0.1-javadoc.jar -------------------------------------------------------------------------------- /dist/BluetoothLeLibrary-0.0.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/dist/BluetoothLeLibrary-0.0.1.jar -------------------------------------------------------------------------------- /documents/Bluetooth_UUIDs.ods: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/documents/Bluetooth_UUIDs.ods -------------------------------------------------------------------------------- /documents/COMPANY_IDENTIFIERS.ods: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/documents/COMPANY_IDENTIFIERS.ods -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | android.enableJetifier=true 2 | android.useAndroidX=true -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | androidx-appcompat = "1.6.1" # changing this will affect minSDK 3 | androidx-recyclerview = "1.2.1" 4 | androidx-test-runner = "1.5.2" 5 | annotation = "1.1.0" 6 | easycursor-android = "2.0.0" 7 | gradle-android = "8.7.2" 8 | gradle-ktlint = "12.1.2" 9 | hilt-android = "2.47" 10 | jsr305 = "3.0.2" 11 | junit4 = "4.13.2" 12 | kotlin = "2.0.21" 13 | kover = "0.6.1" 14 | material = "1.9.0" # changing this will affect minSDK 15 | mockito = "5.14.2" 16 | multidex = "1.0.3" 17 | permissionx = "1.8.1" 18 | test-logger = "3.2.0" 19 | triplet-play = "3.12.1" 20 | vanniktech-maven-publish = "0.30.0" 21 | 22 | [libraries] 23 | android-build-tools-gradle = { module = "com.android.tools.build:gradle", version.ref = "gradle-android" } 24 | android-material = { module = "com.google.android.material:material", version.ref = "material" } 25 | android-support-multidex = { module = "com.android.support:multidex", version.ref = "multidex" } 26 | androidx-annotation = { module = "androidx.annotation:annotation", version.ref = "annotation" } 27 | androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "androidx-appcompat" } 28 | androidx-recyclerview = { module = "androidx.recyclerview:recyclerview", version.ref = "androidx-recyclerview" } 29 | androidx-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } 30 | easycursor-android = { module = "dev.alt236:easycursor-android", version.ref = "easycursor-android" } 31 | hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt-android" } 32 | hilt-compiler = { module = "com.google.dagger:hilt-compiler", version.ref = "hilt-android" } 33 | jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } 34 | junit4 = { module = "junit:junit", version.ref = "junit4" } 35 | kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } 36 | mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" } 37 | permissionx = { module = "com.guolindev.permissionx:permissionx", version.ref = "permissionx" } 38 | 39 | [plugins] 40 | gradle-ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "gradle-ktlint" } 41 | hilt-android = { id = "com.google.dagger.hilt.android", version.ref = "hilt-android" } 42 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } 43 | kotlin-kapt = { id = "kotlin-kapt" } 44 | kotlin-parcelize = { id = "kotlin-parcelize" } 45 | kover = { id = "org.jetbrains.kotlinx.kover", version.ref = "kover" } 46 | test-logger = { id = "com.adarshr.test-logger", version.ref = "test-logger" } 47 | triplet-play = { id = 'com.github.triplet.play', version.ref = "triplet-play" } 48 | vanniktech-maven-publish = { id = "com.vanniktech.maven.publish", version.ref = "vanniktech-maven-publish" } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jul 31 15:27:27 BST 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /image_assets/feature_graphic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/image_assets/feature_graphic.png -------------------------------------------------------------------------------- /image_assets/screenshots/phone_screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/image_assets/screenshots/phone_screenshot_1.png -------------------------------------------------------------------------------- /image_assets/screenshots/phone_screenshot_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/image_assets/screenshots/phone_screenshot_2.png -------------------------------------------------------------------------------- /image_assets/screenshots/phone_screenshot_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/image_assets/screenshots/phone_screenshot_3.png -------------------------------------------------------------------------------- /image_assets/screenshots/phone_screenshot_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/image_assets/screenshots/phone_screenshot_4.png -------------------------------------------------------------------------------- /image_assets/web_hi_res_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/image_assets/web_hi_res_512.png -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | import com.vanniktech.maven.publish.SonatypeHost 2 | 3 | plugins { 4 | id 'com.android.library' 5 | alias(libs.plugins.kotlin.android) 6 | alias(libs.plugins.kotlin.parcelize) 7 | alias(libs.plugins.vanniktech.maven.publish) 8 | } 9 | 10 | apply from: "${project.rootDir}/buildsystem/android-defaults.gradle" 11 | 12 | final int versionMajor = 2 13 | final int versionMinor = 0 14 | final int versionPatch = 0 15 | 16 | def project_name = "Bluetooth LE Libarary (Android)" 17 | def project_description = "Allows for easy access to a Bluetooth LE device's AdRecord and RSSI value" 18 | def github_owner_and_repo = "alt236/Bluetooth-LE-Library---Android" 19 | def group_id = 'dev.alt236' 20 | def artifact_id = 'bluetooth-le-library-android' 21 | def artifact_version = "${versionMajor}.${versionMinor}.${versionPatch}" 22 | 23 | repositories { 24 | google() 25 | mavenCentral() 26 | } 27 | 28 | dependencies { 29 | implementation libs.androidx.annotation 30 | 31 | testImplementation libs.junit4 32 | testImplementation libs.mockito 33 | } 34 | 35 | android { 36 | 37 | androidResources { 38 | noCompress 'zip' 39 | } 40 | lint { 41 | lintConfig file("$rootDir/buildsystem/codequality/lint.xml") 42 | } 43 | namespace 'uk.co.alt236.bluetoothlelib' 44 | buildTypes { 45 | release { 46 | minifyEnabled false 47 | } 48 | } 49 | 50 | compileOptions { 51 | sourceCompatibility JavaVersion.VERSION_11 52 | targetCompatibility JavaVersion.VERSION_11 53 | } 54 | } 55 | 56 | mavenPublishing { // This is for the 'vanniktech-maven-publish' plugin 57 | var automaticRelease = false 58 | publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL, automaticRelease) 59 | signAllPublications() 60 | 61 | coordinates(group_id, artifact_id, artifact_version) 62 | pom { 63 | name = project_name 64 | description = project_description 65 | url = "https://github.com/$github_owner_and_repo" 66 | licenses { 67 | license { 68 | name = 'The Apache License, Version 2.0' 69 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 70 | distribution = "http://www.apache.org/licenses/LICENSE-2.0.txt" 71 | } 72 | } 73 | developers { 74 | developer { 75 | id = 'alt236' 76 | name = 'Alexandros Schillings' 77 | url = "https://github.com/alt236/" 78 | } 79 | } 80 | scm { 81 | url = "https://github.com/$github_owner_and_repo" 82 | } 83 | } 84 | } 85 | 86 | -------------------------------------------------------------------------------- /library/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/library/ic_launcher-web.png -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/alex/Dev/android-sdk-linux/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/BluetoothService.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device; 2 | 3 | import android.bluetooth.BluetoothClass; 4 | 5 | /** 6 | * 7 | */ 8 | public enum BluetoothService { 9 | AUDIO(BluetoothClass.Service.AUDIO), 10 | CAPTURE(BluetoothClass.Service.CAPTURE), 11 | INFORMATION(BluetoothClass.Service.INFORMATION), 12 | LIMITED_DISCOVERABILITY(BluetoothClass.Service.LIMITED_DISCOVERABILITY), 13 | NETWORKING(BluetoothClass.Service.NETWORKING), 14 | OBJECT_TRANSFER(BluetoothClass.Service.OBJECT_TRANSFER), 15 | POSITIONING(BluetoothClass.Service.POSITIONING), 16 | RENDER(BluetoothClass.Service.RENDER), 17 | TELEPHONY(BluetoothClass.Service.TELEPHONY); 18 | 19 | private final int mAndroidConstant; 20 | 21 | BluetoothService(final int androidCode){ 22 | mAndroidConstant = androidCode; 23 | } 24 | 25 | public int getAndroidConstant(){ 26 | return mAndroidConstant; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/adrecord/AdRecordStore.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.adrecord; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | import android.util.SparseArray; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Collection; 10 | import java.util.Collections; 11 | 12 | import dev.alt236.bluetoothlelib.util.AdRecordUtils; 13 | 14 | /** 15 | * The Class AdRecordStore. 16 | */ 17 | public class AdRecordStore implements Parcelable { 18 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 19 | public AdRecordStore createFromParcel(final Parcel in) { 20 | return new AdRecordStore(in); 21 | } 22 | 23 | public AdRecordStore[] newArray(final int size) { 24 | return new AdRecordStore[size]; 25 | } 26 | }; 27 | private final SparseArray mAdRecords; 28 | private final String mLocalNameComplete; 29 | private final String mLocalNameShort; 30 | 31 | public AdRecordStore(final Parcel in) { 32 | final Bundle b = in.readBundle(getClass().getClassLoader()); 33 | mAdRecords = b.getSparseParcelableArray("records_array"); 34 | mLocalNameComplete = b.getString("local_name_complete"); 35 | mLocalNameShort = b.getString("local_name_short"); 36 | } 37 | 38 | /** 39 | * Instantiates a new Bluetooth LE device Ad Record Store. 40 | * 41 | * @param adRecords the ad records 42 | */ 43 | public AdRecordStore(final SparseArray adRecords) { 44 | mAdRecords = adRecords; 45 | 46 | mLocalNameComplete = AdRecordUtils.getRecordDataAsString( 47 | mAdRecords.get(AdRecord.TYPE_LOCAL_NAME_COMPLETE)); 48 | 49 | mLocalNameShort = AdRecordUtils.getRecordDataAsString( 50 | mAdRecords.get(AdRecord.TYPE_LOCAL_NAME_SHORT)); 51 | 52 | } 53 | 54 | /* (non-Javadoc) 55 | * @see android.os.Parcelable#describeContents() 56 | */ 57 | @Override 58 | public int describeContents() { 59 | return 0; 60 | } 61 | 62 | /** 63 | * Gets the short local device name. 64 | * 65 | * @return the local name complete 66 | */ 67 | public String getLocalNameComplete() { 68 | return mLocalNameComplete; 69 | } 70 | 71 | /** 72 | * Gets the complete local device name. 73 | * 74 | * @return the local name short 75 | */ 76 | public String getLocalNameShort() { 77 | return mLocalNameShort; 78 | } 79 | 80 | /** 81 | * retrieves an individual record. 82 | * 83 | * @param record the record 84 | * @return the record 85 | */ 86 | public AdRecord getRecord(final int record) { 87 | return mAdRecords.get(record); 88 | } 89 | 90 | /** 91 | * Gets the record data as string. 92 | * 93 | * @param record the record 94 | * @return the record data as string 95 | */ 96 | public String getRecordDataAsString(final int record) { 97 | return AdRecordUtils.getRecordDataAsString( 98 | mAdRecords.get(record)); 99 | } 100 | 101 | /** 102 | * Gets the record as collection. 103 | * 104 | * @return the records as collection 105 | */ 106 | public Collection getRecordsAsCollection() { 107 | return Collections.unmodifiableCollection(asList(mAdRecords)); 108 | } 109 | 110 | /** 111 | * Checks if is record present. 112 | * 113 | * @param record the record 114 | * @return true, if is record present 115 | */ 116 | public boolean isRecordPresent(final int record) { 117 | return mAdRecords.indexOfKey(record) >= 0; 118 | } 119 | 120 | /* (non-Javadoc) 121 | * @see java.lang.Object#toString() 122 | */ 123 | @Override 124 | public String toString() { 125 | return "AdRecordStore [mLocalNameComplete=" + mLocalNameComplete + ", mLocalNameShort=" + mLocalNameShort + "]"; 126 | } 127 | 128 | /* (non-Javadoc) 129 | * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int) 130 | */ 131 | @Override 132 | public void writeToParcel(final Parcel parcel, final int arg1) { 133 | final Bundle b = new Bundle(); 134 | b.putString("local_name_complete", mLocalNameComplete); 135 | b.putString("local_name_short", mLocalNameShort); 136 | b.putSparseParcelableArray("records_array", mAdRecords); 137 | 138 | parcel.writeBundle(b); 139 | } 140 | 141 | /** 142 | * As list. 143 | * 144 | * @param the generic type 145 | * @param sparseArray the sparse array 146 | * @return the collection 147 | */ 148 | public static Collection asList(final SparseArray sparseArray) { 149 | if (sparseArray == null) return null; 150 | 151 | final Collection arrayList = new ArrayList<>(sparseArray.size()); 152 | for (int i = 0; i < sparseArray.size(); i++) { 153 | arrayList.add(sparseArray.valueAt(i)); 154 | } 155 | 156 | return arrayList; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/BeaconDevice.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon; 2 | 3 | /** 4 | * 5 | */ 6 | public interface BeaconDevice { 7 | BeaconType getBeaconType(); 8 | } 9 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/BeaconManufacturerData.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * 7 | */ 8 | public abstract class BeaconManufacturerData { 9 | private final BeaconType mBeaconType; 10 | private final byte[] mData; 11 | 12 | protected BeaconManufacturerData(final BeaconType expectedType, final byte[] data){ 13 | if (BeaconUtils.getBeaconType(data) != expectedType) { 14 | throw new IllegalArgumentException( 15 | "Manufacturer record '" 16 | + Arrays.toString(data) 17 | + "' is not from a " + expectedType); 18 | } 19 | 20 | this.mData = data; 21 | this.mBeaconType = expectedType; 22 | } 23 | 24 | public BeaconType getBeaconType(){ 25 | return mBeaconType; 26 | } 27 | 28 | public byte[] getData(){ 29 | return mData; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/BeaconType.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon; 2 | 3 | /** 4 | * 5 | */ 6 | public enum BeaconType { 7 | NOT_A_BEACON, 8 | IBEACON, 9 | } 10 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/BeaconUtils.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon; 2 | 3 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice; 4 | import dev.alt236.bluetoothlelib.device.adrecord.AdRecord; 5 | import dev.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconConstants; 6 | import dev.alt236.bluetoothlelib.util.ByteUtils; 7 | 8 | /** 9 | * 10 | */ 11 | public final class BeaconUtils { 12 | 13 | private BeaconUtils(){ 14 | // TO AVOID INSTANTIATION 15 | } 16 | 17 | /** 18 | * Ascertains whether a Manufacturer Data byte array belongs to a known Beacon type; 19 | * 20 | * @param manufacturerData a Bluetooth LE device's raw manufacturerData. 21 | * @return the {@link BeaconType} 22 | */ 23 | public static BeaconType getBeaconType(final byte[] manufacturerData) { 24 | if (manufacturerData == null || manufacturerData.length == 0) { 25 | return BeaconType.NOT_A_BEACON; 26 | } 27 | 28 | if(isIBeacon(manufacturerData)){ 29 | return BeaconType.IBEACON; 30 | } else { 31 | return BeaconType.NOT_A_BEACON; 32 | } 33 | } 34 | 35 | /** 36 | * Ascertains whether a {@link BluetoothLeDevice} is an iBeacon; 37 | * 38 | * @param device a {@link BluetoothLeDevice} device. 39 | * @return the {@link BeaconType} 40 | */ 41 | public static BeaconType getBeaconType(final BluetoothLeDevice device) { 42 | final int key = AdRecord.TYPE_MANUFACTURER_SPECIFIC_DATA; 43 | return getBeaconType(device.getAdRecordStore().getRecordDataAsString(key).getBytes()); 44 | } 45 | 46 | private static boolean isIBeacon(final byte[] manufacturerData){ 47 | // An iBeacon record must be at least 25 chars long 48 | if (!(manufacturerData.length >= 25)) { 49 | return false; 50 | } 51 | 52 | if (ByteUtils.doesArrayBeginWith(manufacturerData, IBeaconConstants.MANUFACTURER_DATA_IBEACON_PREFIX)) { 53 | return true; 54 | } 55 | 56 | return false; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconConstants.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | /** 4 | * 5 | */ 6 | public class IBeaconConstants { 7 | public static final byte[] MANUFACTURER_DATA_IBEACON_PREFIX = {0x4C, 0x00, 0x02, 0x15}; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconDevice.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | import android.bluetooth.BluetoothDevice; 4 | import android.os.Parcel; 5 | 6 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice; 7 | import dev.alt236.bluetoothlelib.device.beacon.BeaconDevice; 8 | import dev.alt236.bluetoothlelib.device.beacon.BeaconType; 9 | 10 | public class IBeaconDevice extends BluetoothLeDevice implements BeaconDevice{ 11 | 12 | /** 13 | * The m iBeacon data. 14 | */ 15 | private final IBeaconManufacturerData mIBeaconData; 16 | 17 | /** 18 | * Instantiates a new iBeacon device. 19 | * 20 | * @param device the device 21 | * @param rssi the RSSI value 22 | * @param scanRecord the scanRecord 23 | * @throws IllegalArgumentException if the passed device is not an iBeacon 24 | */ 25 | public IBeaconDevice(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { 26 | super(device, rssi, scanRecord, 0); 27 | mIBeaconData = new IBeaconManufacturerData(this); 28 | } 29 | 30 | /** 31 | * Instantiates a new iBeacon device. 32 | * 33 | * @param device the device 34 | * @param rssi the RSSI value of the RSSI measurement 35 | * @param scanRecord the scan record 36 | * @param timestamp the timestamp of the RSSI measurement 37 | * @throws IllegalArgumentException if the passed device is not an iBeacon 38 | */ 39 | public IBeaconDevice(final BluetoothDevice device, final int rssi, final byte[] scanRecord, final long timestamp) { 40 | super(device, rssi, scanRecord, timestamp); 41 | mIBeaconData = new IBeaconManufacturerData(this); 42 | } 43 | 44 | /** 45 | * Will try to convert a {@link BluetoothLeDevice} into an 46 | * iBeacon Device. 47 | * 48 | * @param device the device 49 | * @throws IllegalArgumentException if the passed device is not an iBeacon 50 | */ 51 | public IBeaconDevice(final BluetoothLeDevice device) { 52 | super(device); 53 | mIBeaconData = new IBeaconManufacturerData(this); 54 | } 55 | 56 | private IBeaconDevice(final Parcel in) { 57 | super(in); 58 | mIBeaconData = new IBeaconManufacturerData(this); 59 | } 60 | 61 | /** 62 | * Gets the estimated Accuracy of the reading in meters based on 63 | * a simple running average of the last {@link #MAX_RSSI_LOG_SIZE} 64 | * samples. 65 | * 66 | * @return the accuracy in meters 67 | */ 68 | public double getAccuracy() { 69 | return IBeaconUtils.calculateAccuracy( 70 | getCalibratedTxPower(), 71 | getRunningAverageRssi()); 72 | } 73 | 74 | @Override 75 | public BeaconType getBeaconType() { 76 | return BeaconType.IBEACON; 77 | } 78 | 79 | /** 80 | * Gets the calibrated TX power of the iBeacon device as reported. 81 | * 82 | * @return the calibrated TX power 83 | */ 84 | public int getCalibratedTxPower() { 85 | return getIBeaconData().getCalibratedTxPower(); 86 | } 87 | 88 | /** 89 | * Gets the iBeacon company identifier. 90 | * 91 | * @return the company identifier 92 | */ 93 | public int getCompanyIdentifier() { 94 | return getIBeaconData().getCompanyIdentifier(); 95 | } 96 | 97 | /** 98 | * Gets the estimated Distance descriptor. 99 | * 100 | * @return the distance descriptor 101 | */ 102 | public IBeaconDistanceDescriptor getDistanceDescriptor() { 103 | return IBeaconUtils.getDistanceDescriptor(getAccuracy()); 104 | } 105 | 106 | /** 107 | * Gets the iBeacon manufacturing data. 108 | * 109 | * @return the iBeacon data 110 | */ 111 | public IBeaconManufacturerData getIBeaconData() { 112 | return mIBeaconData; 113 | } 114 | 115 | /** 116 | * Gets the iBeacon Major value. 117 | * 118 | * @return the Major value 119 | */ 120 | public int getMajor() { 121 | return getIBeaconData().getMajor(); 122 | } 123 | 124 | /** 125 | * Gets the iBeacon Minor value. 126 | * 127 | * @return the Minor value 128 | */ 129 | public int getMinor() { 130 | return getIBeaconData().getMinor(); 131 | } 132 | 133 | /** 134 | * Gets the iBeacon UUID. 135 | * 136 | * @return the UUID 137 | */ 138 | public String getUUID() { 139 | return getIBeaconData().getUUID(); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconDistanceDescriptor.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | public enum IBeaconDistanceDescriptor { 4 | IMMEDIATE, 5 | NEAR, 6 | FAR, 7 | UNKNOWN, 8 | } 9 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconManufacturerData.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | import java.util.Arrays; 4 | 5 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice; 6 | import dev.alt236.bluetoothlelib.device.adrecord.AdRecord; 7 | import dev.alt236.bluetoothlelib.device.beacon.BeaconManufacturerData; 8 | import dev.alt236.bluetoothlelib.device.beacon.BeaconType; 9 | import dev.alt236.bluetoothlelib.util.ByteUtils; 10 | 11 | /** 12 | * Parses the Manufactured Data field of an iBeacon 13 | *

14 | * The parsing is based on the following schema: 15 | *

 16 |  * Byte|Value
 17 |  * -------------------------------------------------
 18 |  * 0	4C - Byte 1 (LSB) of Company identifier code
 19 |  * 1	00 - Byte 0 (MSB) of Company identifier code (0x004C == Apple)
 20 |  * 2	02 - Byte 0 of iBeacon advertisement indicator
 21 |  * 3	15 - Byte 1 of iBeacon advertisement indicator
 22 |  * 4	e2 |\
 23 |  * 5	c5 |\\
 24 |  * 6	6d |#\\
 25 |  * 7	b5 |##\\
 26 |  * 8	df |###\\
 27 |  * 9	fb |####\\
 28 |  * 10	48 |#####\\
 29 |  * 11	d2 |#####|| iBeacon
 30 |  * 12	b0 |#####|| Proximity UUID
 31 |  * 13	60 |#####//
 32 |  * 14	d0 |####//
 33 |  * 15	f5 |###//
 34 |  * 16	a7 |##//
 35 |  * 17	10 |#//
 36 |  * 18	96 |//
 37 |  * 19	e0 |/
 38 |  * 20	00 - major
 39 |  * 21	00
 40 |  * 22	00 - minor
 41 |  * 23	00
 42 |  * 24	c5 - The 2's complement of the calibrated Tx Power
 43 |  * 
44 | * @author Alexandros Schillings 45 | */ 46 | 47 | public final class IBeaconManufacturerData extends BeaconManufacturerData{ 48 | private final int mCalibratedTxPower; 49 | private final int mCompanyIdentidier; 50 | private final int mIBeaconAdvertisment; 51 | private final int mMajor; 52 | private final int mMinor; 53 | private final String mUUID; 54 | 55 | /** 56 | * Instantiates a new iBeacon manufacturer data object. 57 | * 58 | * @param device a {@link BluetoothLeDevice} 59 | * @throws IllegalArgumentException if the data is not from an iBeacon. 60 | */ 61 | public IBeaconManufacturerData(final BluetoothLeDevice device) { 62 | this(device.getAdRecordStore().getRecord(AdRecord.TYPE_MANUFACTURER_SPECIFIC_DATA).getData()); 63 | } 64 | 65 | /** 66 | * Instantiates a new iBeacon manufacturer data object. 67 | * 68 | * @param manufacturerData the {@link AdRecord#TYPE_MANUFACTURER_SPECIFIC_DATA} data array 69 | * @throws IllegalArgumentException if the data is not from an iBeacon. 70 | */ 71 | public IBeaconManufacturerData(final byte[] manufacturerData) { 72 | super(BeaconType.IBEACON, manufacturerData); 73 | 74 | final byte[] intArray = Arrays.copyOfRange(manufacturerData, 0, 2); 75 | ByteUtils.invertArray(intArray); 76 | 77 | mCompanyIdentidier = ByteUtils.getIntFrom2ByteArray(intArray); 78 | mIBeaconAdvertisment = ByteUtils.getIntFrom2ByteArray(Arrays.copyOfRange(manufacturerData, 2, 4)); 79 | mUUID = IBeaconUtils.calculateUuidString(Arrays.copyOfRange(manufacturerData, 4, 20)); 80 | mMajor = ByteUtils.getIntFrom2ByteArray(Arrays.copyOfRange(manufacturerData, 20, 22)); 81 | mMinor = ByteUtils.getIntFrom2ByteArray(Arrays.copyOfRange(manufacturerData, 22, 24)); 82 | mCalibratedTxPower = manufacturerData[24]; 83 | } 84 | 85 | /** 86 | * Gets the calibrated TX power of the iBeacon device as reported. 87 | * 88 | * @return the calibrated TX power 89 | */ 90 | public int getCalibratedTxPower() { 91 | return mCalibratedTxPower; 92 | } 93 | 94 | /** 95 | * Gets the iBeacon company identifier. 96 | * 97 | * @return the company identifier 98 | */ 99 | public int getCompanyIdentifier() { 100 | return mCompanyIdentidier; 101 | } 102 | 103 | public int getIBeaconAdvertisement() { 104 | return mIBeaconAdvertisment; 105 | } 106 | 107 | /** 108 | * Gets the iBeacon Major value. 109 | * 110 | * @return the Major value 111 | */ 112 | public int getMajor() { 113 | return mMajor; 114 | } 115 | 116 | /** 117 | * Gets the iBeacon Minor value. 118 | * 119 | * @return the Minor value 120 | */ 121 | public int getMinor() { 122 | return mMinor; 123 | } 124 | 125 | /** 126 | * Gets the iBeacon UUID. 127 | * 128 | * @return the UUID 129 | */ 130 | public String getUUID() { 131 | return mUUID; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconUtils.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | import dev.alt236.bluetoothlelib.util.ByteUtils; 4 | 5 | final class IBeaconUtils { 6 | private static final double DISTANCE_THRESHOLD_WTF = 0.0; 7 | private static final double DISTANCE_THRESHOLD_IMMEDIATE = 0.5; 8 | private static final double DISTANCE_THRESHOLD_NEAR = 3.0; 9 | 10 | private IBeaconUtils(){ 11 | // TO AVOID INSTANTIATION 12 | } 13 | 14 | /** 15 | * Calculates the accuracy of an RSSI reading. 16 | *

17 | * The code was taken from 18 | * 19 | * @param txPower the calibrated TX power of an iBeacon 20 | * @param rssi the RSSI value of the iBeacon 21 | * @return the calculated Accuracy 22 | */ 23 | public static double calculateAccuracy(final int txPower, final double rssi) { 24 | if (rssi == 0) { 25 | return -1.0; // if we cannot determine accuracy, return -1. 26 | } 27 | 28 | final double ratio = rssi * 1.0 / txPower; 29 | if (ratio < 1.0) { 30 | return Math.pow(ratio, 10); 31 | } else { 32 | return (0.89976) * Math.pow(ratio, 7.7095) + 0.111; 33 | } 34 | } 35 | 36 | public static String calculateUuidString(final byte[] uuid) { 37 | final StringBuilder sb = new StringBuilder(); 38 | 39 | for (int i = 0; i < uuid.length; i++) { 40 | if (i == 4) { 41 | sb.append('-'); 42 | } 43 | if (i == 6) { 44 | sb.append('-'); 45 | } 46 | if (i == 8) { 47 | sb.append('-'); 48 | } 49 | if (i == 10) { 50 | sb.append('-'); 51 | } 52 | 53 | final int intFromByte = ByteUtils.getIntFromByte(uuid[i]); 54 | if(intFromByte <= 0xF){ 55 | sb.append('0'); 56 | } 57 | sb.append(Integer.toHexString(intFromByte)); 58 | } 59 | 60 | 61 | return sb.toString(); 62 | } 63 | 64 | public static IBeaconDistanceDescriptor getDistanceDescriptor(final double accuracy) { 65 | if (accuracy < DISTANCE_THRESHOLD_WTF) { 66 | return IBeaconDistanceDescriptor.UNKNOWN; 67 | } 68 | 69 | if (accuracy < DISTANCE_THRESHOLD_IMMEDIATE) { 70 | return IBeaconDistanceDescriptor.IMMEDIATE; 71 | } 72 | 73 | if (accuracy < DISTANCE_THRESHOLD_NEAR) { 74 | return IBeaconDistanceDescriptor.NEAR; 75 | } 76 | 77 | return IBeaconDistanceDescriptor.FAR; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/util/AdRecordUtils.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.util; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.util.SparseArray; 5 | 6 | import java.io.UnsupportedEncodingException; 7 | import java.util.ArrayList; 8 | import java.util.Arrays; 9 | import java.util.Collections; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import androidx.annotation.Nullable; 15 | import dev.alt236.bluetoothlelib.device.adrecord.AdRecord; 16 | 17 | public final class AdRecordUtils { 18 | 19 | private AdRecordUtils(){ 20 | // TO AVOID INSTANTIATION 21 | } 22 | 23 | public static String getRecordDataAsString(@Nullable final AdRecord record) { 24 | if (record == null) { 25 | return ""; 26 | } 27 | 28 | return toString(record.getData()); 29 | } 30 | 31 | @Nullable 32 | public static byte[] getServiceData(@Nullable final AdRecord record) { 33 | if (record == null) { 34 | return null; 35 | } 36 | if (record.getType() != AdRecord.TYPE_SERVICE_DATA) return null; 37 | 38 | final byte[] raw = record.getData(); 39 | if (raw == null) { 40 | return null; 41 | } 42 | //Chop out the uuid 43 | return Arrays.copyOfRange(raw, 2, raw.length); 44 | } 45 | 46 | public static int getServiceDataUuid(@Nullable final AdRecord record) { 47 | if (record == null) { 48 | return -1; 49 | } 50 | if (record.getType() != AdRecord.TYPE_SERVICE_DATA) return -1; 51 | 52 | final byte[] raw = record.getData(); 53 | if (raw == null) { 54 | return -1; 55 | } 56 | 57 | //Find UUID data in byte array 58 | int uuid = (raw[1] & 0xFF) << 8; 59 | uuid += (raw[0] & 0xFF); 60 | 61 | return uuid; 62 | } 63 | 64 | /* 65 | * Read out all the AD structures from the raw scan record 66 | */ 67 | public static List parseScanRecordAsList(final byte[] scanRecord) { 68 | final List records = new ArrayList<>(); 69 | 70 | int index = 0; 71 | while (index < scanRecord.length) { 72 | final int length = scanRecord[index++]; 73 | //Done once we run out of records 74 | if (length == 0) break; 75 | 76 | final int type = ByteUtils.getIntFromByte(scanRecord[index]); 77 | 78 | //Done if our record isn't a valid type 79 | if (type == 0) break; 80 | 81 | final byte[] data = Arrays.copyOfRange(scanRecord, index + 1, index + length); 82 | 83 | records.add(new AdRecord(length, type, data)); 84 | 85 | //Advance 86 | index += length; 87 | } 88 | 89 | return Collections.unmodifiableList(records); 90 | } 91 | 92 | @SuppressLint("UseSparseArrays") 93 | public static Map parseScanRecordAsMap(final byte[] scanRecord) { 94 | final Map records = new HashMap<>(); 95 | 96 | int index = 0; 97 | while (index < scanRecord.length) { 98 | final int length = scanRecord[index++]; 99 | //Done once we run out of records 100 | if (length == 0) break; 101 | 102 | final int type = ByteUtils.getIntFromByte(scanRecord[index]); 103 | 104 | //Done if our record isn't a valid type 105 | if (type == 0) break; 106 | 107 | final byte[] data = Arrays.copyOfRange(scanRecord, index + 1, index + length); 108 | 109 | records.put(type, new AdRecord(length, type, data)); 110 | 111 | //Advance 112 | index += length; 113 | } 114 | 115 | return Collections.unmodifiableMap(records); 116 | } 117 | 118 | public static SparseArray parseScanRecordAsSparseArray(final byte[] scanRecord) { 119 | final SparseArray records = new SparseArray<>(); 120 | 121 | int index = 0; 122 | while (index < scanRecord.length) { 123 | final int length = scanRecord[index++]; 124 | //Done once we run out of records 125 | if (length == 0) break; 126 | 127 | final int type = ByteUtils.getIntFromByte(scanRecord[index]); 128 | 129 | //Done if our record isn't a valid type 130 | if (type == 0) break; 131 | 132 | final byte[] data = Arrays.copyOfRange(scanRecord, index + 1, index + length); 133 | 134 | records.put(type, new AdRecord(length, type, data)); 135 | 136 | //Advance 137 | index += length; 138 | } 139 | 140 | return records; 141 | } 142 | 143 | private static String toString(@Nullable byte[] array) { 144 | if (array == null) { 145 | return ""; 146 | } 147 | 148 | try { 149 | //noinspection CharsetObjectCanBeUsed 150 | return new String(array, "UTF-8"); 151 | } catch (UnsupportedEncodingException e) { 152 | return ""; 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/util/ByteUtils.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.util; 2 | 3 | import java.nio.ByteBuffer; 4 | 5 | import androidx.annotation.Nullable; 6 | 7 | public class ByteUtils { 8 | 9 | /** 10 | * The Constant HEXES. 11 | */ 12 | private static final String HEXES = "0123456789ABCDEF"; 13 | 14 | private ByteUtils(){ 15 | // TO AVOID INSTANTIATION 16 | } 17 | 18 | /** 19 | * Gets a pretty representation of a Byte Array as a HEX String. 20 | *

21 | * Sample output: [01, 30, FF, AA] 22 | * 23 | * @param array the array 24 | * @return the string 25 | */ 26 | public static String byteArrayToHexString(@Nullable final byte[] array) { 27 | final byte[] safeArray = array == null ? new byte[0] : array; 28 | final StringBuilder sb = new StringBuilder(); 29 | boolean firstEntry = true; 30 | sb.append('['); 31 | 32 | for (final byte b : safeArray) { 33 | if (!firstEntry) { 34 | sb.append(", "); 35 | } 36 | sb.append(HEXES.charAt((b & 0xF0) >> 4)); 37 | sb.append(HEXES.charAt((b & 0x0F))); 38 | firstEntry = false; 39 | } 40 | 41 | sb.append(']'); 42 | return sb.toString(); 43 | } 44 | 45 | /** 46 | * Checks to see if a byte array starts with another byte array. 47 | * 48 | * @param array the array 49 | * @param prefix the prefix 50 | * @return true, if successful 51 | */ 52 | public static boolean doesArrayBeginWith(final byte[] array, final byte[] prefix) { 53 | if (array.length < prefix.length) { 54 | return false; 55 | } 56 | 57 | for (int i = 0; i < prefix.length; i++) { 58 | if (array[i] != prefix[i]) { 59 | return false; 60 | } 61 | } 62 | 63 | return true; 64 | } 65 | 66 | /** 67 | * Converts a byte array with a length of 2 into an int 68 | * 69 | * @param input the input 70 | * @return the int from the array 71 | */ 72 | public static int getIntFrom2ByteArray(final byte[] input) { 73 | final byte[] result = new byte[4]; 74 | 75 | result[0] = 0; 76 | result[1] = 0; 77 | result[2] = input[0]; 78 | result[3] = input[1]; 79 | 80 | return ByteUtils.getIntFromByteArray(result); 81 | } 82 | 83 | /** 84 | * Converts a byte to an int, preserving the sign. 85 | *

86 | * For example, FF will be converted to 255 and not -1. 87 | * 88 | * @param bite the byte 89 | * @return the int from byte 90 | */ 91 | public static int getIntFromByte(final byte bite) { 92 | return bite & 0xFF; 93 | } 94 | 95 | /** 96 | * Converts a byte array to an int. 97 | * 98 | * @param bytes the bytes 99 | * @return the int from byte array 100 | */ 101 | public static int getIntFromByteArray(final byte[] bytes) { 102 | return ByteBuffer.wrap(bytes).getInt(); 103 | } 104 | 105 | /** 106 | * Converts a byte array to a long. 107 | * 108 | * @param bytes the bytes 109 | * @return the long from byte array 110 | */ 111 | public static long getLongFromByteArray(final byte[] bytes) { 112 | return ByteBuffer.wrap(bytes).getLong(); 113 | } 114 | 115 | 116 | /** 117 | * Inverts an byte array in place. 118 | * 119 | * @param array the array 120 | */ 121 | public static void invertArray(final byte[] array) { 122 | final int size = array.length; 123 | byte temp; 124 | 125 | for (int i = 0; i < size / 2; i++) { 126 | temp = array[i]; 127 | array[i] = array[size - 1 - i]; 128 | array[size - 1 - i] = temp; 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /library/src/main/java/dev/alt236/bluetoothlelib/util/LimitedLinkHashMap.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.util; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | public class LimitedLinkHashMap extends LinkedHashMap { 7 | private static final long serialVersionUID = -5375660288461724925L; 8 | 9 | private final int mMaxSize; 10 | 11 | public LimitedLinkHashMap(final int maxSize) { 12 | super(maxSize + 1, 1, false); 13 | mMaxSize = maxSize; 14 | } 15 | 16 | @Override 17 | protected boolean removeEldestEntry(final Map.Entry eldest) { 18 | return this.size() > mMaxSize; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /library/src/test/java/dev/alt236/bluetoothlelib/device/beacon/BeaconUtilsTest.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon; 2 | 3 | import junit.framework.TestCase; 4 | 5 | /** 6 | * 7 | */ 8 | public class BeaconUtilsTest extends TestCase { 9 | 10 | public void testGetBeaconTypeIBeacon() throws Exception { 11 | assertEquals(BeaconType.IBEACON, BeaconUtils.getBeaconType(new byte[]{ 12 | 0x4C, 0x00, 0x02, 0x15, 0x00, // <- Magic iBeacon header 13 | 0x00, 0x00, 0x00, 0x00, 0x00, 14 | 0x00, 0x00, 0x00, 0x00, 0x00, 15 | 0x00, 0x00, 0x00, 0x00, 0x00, 16 | 0x00, 0x00, 0x00, 0x00, 0x00 17 | })); 18 | } 19 | 20 | public void testGetBeaconTypeInvalid() throws Exception { 21 | assertEquals(BeaconType.NOT_A_BEACON, BeaconUtils.getBeaconType((byte[]) null)); 22 | assertEquals(BeaconType.NOT_A_BEACON, BeaconUtils.getBeaconType(new byte[0])); 23 | assertEquals(BeaconType.NOT_A_BEACON, BeaconUtils.getBeaconType(new byte[25])); 24 | } 25 | } -------------------------------------------------------------------------------- /library/src/test/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconManufacturerDataTest.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import dev.alt236.bluetoothlelib.device.beacon.BeaconManufacturerData; 6 | 7 | /** 8 | * 9 | */ 10 | public class IBeaconManufacturerDataTest extends TestCase { 11 | private static final byte[] NON_BEACON = 12 | {2, 1, 26, 11, -1, 76, 0, 9, 6, 3, -32, -64, -88, 13 | 1, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 16 | 17 | public void testNonIBeaconData() throws Exception{ 18 | try { 19 | BeaconManufacturerData data = new IBeaconManufacturerData(NON_BEACON); 20 | fail("Should have thrown an exception"); 21 | } catch (final IllegalArgumentException e){ 22 | // EXPECTED 23 | } 24 | 25 | try { 26 | BeaconManufacturerData data = new IBeaconManufacturerData((byte[]) null); 27 | fail("Should have thrown an exception"); 28 | } catch (final IllegalArgumentException e){ 29 | // EXPECTED 30 | } 31 | 32 | try { 33 | BeaconManufacturerData data = new IBeaconManufacturerData(new byte[0]); 34 | fail("Should have thrown an exception"); 35 | } catch (final IllegalArgumentException e){ 36 | // EXPECTED 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /library/src/test/java/dev/alt236/bluetoothlelib/device/beacon/ibeacon/IBeaconUtilsTest.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.device.beacon.ibeacon; 2 | 3 | import junit.framework.TestCase; 4 | 5 | /** 6 | * 7 | */ 8 | public class IBeaconUtilsTest extends TestCase { 9 | 10 | public void testCalculateUuidString() throws Exception { 11 | assertEquals("00", IBeaconUtils.calculateUuidString(new byte[]{0})); 12 | assertEquals("0a", IBeaconUtils.calculateUuidString(new byte[]{10})); 13 | assertEquals("0f", IBeaconUtils.calculateUuidString(new byte[]{15})); 14 | assertEquals("10", IBeaconUtils.calculateUuidString(new byte[]{16})); 15 | assertEquals("7f", IBeaconUtils.calculateUuidString(new byte[]{127})); 16 | assertEquals( 17 | "00000000-0000-0000-0000-00", 18 | IBeaconUtils.calculateUuidString(new byte[]{0,0,0,0,0,0,0,0,0,0,0})); 19 | } 20 | 21 | public void testGetDistanceDescriptor() throws Exception { 22 | assertEquals(IBeaconDistanceDescriptor.UNKNOWN, IBeaconUtils.getDistanceDescriptor(-1)); 23 | 24 | assertEquals(IBeaconDistanceDescriptor.IMMEDIATE, IBeaconUtils.getDistanceDescriptor(0)); 25 | assertEquals(IBeaconDistanceDescriptor.IMMEDIATE, IBeaconUtils.getDistanceDescriptor(0.4)); 26 | 27 | assertEquals(IBeaconDistanceDescriptor.NEAR, IBeaconUtils.getDistanceDescriptor(0.5)); 28 | assertEquals(IBeaconDistanceDescriptor.NEAR, IBeaconUtils.getDistanceDescriptor(2.9)); 29 | 30 | assertEquals(IBeaconDistanceDescriptor.FAR, IBeaconUtils.getDistanceDescriptor(3)); 31 | } 32 | } -------------------------------------------------------------------------------- /library/src/test/java/dev/alt236/bluetoothlelib/resolvers/GattAttributeResolverTest.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.resolvers; 2 | 3 | import junit.framework.TestCase; 4 | 5 | /** 6 | * 7 | */ 8 | public class GattAttributeResolverTest extends TestCase { 9 | private static final String UKNOWN = "unknown"; 10 | 11 | public void testGetAttributeName() throws Exception { 12 | assertEquals(UKNOWN, GattAttributeResolver.getAttributeName("foo", UKNOWN)); 13 | assertEquals("Estimote Advertising Vector", GattAttributeResolver.getAttributeName("b9402002-f5f8-466e-aff9-25556b57fe6d", UKNOWN)); 14 | assertEquals("LINK_LOSS", GattAttributeResolver.getAttributeName("00001803-0000-1000-8000-00805f9b34fb", UKNOWN)); 15 | assertEquals("Base GUID", GattAttributeResolver.getAttributeName("00000000-0000-1000-8000-00805f9b34fb", UKNOWN)); 16 | assertEquals("PNPID", GattAttributeResolver.getAttributeName("00002a50-0000-1000-8000-00805f9b34fb", UKNOWN)); 17 | assertEquals("HTTP", GattAttributeResolver.getAttributeName("0000000c-0000-1000-8000-00805f9b34fb", UKNOWN)); 18 | 19 | } 20 | } -------------------------------------------------------------------------------- /library/src/test/java/dev/alt236/bluetoothlelib/util/AdRecordUtilsTest.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.util; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import dev.alt236.bluetoothlelib.device.adrecord.AdRecord; 9 | 10 | /** 11 | * 12 | */ 13 | public class AdRecordUtilsTest extends TestCase { 14 | private static final byte[] NON_IBEACON = 15 | {2, 1, 26, 11, -1, 76, 0, 9, 6, 3, -32, -64, -88, 16 | 1, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 19 | 20 | public void testParseScanRecordAsList() throws Exception { 21 | final List adRecords = AdRecordUtils.parseScanRecordAsList(NON_IBEACON); 22 | assertNotNull(adRecords); 23 | assertEquals(2, adRecords.size()); 24 | 25 | int type = AdRecord.TYPE_FLAGS; 26 | assertEquals(type, adRecords.get(0).getType()); 27 | assertEquals(2, adRecords.get(0).getLength()); 28 | 29 | type = AdRecord.TYPE_MANUFACTURER_SPECIFIC_DATA; 30 | assertEquals(type, adRecords.get(1).getType()); 31 | assertEquals(11, adRecords.get(1).getLength()); 32 | } 33 | 34 | public void testParseScanRecordAsMap() throws Exception { 35 | final Map adRecords = AdRecordUtils.parseScanRecordAsMap(NON_IBEACON); 36 | assertNotNull(adRecords); 37 | assertEquals(2, adRecords.size()); 38 | 39 | int type = AdRecord.TYPE_FLAGS; 40 | assertEquals(type, adRecords.get(type).getType()); 41 | assertEquals(2, adRecords.get(type).getLength()); 42 | 43 | type = AdRecord.TYPE_MANUFACTURER_SPECIFIC_DATA; 44 | assertEquals(type, adRecords.get(type).getType()); 45 | assertEquals(11, adRecords.get(type).getLength()); 46 | } 47 | 48 | public void testParseScanRecordAsSparseArray() throws Exception { 49 | // 50 | // Cannot be tested here as it relies on Android code... 51 | // 52 | // final SparseArray adRecords = AdRecordUtils.parseScanRecordAsSparseArray(NON_IBEACON); 53 | // assertNotNull(adRecords); 54 | // assertEquals(2, adRecords.size()); 55 | // assertEquals(AdRecord.TYPE_FLAGS, adRecords.get(AdRecord.TYPE_FLAGS).getType()); 56 | // assertEquals(AdRecord.TYPE_MANUFACTURER_SPECIFIC_DATA, adRecords.get(AdRecord.TYPE_MANUFACTURER_SPECIFIC_DATA).getType()); 57 | } 58 | } -------------------------------------------------------------------------------- /library/src/test/java/dev/alt236/bluetoothlelib/util/ByteUtilsTest.java: -------------------------------------------------------------------------------- 1 | package dev.alt236.bluetoothlelib.util; 2 | 3 | import junit.framework.TestCase; 4 | 5 | /** 6 | * 7 | */ 8 | public class ByteUtilsTest extends TestCase { 9 | 10 | public void testByteArrayToHexString() throws Exception { 11 | assertEquals("[]", ByteUtils.byteArrayToHexString(new byte[0])); 12 | 13 | assertEquals("[]", ByteUtils.byteArrayToHexString(null)); 14 | 15 | final byte[] one = {1, 10, 15, 127}; 16 | assertEquals("[01, 0A, 0F, 7F]", ByteUtils.byteArrayToHexString(one)); 17 | } 18 | 19 | public void testDoesArrayBeginWith() throws Exception { 20 | 21 | // If the prefix is longer than the array, 22 | // we automatically fail 23 | byte[] array = new byte[10]; 24 | byte[] prefix = new byte[array.length * 2]; 25 | assertFalse(ByteUtils.doesArrayBeginWith(array, prefix)); 26 | 27 | array = new byte[]{1, 2, 3}; 28 | prefix = new byte[]{1, 3}; 29 | assertFalse(ByteUtils.doesArrayBeginWith(array, prefix)); 30 | 31 | array = new byte[10]; 32 | prefix = new byte[array.length]; 33 | assertTrue(ByteUtils.doesArrayBeginWith(array, prefix)); 34 | 35 | array = new byte[]{1, 2, 3}; 36 | prefix = new byte[]{1, 2}; 37 | assertTrue(ByteUtils.doesArrayBeginWith(array, prefix)); 38 | } 39 | 40 | public void testGetIntFromByte() throws Exception { 41 | byte bite = 127; 42 | int integer = ByteUtils.getIntFromByte(bite); 43 | assertEquals(127, integer); 44 | 45 | bite = -1; 46 | integer = ByteUtils.getIntFromByte(bite); 47 | assertEquals(255, integer); 48 | } 49 | 50 | public void testInvertArray() throws Exception { 51 | final byte[] original = {1, 2 ,3 ,4}; 52 | final byte[] out = new byte[original.length]; 53 | 54 | System.arraycopy( original, 0, out, 0, original.length); 55 | ByteUtils.invertArray(out); 56 | 57 | assertEquals(original[0], out[3]); 58 | assertEquals(original[1], out[2]); 59 | assertEquals(original[2], out[1]); 60 | assertEquals(original[3], out[0]); 61 | } 62 | } -------------------------------------------------------------------------------- /sample_app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample_app/apk_v1.1.1.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/apk_v1.1.1.apk -------------------------------------------------------------------------------- /sample_app/app_v1.1.0.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/app_v1.1.0.apk -------------------------------------------------------------------------------- /sample_app/build.gradle: -------------------------------------------------------------------------------- 1 | import com.github.triplet.gradle.androidpublisher.ReleaseStatus 2 | 3 | plugins { 4 | id 'com.android.application' 5 | alias(libs.plugins.kotlin.android) 6 | alias(libs.plugins.kotlin.kapt) 7 | alias(libs.plugins.kotlin.parcelize) 8 | alias(libs.plugins.hilt.android) 9 | alias(libs.plugins.triplet.play) 10 | } 11 | 12 | apply from: "${project.rootDir}/buildsystem/android-defaults.gradle" 13 | 14 | final int versionMajor = 2 15 | final int versionMinor = 0 16 | final int versionPatch = getBuildNumber() 17 | final int androidVersionCode = getBuildNumber() 18 | 19 | final String semanticVersion = "${versionMajor}.${versionMinor}.${versionPatch}" 20 | 21 | repositories { 22 | google() 23 | mavenCentral() 24 | maven { url "https://repo.commonsware.com.s3.amazonaws.com" } 25 | maven { url "https://s3.amazonaws.com/repo.commonsware.com" } 26 | } 27 | 28 | android { 29 | buildFeatures { 30 | buildConfig = true 31 | } 32 | 33 | compileOptions { 34 | sourceCompatibility JavaVersion.VERSION_11 35 | targetCompatibility JavaVersion.VERSION_11 36 | } 37 | 38 | signingConfigs { 39 | release { 40 | storeFile file(System.getenv("ANDROID_KEYSTORE") ?: "[KEY_NOT_DEFINED]") 41 | storePassword System.getenv("KEYSTORE_PASSWORD") 42 | keyAlias System.getenv("KEY_ALIAS") 43 | keyPassword System.getenv("KEY_PASSWORD") 44 | } 45 | 46 | debug { 47 | storeFile file("${project.rootDir}/buildsystem/signing_keys/debug.keystore") 48 | keyAlias 'androiddebugkey' 49 | keyPassword 'android' 50 | storePassword 'android' 51 | } 52 | } 53 | androidResources { 54 | noCompress 'zip' 55 | } 56 | lint { 57 | lintConfig file("$rootDir/buildsystem/codequality/lint.xml") 58 | } 59 | namespace 'uk.co.alt236.btlescan' 60 | 61 | defaultConfig { 62 | versionCode androidVersionCode 63 | versionName semanticVersion 64 | } 65 | 66 | buildTypes { 67 | release { 68 | minifyEnabled false 69 | resValue "string", "app_name", "Bluetooth LE Scanner" 70 | if(isRunningOnCi()) { 71 | signingConfig signingConfigs.release 72 | } 73 | } 74 | 75 | debug { 76 | minifyEnabled false 77 | applicationIdSuffix ".debug" 78 | resValue "string", "app_name", "Debug Bluetooth LE Scanner" 79 | signingConfig signingConfigs.debug 80 | } 81 | } 82 | 83 | compileOptions { 84 | sourceCompatibility JavaVersion.VERSION_17 85 | targetCompatibility JavaVersion.VERSION_17 86 | } 87 | 88 | kotlinOptions { 89 | jvmTarget = 17 90 | } 91 | } 92 | 93 | dependencies { 94 | implementation project(':library') 95 | 96 | implementation libs.androidx.appcompat 97 | implementation libs.androidx.recyclerview 98 | implementation libs.permissionx 99 | implementation libs.easycursor.android 100 | 101 | implementation libs.hilt.android 102 | kapt libs.hilt.compiler 103 | 104 | testImplementation libs.junit4 105 | testImplementation libs.mockito 106 | } 107 | 108 | play { 109 | def credentialsPath = System.getenv("GPLAY_DEPLOY_KEY") ?: "[KEY_NOT_DEFINED]" 110 | def lastCommitMessage = getLastGitCommitMessage().take(50) 111 | 112 | logger.warn("GPP Config: $credentialsPath") 113 | logger.warn("Release Name: '$lastCommitMessage'") 114 | 115 | if(isRunningOnCi()) { 116 | enabled = true 117 | track = "internal" 118 | //userFraction = 1.0 119 | releaseStatus = ReleaseStatus.COMPLETED 120 | serviceAccountCredentials = file(credentialsPath) 121 | releaseName = lastCommitMessage 122 | artifactDir = file("${project.rootDir}/sample_app/build/outputs/apk/release/") 123 | } else { 124 | enabled = false 125 | } 126 | } -------------------------------------------------------------------------------- /sample_app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/alex/Dev/android-sdk-linux/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample_app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 11 | 12 | 13 | 14 | 17 | 18 | 19 | 20 | 21 | 24 | 25 | 31 | 32 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 45 | 46 | 49 | 50 | 53 | 54 | 59 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/containers/BluetoothLeDeviceStore.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.containers 2 | 3 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice 4 | import dev.alt236.easycursor.objectcursor.EasyObjectCursor 5 | import java.util.Collections 6 | 7 | class BluetoothLeDeviceStore { 8 | private val mDeviceMap = HashMap() 9 | 10 | fun addDevice(device: BluetoothLeDevice) { 11 | if (mDeviceMap.containsKey(device.address)) { 12 | mDeviceMap[device.address]!!.updateRssiReading(device.timestamp, device.rssi) 13 | } else { 14 | mDeviceMap[device.address] = device 15 | } 16 | } 17 | 18 | fun clear() { 19 | mDeviceMap.clear() 20 | } 21 | 22 | val size: Int 23 | get() = mDeviceMap.size 24 | 25 | val deviceCursor: EasyObjectCursor 26 | get() = getDeviceCursor(DEFAULT_COMPARATOR) 27 | 28 | fun getDeviceCursor(comparator: Comparator): EasyObjectCursor = 29 | EasyObjectCursor( 30 | BluetoothLeDevice::class.java, 31 | getDeviceList(comparator), 32 | "address", 33 | ) 34 | 35 | val deviceList: List 36 | get() = getDeviceList(DEFAULT_COMPARATOR) 37 | 38 | fun getDeviceList(comparator: Comparator): List { 39 | val methodResult: List = ArrayList(mDeviceMap.values) 40 | Collections.sort(methodResult, comparator) 41 | return methodResult 42 | } 43 | 44 | private class BluetoothLeDeviceComparator : Comparator { 45 | override fun compare( 46 | arg0: BluetoothLeDevice, 47 | arg1: BluetoothLeDevice, 48 | ): Int = arg0.address.compareTo(arg1.address) 49 | } 50 | 51 | companion object { 52 | private val DEFAULT_COMPARATOR = BluetoothLeDeviceComparator() 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/kt/ByteArrayExt.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.kt 2 | 3 | object ByteArrayExt { 4 | fun ByteArray.toCharString(): String { 5 | val chars = ArrayList(this.size) 6 | 7 | for (byte in this) { 8 | if (byte in 0..31) { 9 | val unicode = (0x2400 + byte).toChar() 10 | chars.add(unicode) 11 | } else { 12 | chars.add(byte.toChar()) 13 | } 14 | } 15 | return String(chars.toCharArray()) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/permission/BluetoothPermissionCheck.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.permission 2 | 3 | import android.Manifest 4 | import android.os.Build 5 | import androidx.fragment.app.FragmentActivity 6 | import com.permissionx.guolindev.PermissionX 7 | import uk.co.alt236.btlescan.R 8 | 9 | class BluetoothPermissionCheck { 10 | fun checkBluetoothPermissions( 11 | activity: FragmentActivity, 12 | callback: PermissionCheckResultCallback, 13 | ) { 14 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 15 | checkNeeded(activity, callback) 16 | } else { 17 | checkNotNeeded(callback) 18 | } 19 | } 20 | 21 | private fun checkNotNeeded(callback: PermissionCheckResultCallback) { 22 | callback.onSuccess() 23 | } 24 | 25 | private fun checkNeeded( 26 | activity: FragmentActivity, 27 | callback: PermissionCheckResultCallback, 28 | ) { 29 | val permissionRequest = getPermissionRequest() 30 | val appContext = activity.applicationContext 31 | 32 | PermissionX 33 | .init(activity) 34 | .permissions(permissionRequest.permissions) 35 | .onExplainRequestReason { scope, deniedList -> 36 | scope.showRequestReasonDialog( 37 | deniedList, 38 | message = appContext.getString(permissionRequest.permissionRationaleResId), 39 | positiveText = appContext.getString(android.R.string.ok), 40 | negativeText = appContext.getString(android.R.string.cancel), 41 | ) 42 | }.onForwardToSettings { scope, deniedList -> 43 | scope.showForwardToSettingsDialog( 44 | deniedList, 45 | appContext.getString(permissionRequest.permissionNeedToGoToSettings), 46 | positiveText = appContext.getString(android.R.string.ok), 47 | negativeText = appContext.getString(android.R.string.cancel), 48 | ) 49 | }.request { allGranted, _, _ -> 50 | if (allGranted) { 51 | callback.onSuccess() 52 | } else { 53 | val notGrantedMessage = appContext.getString(permissionRequest.notGrantedResId) 54 | callback.onFailure(notGrantedMessage) 55 | } 56 | } 57 | } 58 | 59 | private fun getPermissionRequest(): PermissionRequest { 60 | val permissions: List 61 | val notGrantedResId: Int 62 | 63 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 64 | permissions = 65 | listOf( 66 | Manifest.permission.BLUETOOTH_CONNECT, 67 | Manifest.permission.BLUETOOTH_SCAN, 68 | Manifest.permission.ACCESS_FINE_LOCATION, 69 | ) 70 | notGrantedResId = R.string.permission_not_granted_bt_scan 71 | } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { 72 | permissions = listOf(Manifest.permission.ACCESS_FINE_LOCATION) 73 | notGrantedResId = R.string.permission_not_granted_fine_location 74 | } else { 75 | permissions = listOf(Manifest.permission.ACCESS_COARSE_LOCATION) 76 | notGrantedResId = R.string.permission_not_granted_coarse_location 77 | } 78 | 79 | return PermissionRequest( 80 | permissions = permissions, 81 | notGrantedResId = notGrantedResId, 82 | permissionRationaleResId = R.string.permission_rationale, 83 | permissionNeedToGoToSettings = R.string.permission_need_to_go_to_settings, 84 | ) 85 | } 86 | 87 | private data class PermissionRequest( 88 | val permissions: List, 89 | val notGrantedResId: Int, 90 | val permissionRationaleResId: Int, 91 | val permissionNeedToGoToSettings: Int, 92 | ) 93 | 94 | interface PermissionCheckResultCallback { 95 | fun onSuccess() 96 | 97 | fun onFailure(message: CharSequence) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/permission/PermissionDeniedDialogFragment.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.permission 2 | 3 | import android.app.Dialog 4 | import android.os.Bundle 5 | import androidx.appcompat.app.AlertDialog 6 | import androidx.fragment.app.DialogFragment 7 | 8 | class PermissionDeniedDialogFragment : DialogFragment() { 9 | override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = 10 | AlertDialog 11 | .Builder(requireContext()) 12 | .setMessage(requireArguments().getCharSequence(EXTRA_MESSAGE)) 13 | .setPositiveButton(getString(android.R.string.ok)) { _, _ -> } 14 | .create() 15 | 16 | companion object { 17 | private val EXTRA_MESSAGE = 18 | PermissionDeniedDialogFragment::class.java.name + ".EXTRA_MESSAGE" 19 | 20 | @JvmStatic 21 | fun create(message: CharSequence): DialogFragment { 22 | val fragment = PermissionDeniedDialogFragment() 23 | val args = Bundle() 24 | args.putCharSequence(EXTRA_MESSAGE, message) 25 | fragment.arguments = args 26 | return fragment 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/services/LocalBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.services 2 | 3 | import android.os.Binder 4 | 5 | class LocalBinder( 6 | val service: BluetoothLeService, 7 | ) : Binder() 8 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/services/State.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.services 2 | 3 | internal enum class State { 4 | DISCONNECTED, 5 | CONNECTING, 6 | CONNECTED, 7 | } 8 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/IntentReceiverCompat.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.Activity 5 | import android.content.BroadcastReceiver 6 | import android.content.Context 7 | import android.content.IntentFilter 8 | import android.os.Build 9 | 10 | object IntentReceiverCompat { 11 | @SuppressLint("UnspecifiedRegisterReceiverFlag") 12 | @JvmStatic 13 | fun registerExportedReceiver( 14 | activity: Activity, 15 | receiver: BroadcastReceiver, 16 | filter: IntentFilter, 17 | ) { 18 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 19 | activity.registerReceiver( 20 | receiver, 21 | filter, 22 | Context.RECEIVER_EXPORTED, 23 | ) 24 | } else { 25 | activity.registerExportUnawareReceiver(receiver, filter) 26 | } 27 | } 28 | 29 | @SuppressLint("UnspecifiedRegisterReceiverFlag") 30 | private fun Activity.registerExportUnawareReceiver( 31 | receiver: BroadcastReceiver, 32 | filter: IntentFilter, 33 | ) { 34 | this.registerReceiver( 35 | receiver, 36 | filter, 37 | ) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/Navigation.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.net.Uri 6 | import androidx.core.app.ActivityCompat 7 | import androidx.core.app.ShareCompat 8 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice 9 | import uk.co.alt236.btlescan.R 10 | import uk.co.alt236.btlescan.ui.control.DeviceControlActivity 11 | import uk.co.alt236.btlescan.ui.details.DeviceDetailsActivity 12 | 13 | class Navigation( 14 | private val activity: Activity, 15 | ) { 16 | fun openDetailsActivity(device: BluetoothLeDevice?) { 17 | val intent = DeviceDetailsActivity.createIntent(activity, device) 18 | startActivity(intent) 19 | } 20 | 21 | fun startControlActivity(device: BluetoothLeDevice?) { 22 | val intent = DeviceControlActivity.createIntent(activity, device) 23 | startActivity(intent) 24 | } 25 | 26 | fun shareFileViaEmail( 27 | uri: Uri, 28 | recipient: Array?, 29 | subject: String?, 30 | message: String?, 31 | ) { 32 | val intent = 33 | ShareCompat.IntentBuilder 34 | .from(activity) 35 | .setChooserTitle(R.string.exporter_email_device_list_picker_text) 36 | .setStream(uri) 37 | .setEmailTo(recipient ?: emptyArray()) 38 | .setSubject(subject ?: "") 39 | .setText(message ?: "") 40 | .setType("text/text") 41 | .intent 42 | .setAction(Intent.ACTION_SEND) 43 | .setDataAndType(uri, "plain/text") 44 | .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 45 | 46 | startActivity(intent) 47 | } 48 | 49 | private fun startActivity(intent: Intent) { 50 | ActivityCompat.startActivity(activity, intent, null) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/recyclerview/BaseRecyclerViewAdapter.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common.recyclerview 2 | 3 | import android.view.ViewGroup 4 | import androidx.recyclerview.widget.RecyclerView 5 | 6 | abstract class BaseRecyclerViewAdapter 7 | @JvmOverloads 8 | constructor( 9 | private val core: RecyclerViewBinderCore, 10 | items: List = ArrayList(), 11 | ) : RecyclerView.Adapter>() { 12 | private val list = ArrayList() 13 | 14 | init { 15 | list.addAll(items) 16 | } 17 | 18 | override fun onCreateViewHolder( 19 | parent: ViewGroup, 20 | viewType: Int, 21 | ): BaseViewHolder = core.create(parent, viewType) 22 | 23 | override fun onBindViewHolder( 24 | holder: BaseViewHolder, 25 | position: Int, 26 | ) { 27 | val viewType = getItemViewType(position) 28 | val binder = core.getBinder(viewType) 29 | 30 | bind(binder, holder, getItem(position)) 31 | } 32 | 33 | override fun getItemCount(): Int = list.size 34 | 35 | override fun getItemViewType(position: Int): Int = core.getViewType(getItem(position)) 36 | 37 | fun getItem(position: Int): RecyclerViewItem? = list[position] 38 | 39 | fun setData(data: Collection) { 40 | list.clear() 41 | list.addAll(data) 42 | notifyDataSetChanged() 43 | } 44 | 45 | companion object { 46 | private fun bind( 47 | binder: BaseViewBinder, 48 | holder: BaseViewHolder<*>, 49 | item: RecyclerViewItem?, 50 | ) { 51 | @Suppress("UNCHECKED_CAST") 52 | binder.bind((holder as BaseViewHolder), item as T) 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/recyclerview/BaseViewBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common.recyclerview 2 | 3 | import android.content.Context 4 | import androidx.annotation.StringRes 5 | import uk.co.alt236.btlescan.R 6 | 7 | abstract class BaseViewBinder( 8 | protected val context: Context, 9 | ) { 10 | abstract fun bind( 11 | holder: BaseViewHolder, 12 | item: T, 13 | ) 14 | 15 | abstract fun canBind(item: RecyclerViewItem): Boolean 16 | 17 | protected fun getString( 18 | @StringRes id: Int, 19 | ): String = context.getString(id) 20 | 21 | protected fun getString( 22 | @StringRes resId: Int, 23 | vararg formatArgs: Any?, 24 | ): String = context.getString(resId, *formatArgs) 25 | 26 | protected fun getQuotedString(vararg formatArgs: Any?): String = getString(R.string.formatter_single_quoted_string, *formatArgs) 27 | } 28 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/recyclerview/BaseViewHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common.recyclerview 2 | 3 | import android.view.View 4 | import androidx.recyclerview.widget.RecyclerView.ViewHolder 5 | 6 | abstract class BaseViewHolder( 7 | val view: View, 8 | ) : ViewHolder(view) 9 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/recyclerview/RecyclerViewBinderCore.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common.recyclerview; 2 | 3 | import android.util.Log; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | 8 | import java.lang.reflect.Constructor; 9 | import java.lang.reflect.InvocationTargetException; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public class RecyclerViewBinderCore { 14 | public static final int INVALID_VIEWTYPE = -1; 15 | 16 | private static final String TAG = RecyclerViewBinderCore.class.getSimpleName(); 17 | private final List>> mViewHolderClasses; 18 | private final List> mViewBinders; 19 | private final List mLayoutIds; 20 | 21 | public RecyclerViewBinderCore() { 22 | mViewBinders = new ArrayList<>(); 23 | mViewHolderClasses = new ArrayList<>(); 24 | mLayoutIds = new ArrayList<>(); 25 | } 26 | 27 | public void clear() { 28 | mViewBinders.clear(); 29 | mViewHolderClasses.clear(); 30 | mLayoutIds.clear(); 31 | } 32 | 33 | public void add( 34 | final BaseViewBinder binder, 35 | final Class> viewHolder, 36 | final int layoutId) { 37 | 38 | mViewBinders.add(binder); 39 | mViewHolderClasses.add(viewHolder); 40 | mLayoutIds.add(layoutId); 41 | } 42 | 43 | public BaseViewHolder create(ViewGroup parent, final int viewType) { 44 | if (viewType == INVALID_VIEWTYPE) { 45 | throw new IllegalArgumentException("Invalid viewType: " + viewType); 46 | } 47 | 48 | final Class clazz = mViewHolderClasses.get(viewType); 49 | final int layoutId = mLayoutIds.get(viewType); 50 | final View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false); 51 | 52 | return (BaseViewHolder) instantiate(clazz, itemView); 53 | } 54 | 55 | public int getViewType(final T item) { 56 | int result = INVALID_VIEWTYPE; 57 | int count = 0; 58 | 59 | for (final BaseViewBinder binder : mViewBinders) { 60 | 61 | if (binder.canBind(item)) { 62 | result = count; 63 | break; 64 | } 65 | 66 | count++; 67 | } 68 | 69 | if (result == INVALID_VIEWTYPE) { 70 | Log.w(TAG, "Could not get viewType for " + item); 71 | } 72 | 73 | return result; 74 | } 75 | 76 | public BaseViewBinder getBinder(int viewType) { 77 | if (viewType == INVALID_VIEWTYPE) { 78 | throw new IllegalArgumentException("Invalid viewType: " + viewType); 79 | } 80 | 81 | return mViewBinders.get(viewType); 82 | } 83 | 84 | @SuppressWarnings("TryWithIdenticalCatches") 85 | private static Object instantiate( 86 | final Class clazz, View parentView) { 87 | try { 88 | final Constructor constructor = clazz.getDeclaredConstructors()[0]; 89 | return constructor.newInstance(parentView); 90 | } catch (InstantiationException e) { 91 | throw new IllegalStateException(e); 92 | } catch (IllegalAccessException e) { 93 | throw new IllegalStateException(e); 94 | } catch (InvocationTargetException e) { 95 | throw new IllegalStateException(e); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/common/recyclerview/RecyclerViewItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.common.recyclerview 2 | 3 | interface RecyclerViewItem 4 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/control/Exporter.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.control; 2 | 3 | import android.bluetooth.BluetoothGattCharacteristic; 4 | import android.bluetooth.BluetoothGattService; 5 | import android.content.Context; 6 | 7 | import java.util.List; 8 | 9 | import dev.alt236.bluetoothlelib.resolvers.GattAttributeResolver; 10 | import uk.co.alt236.btlescan.R; 11 | 12 | /*package*/ class Exporter { 13 | private final Context mContext; 14 | 15 | public Exporter(final Context context) { 16 | mContext = context.getApplicationContext(); 17 | } 18 | 19 | public String generateExportString(final String deviceName, 20 | final String deviceAddress, 21 | final List gattServices) { 22 | 23 | final String unknownServiceString = mContext.getString(R.string.unknown_service); 24 | final String unknownCharaString = mContext.getString(R.string.unknown_characteristic); 25 | final StringBuilder exportBuilder = new StringBuilder(); 26 | 27 | exportBuilder.append("Device Name: "); 28 | exportBuilder.append(deviceName); 29 | exportBuilder.append('\n'); 30 | exportBuilder.append("Device Address: "); 31 | exportBuilder.append(deviceAddress); 32 | exportBuilder.append('\n'); 33 | exportBuilder.append('\n'); 34 | 35 | exportBuilder.append("Services:"); 36 | exportBuilder.append("--------------------------"); 37 | exportBuilder.append('\n'); 38 | 39 | String uuid = null; 40 | for (final BluetoothGattService gattService : gattServices) { 41 | uuid = gattService.getUuid().toString(); 42 | 43 | exportBuilder.append(GattAttributeResolver.getAttributeName(uuid, unknownServiceString)); 44 | exportBuilder.append(" ("); 45 | exportBuilder.append(uuid); 46 | exportBuilder.append(')'); 47 | exportBuilder.append('\n'); 48 | 49 | final List gattCharacteristics = gattService.getCharacteristics(); 50 | for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { 51 | uuid = gattCharacteristic.getUuid().toString(); 52 | 53 | exportBuilder.append('\t'); 54 | exportBuilder.append(GattAttributeResolver.getAttributeName(uuid, unknownCharaString)); 55 | exportBuilder.append(" ("); 56 | exportBuilder.append(uuid); 57 | exportBuilder.append(')'); 58 | exportBuilder.append('\n'); 59 | } 60 | 61 | exportBuilder.append('\n'); 62 | exportBuilder.append('\n'); 63 | } 64 | 65 | exportBuilder.append("--------------------------"); 66 | exportBuilder.append('\n'); 67 | 68 | return exportBuilder.toString(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/control/GattDataAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.control; 2 | 3 | import android.bluetooth.BluetoothGattCharacteristic; 4 | import android.bluetooth.BluetoothGattService; 5 | import android.content.Context; 6 | import android.widget.SimpleExpandableListAdapter; 7 | 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | import dev.alt236.bluetoothlelib.resolvers.GattAttributeResolver; 14 | import uk.co.alt236.btlescan.R; 15 | 16 | /*package*/ class GattDataAdapterFactory { 17 | private static final String LIST_NAME = "NAME"; 18 | private static final String LIST_UUID = "UUID"; 19 | 20 | public static GattDataAdapter createAdapter(final Context context, 21 | final List gattServices) { 22 | 23 | 24 | final String unknownServiceString = context.getString(R.string.unknown_service); 25 | final String unknownCharaString = context.getString(R.string.unknown_characteristic); 26 | final List> gattServiceData = new ArrayList<>(); 27 | final List>> gattCharacteristicData = new ArrayList<>(); 28 | final List> fullGattCharacteristics = new ArrayList<>(); 29 | 30 | // Loops through available GATT Services. 31 | String uuid; 32 | for (final BluetoothGattService gattService : gattServices) { 33 | final Map currentServiceData = new HashMap<>(); 34 | uuid = gattService.getUuid().toString(); 35 | currentServiceData.put(LIST_NAME, GattAttributeResolver.getAttributeName(uuid, unknownServiceString)); 36 | currentServiceData.put(LIST_UUID, uuid); 37 | gattServiceData.add(currentServiceData); 38 | 39 | final List> gattCharacteristicGroupData = new ArrayList<>(); 40 | final List gattCharacteristics = gattService.getCharacteristics(); 41 | final List charas = new ArrayList<>(); 42 | 43 | // Loops through available Characteristics. 44 | for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { 45 | charas.add(gattCharacteristic); 46 | final Map currentCharaData = new HashMap<>(); 47 | uuid = gattCharacteristic.getUuid().toString(); 48 | currentCharaData.put(LIST_NAME, GattAttributeResolver.getAttributeName(uuid, unknownCharaString)); 49 | currentCharaData.put(LIST_UUID, uuid); 50 | gattCharacteristicGroupData.add(currentCharaData); 51 | } 52 | 53 | fullGattCharacteristics.add(charas); 54 | gattCharacteristicData.add(gattCharacteristicGroupData); 55 | } 56 | 57 | return new GattDataAdapter( 58 | context, 59 | fullGattCharacteristics, 60 | gattServiceData, 61 | android.R.layout.simple_expandable_list_item_2, 62 | new String[]{LIST_NAME, LIST_UUID}, 63 | new int[]{android.R.id.text1, android.R.id.text2}, 64 | gattCharacteristicData, 65 | android.R.layout.simple_expandable_list_item_2, 66 | new String[]{LIST_NAME, LIST_UUID}, 67 | new int[]{android.R.id.text1, android.R.id.text2} 68 | ); 69 | } 70 | 71 | 72 | public static class GattDataAdapter extends SimpleExpandableListAdapter { 73 | 74 | private final List> mGattCharacteristics; 75 | 76 | public GattDataAdapter(Context context, 77 | List> gattCharacteristics, 78 | List> groupData, 79 | int groupLayout, String[] groupFrom, 80 | int[] groupTo, 81 | List>> childData, 82 | int childLayout, 83 | String[] childFrom, 84 | int[] childTo) { 85 | 86 | super(context, groupData, groupLayout, groupFrom, groupTo, childData, childLayout, childFrom, childTo); 87 | mGattCharacteristics = gattCharacteristics; 88 | } 89 | 90 | public BluetoothGattCharacteristic getBluetoothGattCharacteristic(final int groupPosition, final int childPosition) { 91 | return mGattCharacteristics.get(groupPosition).get(childPosition); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/control/State.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.control 2 | 3 | internal enum class State { 4 | DISCONNECTED, 5 | CONNECTING, 6 | CONNECTED, 7 | } 8 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/control/View.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.control 2 | 3 | import android.app.Activity 4 | import android.widget.ExpandableListView 5 | import android.widget.SimpleExpandableListAdapter 6 | import android.widget.TextView 7 | import androidx.core.content.res.ResourcesCompat 8 | import dev.alt236.bluetoothlelib.resolvers.GattAttributeResolver 9 | import dev.alt236.bluetoothlelib.util.ByteUtils 10 | import uk.co.alt236.btlescan.R 11 | import uk.co.alt236.btlescan.kt.ByteArrayExt.toCharString 12 | import java.nio.charset.Charset 13 | 14 | internal class View( 15 | activity: Activity, 16 | ) { 17 | private val resources = activity.resources 18 | private val mGattServicesList: ExpandableListView = activity.findViewById(R.id.gatt_services_list) 19 | private var mConnectionState: TextView = activity.findViewById(R.id.connection_state) 20 | private var mGattUUID: TextView = activity.findViewById(R.id.uuid) 21 | private var mGattUUIDDesc: TextView = activity.findViewById(R.id.description) 22 | private var mDataAsString: TextView = activity.findViewById(R.id.data_as_string) 23 | private var mDataAsArray: TextView = activity.findViewById(R.id.data_as_array) 24 | private var mDataAsChars: TextView = activity.findViewById(R.id.data_as_characters) 25 | 26 | fun clearUi() { 27 | mGattServicesList.setAdapter(null as SimpleExpandableListAdapter?) 28 | mGattUUID.setText(R.string.no_data) 29 | mGattUUIDDesc.setText(R.string.no_data) 30 | mDataAsArray.setText(R.string.no_data) 31 | mDataAsString.setText(R.string.no_data) 32 | mDataAsChars.setText(R.string.no_data) 33 | } 34 | 35 | fun setConnectionState(state: State) { 36 | val colourId: Int 37 | val resId: Int 38 | 39 | when (state) { 40 | State.CONNECTED -> { 41 | colourId = android.R.color.holo_green_dark 42 | resId = R.string.connected 43 | } 44 | State.DISCONNECTED -> { 45 | colourId = android.R.color.holo_red_dark 46 | resId = R.string.disconnected 47 | } 48 | State.CONNECTING -> { 49 | colourId = android.R.color.holo_orange_dark 50 | resId = R.string.connecting 51 | } 52 | } 53 | 54 | mConnectionState.setText(resId) 55 | mConnectionState.setTextColor(ResourcesCompat.getColor(resources, colourId, null)) 56 | } 57 | 58 | fun setGattUuid(uuid: String?) { 59 | mGattUUID.text = uuid ?: resources.getString(R.string.no_data) 60 | mGattUUIDDesc.text = GattAttributeResolver.getAttributeName(uuid, resources.getString(R.string.unknown)) 61 | } 62 | 63 | fun setData(bytes: ByteArray?) { 64 | val safeBytes = bytes ?: ByteArray(0) 65 | 66 | mDataAsArray.text = quoteString(ByteUtils.byteArrayToHexString(safeBytes)) 67 | mDataAsString.text = quoteString(safeBytes.toString(Charset.forName("UTF-8"))) 68 | mDataAsChars.text = quoteString(safeBytes.toCharString()) 69 | } 70 | 71 | fun setListAdapter(adapter: SimpleExpandableListAdapter) { 72 | mGattServicesList.setAdapter(adapter) 73 | } 74 | 75 | fun setListClickListener(listener: ExpandableListView.OnChildClickListener) { 76 | mGattServicesList.setOnChildClickListener(listener) 77 | } 78 | 79 | private fun quoteString(string: String): String = resources.getString(R.string.formatter_single_quoted_string, string) 80 | } 81 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/DetailsRecyclerAdapter.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details 2 | 3 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseRecyclerViewAdapter 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewBinderCore 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 6 | 7 | internal class DetailsRecyclerAdapter( 8 | core: RecyclerViewBinderCore, 9 | items: List, 10 | ) : BaseRecyclerViewAdapter(core, items) 11 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/RecyclerViewCoreFactory.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details; 2 | 3 | import android.content.Context; 4 | 5 | import uk.co.alt236.btlescan.R; 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewBinderCore; 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.binder.AdRecordBinder; 8 | import uk.co.alt236.btlescan.ui.details.recyclerview.binder.DeviceInfoBinder; 9 | import uk.co.alt236.btlescan.ui.details.recyclerview.binder.HeaderBinder; 10 | import uk.co.alt236.btlescan.ui.details.recyclerview.binder.IBeaconBinder; 11 | import uk.co.alt236.btlescan.ui.details.recyclerview.binder.RssiBinder; 12 | import uk.co.alt236.btlescan.ui.details.recyclerview.binder.TextBinder; 13 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.AdRecordHolder; 14 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.DeviceInfoHolder; 15 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.HeaderHolder; 16 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.IBeaconHolder; 17 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.RssiInfoHolder; 18 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.TextHolder; 19 | 20 | /*protected*/ final class RecyclerViewCoreFactory { 21 | 22 | public static RecyclerViewBinderCore create(final Context context) { 23 | final RecyclerViewBinderCore core = new RecyclerViewBinderCore(); 24 | 25 | core.add(new TextBinder(context), TextHolder.class, R.layout.list_item_view_textview); 26 | core.add(new HeaderBinder(context), HeaderHolder.class, R.layout.list_item_view_header); 27 | core.add(new AdRecordBinder(context), AdRecordHolder.class, R.layout.list_item_view_adrecord); 28 | core.add(new RssiBinder(context), RssiInfoHolder.class, R.layout.list_item_view_rssi_info); 29 | core.add(new DeviceInfoBinder(context), DeviceInfoHolder.class, R.layout.list_item_view_device_info); 30 | core.add(new IBeaconBinder(context), IBeaconHolder.class, R.layout.list_item_view_ibeacon_details); 31 | 32 | return core; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/AdRecordBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.binder 2 | 3 | import android.content.Context 4 | import dev.alt236.bluetoothlelib.util.ByteUtils 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 8 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.AdRecordHolder 9 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.AdRecordItem 10 | 11 | class AdRecordBinder( 12 | context: Context, 13 | ) : BaseViewBinder(context) { 14 | override fun bind( 15 | holder: BaseViewHolder, 16 | item: AdRecordItem, 17 | ) { 18 | val actualHolder = holder as AdRecordHolder 19 | 20 | actualHolder.titleTextView.text = item.title 21 | actualHolder.lengthTextView.text = item.data.size.toString() 22 | 23 | actualHolder.stringTextView.text = getQuotedString(item.dataAsString) 24 | 25 | val hexString = ByteUtils.byteArrayToHexString(item.data) 26 | actualHolder.arrayTextView.text = getQuotedString(hexString) 27 | 28 | val charString = item.dataAsChars 29 | actualHolder.charactersTextView.text = getQuotedString(charString) 30 | } 31 | 32 | override fun canBind(item: RecyclerViewItem): Boolean = item is AdRecordItem 33 | } 34 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/DeviceInfoBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.binder 2 | 3 | import android.content.Context 4 | import uk.co.alt236.btlescan.R 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 8 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.DeviceInfoHolder 9 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.DeviceInfoItem 10 | 11 | class DeviceInfoBinder( 12 | context: Context, 13 | ) : BaseViewBinder(context) { 14 | override fun bind( 15 | holder: BaseViewHolder, 16 | item: DeviceInfoItem, 17 | ) { 18 | val actualHolder = holder as DeviceInfoHolder 19 | actualHolder.name.text = item.name 20 | actualHolder.address.text = item.address 21 | actualHolder.deviceClass.text = item.bluetoothDeviceClassName 22 | actualHolder.majorClass.text = item.bluetoothDeviceMajorClassName 23 | actualHolder.bondingState.text = item.bluetoothDeviceBondState 24 | actualHolder.services.text = createSupportedDevicesString(item) 25 | } 26 | 27 | private fun createSupportedDevicesString(item: DeviceInfoItem): String { 28 | val retVal: String 29 | retVal = 30 | if (item.bluetoothDeviceKnownSupportedServices.isEmpty()) { 31 | context.getString(R.string.no_known_services) 32 | } else { 33 | val sb = StringBuilder() 34 | for (service in item.bluetoothDeviceKnownSupportedServices) { 35 | if (sb.isNotEmpty()) { 36 | sb.append(", ") 37 | } 38 | sb.append(service) 39 | } 40 | sb.toString() 41 | } 42 | return retVal 43 | } 44 | 45 | override fun canBind(item: RecyclerViewItem): Boolean = item is DeviceInfoItem 46 | } 47 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/HeaderBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.binder 2 | 3 | import android.content.Context 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.HeaderHolder 8 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.HeaderItem 9 | 10 | class HeaderBinder( 11 | context: Context, 12 | ) : BaseViewBinder(context) { 13 | override fun bind( 14 | holder: BaseViewHolder, 15 | item: HeaderItem, 16 | ) { 17 | val actualHolder = holder as HeaderHolder 18 | actualHolder.textView.text = item.text 19 | } 20 | 21 | override fun canBind(item: RecyclerViewItem): Boolean = item is HeaderItem 22 | } 23 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/IBeaconBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.binder 2 | 3 | import android.content.Context 4 | import dev.alt236.bluetoothlelib.resolvers.CompanyIdentifierResolver 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 7 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 8 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 9 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.IBeaconHolder 10 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.IBeaconItem 11 | import uk.co.alt236.btlescan.util.TimeFormatter 12 | import java.util.Locale 13 | 14 | class IBeaconBinder( 15 | context: Context, 16 | ) : BaseViewBinder(context) { 17 | override fun bind( 18 | holder: BaseViewHolder, 19 | item: IBeaconItem, 20 | ) { 21 | val actualHolder = holder as IBeaconHolder 22 | val companyName = 23 | CompanyIdentifierResolver.getCompanyName( 24 | item.companyIdentifier, 25 | context.getString(R.string.unknown), 26 | ) 27 | actualHolder.companyId.text = getWithHexEncode(companyName, item.companyIdentifier) 28 | actualHolder.advert.text = getWithHexEncode(item.iBeaconAdvertisement) 29 | actualHolder.uuid.text = item.uuid 30 | actualHolder.major.text = getWithHexEncode(item.major) 31 | actualHolder.minor.text = getWithHexEncode(item.minor) 32 | actualHolder.txPower.text = getWithHexEncode(item.calibratedTxPower) 33 | } 34 | 35 | override fun canBind(item: RecyclerViewItem): Boolean = item is IBeaconItem 36 | 37 | companion object { 38 | private const val STRING_FORMAT = "%s (%s)" 39 | 40 | private fun formatTime(time: Long): String = TimeFormatter.getIsoDateTime(time) 41 | 42 | private fun getWithHexEncode( 43 | first: String, 44 | value: Int, 45 | ): String = createLine(first, hexEncode(value)) 46 | 47 | private fun getWithHexEncode(value: Int): String = createLine(value.toString(), hexEncode(value)) 48 | 49 | private fun createLine( 50 | first: String, 51 | second: String, 52 | ): String = String.format(Locale.US, STRING_FORMAT, first, second) 53 | 54 | private fun hexEncode(integer: Int): String = "0x" + Integer.toHexString(integer).toUpperCase(Locale.US) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/RssiBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.binder 2 | 3 | import android.content.Context 4 | import uk.co.alt236.btlescan.R 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 8 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.RssiInfoHolder 9 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.RssiItem 10 | import uk.co.alt236.btlescan.util.TimeFormatter 11 | 12 | class RssiBinder( 13 | context: Context, 14 | ) : BaseViewBinder(context) { 15 | override fun bind( 16 | holder: BaseViewHolder, 17 | item: RssiItem, 18 | ) { 19 | val actualHolder = holder as RssiInfoHolder 20 | actualHolder.firstTimestamp.text = formatTime(item.firstTimestamp) 21 | actualHolder.firstRssi.text = formatRssi(item.firstRssi) 22 | actualHolder.lastTimestamp.text = formatTime(item.timestamp) 23 | actualHolder.lastRssi.text = formatRssi(item.rssi) 24 | actualHolder.runningAverageRssi.text = formatRssi(item.runningAverageRssi) 25 | } 26 | 27 | override fun canBind(item: RecyclerViewItem): Boolean = item is RssiItem 28 | 29 | private fun formatRssi(rssi: Double): String = getString(R.string.formatter_db, rssi.toString()) 30 | 31 | private fun formatRssi(rssi: Int): String = getString(R.string.formatter_db, rssi.toString()) 32 | 33 | companion object { 34 | private fun formatTime(time: Long): String = TimeFormatter.getIsoDateTime(time) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/TextBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.binder 2 | 3 | import android.content.Context 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.holder.TextHolder 8 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.TextItem 9 | 10 | class TextBinder( 11 | context: Context, 12 | ) : BaseViewBinder(context) { 13 | override fun bind( 14 | holder: BaseViewHolder, 15 | item: TextItem, 16 | ) { 17 | val actualHolder = holder as TextHolder 18 | actualHolder.textView.text = item.text 19 | } 20 | 21 | override fun canBind(item: RecyclerViewItem): Boolean = item is TextItem 22 | } 23 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/AdRecordHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.AdRecordItem 8 | 9 | class AdRecordHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView) { 12 | val stringTextView: TextView = itemView.findViewById(R.id.data_as_string) as TextView 13 | val lengthTextView: TextView = itemView.findViewById(R.id.length) as TextView 14 | val arrayTextView: TextView = itemView.findViewById(R.id.data_as_array) as TextView 15 | val charactersTextView: TextView = itemView.findViewById(R.id.data_as_characters) as TextView 16 | val titleTextView: TextView = itemView.findViewById(R.id.title) as TextView 17 | } 18 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/DeviceInfoHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.DeviceInfoItem 8 | 9 | class DeviceInfoHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView) { 12 | val name: TextView = itemView.findViewById(R.id.deviceName) as TextView 13 | val address: TextView = itemView.findViewById(R.id.deviceAddress) as TextView 14 | val deviceClass: TextView = itemView.findViewById(R.id.deviceClass) as TextView 15 | val majorClass: TextView = itemView.findViewById(R.id.deviceMajorClass) as TextView 16 | val services: TextView = itemView.findViewById(R.id.deviceServiceList) as TextView 17 | val bondingState: TextView = itemView.findViewById(R.id.deviceBondingState) as TextView 18 | } 19 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/HeaderHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.HeaderItem 8 | 9 | class HeaderHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView) { 12 | val textView: TextView = itemView.findViewById(R.id.text) as TextView 13 | } 14 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/IBeaconHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.IBeaconItem 8 | 9 | class IBeaconHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView) { 12 | val companyId: TextView = itemView.findViewById(R.id.companyId) as TextView 13 | val advert: TextView = itemView.findViewById(R.id.advertisement) as TextView 14 | val uuid: TextView = itemView.findViewById(R.id.uuid) as TextView 15 | val major: TextView = itemView.findViewById(R.id.major) as TextView 16 | val minor: TextView = itemView.findViewById(R.id.minor) as TextView 17 | val txPower: TextView = itemView.findViewById(R.id.txpower) as TextView 18 | } 19 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/RssiInfoHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.RssiItem 8 | 9 | class RssiInfoHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView) { 12 | val firstTimestamp: TextView = itemView.findViewById(R.id.firstTimestamp) as TextView 13 | val firstRssi: TextView = itemView.findViewById(R.id.firstRssi) as TextView 14 | val lastTimestamp: TextView = itemView.findViewById(R.id.lastTimestamp) as TextView 15 | val lastRssi: TextView = itemView.findViewById(R.id.lastRssi) as TextView 16 | val runningAverageRssi: TextView = itemView.findViewById(R.id.runningAverageRssi) as TextView 17 | } 18 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/TextHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.details.recyclerview.model.TextItem 8 | 9 | class TextHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView) { 12 | val textView: TextView = itemView.findViewById(R.id.text) as TextView 13 | } 14 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/model/AdRecordItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.model 2 | 3 | import dev.alt236.bluetoothlelib.device.adrecord.AdRecord 4 | import dev.alt236.bluetoothlelib.util.AdRecordUtils 5 | import uk.co.alt236.btlescan.kt.ByteArrayExt.toCharString 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 7 | 8 | class AdRecordItem( 9 | val title: String, 10 | record: AdRecord, 11 | ) : RecyclerViewItem { 12 | val data: ByteArray = record.data ?: ByteArray(0) 13 | val dataAsString: String = AdRecordUtils.getRecordDataAsString(record) 14 | val dataAsChars: String = data.toCharString() 15 | } 16 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/model/DeviceInfoItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.model 2 | 3 | import android.annotation.SuppressLint 4 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice 5 | import dev.alt236.bluetoothlelib.device.BluetoothService 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 7 | 8 | @SuppressLint("MissingPermission") // We check before this is called 9 | class DeviceInfoItem( 10 | private val mDevice: BluetoothLeDevice, 11 | ) : RecyclerViewItem { 12 | val bluetoothDeviceKnownSupportedServices: Set 13 | get() = mDevice.bluetoothDeviceKnownSupportedServices 14 | 15 | val bluetoothDeviceBondState: String 16 | get() = mDevice.bluetoothDeviceBondState 17 | 18 | val bluetoothDeviceMajorClassName: String 19 | get() = mDevice.bluetoothDeviceMajorClassName 20 | 21 | val bluetoothDeviceClassName: String 22 | get() = mDevice.bluetoothDeviceClassName 23 | 24 | val address: String 25 | get() = mDevice.address 26 | 27 | val name: String 28 | get() = mDevice.name ?: "" 29 | } 30 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/model/HeaderItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.model 2 | 3 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 4 | 5 | class HeaderItem( 6 | val text: CharSequence, 7 | ) : RecyclerViewItem 8 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/model/IBeaconItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.model 2 | 3 | import dev.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconManufacturerData 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 5 | 6 | class IBeaconItem( 7 | iBeaconData: IBeaconManufacturerData, 8 | ) : RecyclerViewItem { 9 | val major: Int = iBeaconData.major 10 | val minor: Int = iBeaconData.minor 11 | val uuid: String = iBeaconData.uuid 12 | val companyIdentifier: Int = iBeaconData.companyIdentifier 13 | val iBeaconAdvertisement: Int = iBeaconData.iBeaconAdvertisement 14 | val calibratedTxPower: Int = iBeaconData.calibratedTxPower 15 | } 16 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/model/RssiItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.model 2 | 3 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 5 | 6 | class RssiItem( 7 | private val mDevice: BluetoothLeDevice, 8 | ) : RecyclerViewItem { 9 | val rssi: Int 10 | get() = mDevice.rssi 11 | 12 | val runningAverageRssi: Double 13 | get() = mDevice.runningAverageRssi 14 | 15 | val firstRssi: Int 16 | get() = mDevice.firstRssi 17 | 18 | val firstTimestamp: Long 19 | get() = mDevice.firstTimestamp 20 | 21 | val timestamp: Long 22 | get() = mDevice.timestamp 23 | } 24 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/model/TextItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.details.recyclerview.model 2 | 3 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 4 | 5 | class TextItem( 6 | val text: CharSequence, 7 | ) : RecyclerViewItem 8 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/DeviceRecyclerAdapter.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main 2 | 3 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseRecyclerViewAdapter 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewBinderCore 5 | 6 | internal class DeviceRecyclerAdapter( 7 | core: RecyclerViewBinderCore, 8 | ) : BaseRecyclerViewAdapter(core) 9 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/DialogFactory.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main; 2 | 3 | import android.app.Activity; 4 | import android.app.Dialog; 5 | import android.content.Context; 6 | import android.content.DialogInterface; 7 | import android.text.SpannableString; 8 | import android.text.method.LinkMovementMethod; 9 | import android.text.util.Linkify; 10 | import android.view.LayoutInflater; 11 | import android.view.View; 12 | import android.widget.TextView; 13 | 14 | import androidx.appcompat.app.AlertDialog; 15 | import uk.co.alt236.btlescan.R; 16 | 17 | /*package*/ final class DialogFactory { 18 | 19 | private DialogFactory() { 20 | // NOOP 21 | } 22 | 23 | public static Dialog createAboutDialog(final Context context) { 24 | final View view = LayoutInflater.from(context).inflate(R.layout.dialog_textview, null); 25 | final TextView textView = view.findViewById(R.id.text); 26 | 27 | final SpannableString text = new SpannableString(context.getString(R.string.about_dialog_text)); 28 | 29 | textView.setText(text); 30 | textView.setAutoLinkMask(Activity.RESULT_OK); 31 | textView.setMovementMethod(LinkMovementMethod.getInstance()); 32 | 33 | Linkify.addLinks(text, Linkify.ALL); 34 | 35 | final DialogInterface.OnClickListener listener = (dialog, id) -> { 36 | }; 37 | 38 | return new AlertDialog.Builder(context) 39 | .setTitle(R.string.menu_about) 40 | .setCancelable(false) 41 | .setPositiveButton(android.R.string.ok, listener) 42 | .setView(view) 43 | .create(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/RecyclerViewCoreFactory.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main; 2 | 3 | import android.content.Context; 4 | 5 | import uk.co.alt236.btlescan.R; 6 | import uk.co.alt236.btlescan.ui.common.Navigation; 7 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewBinderCore; 8 | import uk.co.alt236.btlescan.ui.main.recyclerview.binder.IBeaconBinder; 9 | import uk.co.alt236.btlescan.ui.main.recyclerview.binder.LeDeviceBinder; 10 | import uk.co.alt236.btlescan.ui.main.recyclerview.holder.IBeaconHolder; 11 | import uk.co.alt236.btlescan.ui.main.recyclerview.holder.LeDeviceHolder; 12 | 13 | /*protected*/ final class RecyclerViewCoreFactory { 14 | 15 | public static RecyclerViewBinderCore create(final Context context, final Navigation navigation) { 16 | final RecyclerViewBinderCore core = new RecyclerViewBinderCore(); 17 | 18 | core.add(new IBeaconBinder(context, navigation), IBeaconHolder.class, R.layout.list_item_device_ibeacon); 19 | core.add(new LeDeviceBinder(context, navigation), LeDeviceHolder.class, R.layout.list_item_device_le); 20 | 21 | return core; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/View.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main 2 | 3 | import android.app.Activity 4 | import android.view.View 5 | import android.widget.TextView 6 | import androidx.recyclerview.widget.LinearLayoutManager 7 | import androidx.recyclerview.widget.RecyclerView 8 | import uk.co.alt236.btlescan.R 9 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseRecyclerViewAdapter 10 | 11 | class View( 12 | activity: Activity, 13 | ) { 14 | private val resources = activity.resources 15 | private val mTvBluetoothLeStatus: TextView = activity.findViewById(R.id.tvBluetoothLe) 16 | private var mTvBluetoothStatus: TextView = activity.findViewById(R.id.tvBluetoothStatus) 17 | private var mTvItemCount: TextView = activity.findViewById(R.id.tvItemCount) 18 | private var mList: RecyclerView = activity.findViewById(android.R.id.list) 19 | private var mEmpty: View = activity.findViewById(android.R.id.empty) 20 | 21 | init { 22 | mList.layoutManager = LinearLayoutManager(activity) 23 | } 24 | 25 | fun setBluetoothEnabled(enabled: Boolean) { 26 | if (enabled) { 27 | mTvBluetoothStatus.setText(R.string.on) 28 | } else { 29 | mTvBluetoothStatus.setText(R.string.off) 30 | } 31 | } 32 | 33 | fun setBluetoothLeSupported(supported: Boolean) { 34 | if (supported) { 35 | mTvBluetoothLeStatus.setText(R.string.supported) 36 | } else { 37 | mTvBluetoothLeStatus.setText(R.string.not_supported) 38 | } 39 | } 40 | 41 | fun updateItemCount(count: Int) { 42 | val text = resources.getString(R.string.formatter_item_count, count.toString()) 43 | mTvItemCount.text = text 44 | } 45 | 46 | fun setListAdapter(adapter: BaseRecyclerViewAdapter) { 47 | mList.adapter = adapter 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/binder/CommonBinding.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.binder; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | 6 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice; 7 | import uk.co.alt236.btlescan.R; 8 | import uk.co.alt236.btlescan.ui.main.recyclerview.holder.CommonDeviceHolder; 9 | import uk.co.alt236.btlescan.util.Constants; 10 | 11 | /*package*/ class CommonBinding { 12 | 13 | @SuppressLint("MissingPermission") // We check before this is called 14 | public static void bind(final Context context, 15 | final CommonDeviceHolder holder, 16 | final BluetoothLeDevice device) { 17 | 18 | final String deviceName = device.getName(); 19 | final double rssi = device.getRssi(); 20 | 21 | if (deviceName != null && !deviceName.isEmpty()) { 22 | holder.getDeviceName().setText(deviceName); 23 | } else { 24 | holder.getDeviceName().setText(R.string.unknown_device); 25 | } 26 | 27 | final String rssiString = 28 | context.getString(R.string.formatter_db, String.valueOf(rssi)); 29 | final String runningAverageRssiString = 30 | context.getString(R.string.formatter_db, String.valueOf(device.getRunningAverageRssi())); 31 | 32 | holder.getDeviceLastUpdated().setText( 33 | android.text.format.DateFormat.format( 34 | Constants.TIME_FORMAT, new java.util.Date(device.getTimestamp()))); 35 | holder.getDeviceAddress().setText(device.getAddress()); 36 | holder.getDeviceRssi().setText(rssiString + " / " + runningAverageRssiString); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/binder/IBeaconBinder.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.binder; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.annotation.NonNull; 6 | import dev.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconDevice; 7 | import uk.co.alt236.btlescan.R; 8 | import uk.co.alt236.btlescan.ui.common.Navigation; 9 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder; 10 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder; 11 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem; 12 | import uk.co.alt236.btlescan.ui.main.recyclerview.holder.IBeaconHolder; 13 | import uk.co.alt236.btlescan.ui.main.recyclerview.model.IBeaconItem; 14 | import uk.co.alt236.btlescan.util.Constants; 15 | 16 | public class IBeaconBinder extends BaseViewBinder { 17 | 18 | private final Navigation navigation; 19 | 20 | public IBeaconBinder(Context context, Navigation navigation) { 21 | super(context); 22 | this.navigation = navigation; 23 | } 24 | 25 | @Override 26 | public void bind(@NonNull BaseViewHolder holder, @NonNull IBeaconItem item) { 27 | 28 | final IBeaconHolder actualHolder = (IBeaconHolder) holder; 29 | final IBeaconDevice device = item.getDevice(); 30 | 31 | final String accuracy = Constants.DOUBLE_TWO_DIGIT_ACCURACY.format(device.getAccuracy()); 32 | 33 | actualHolder.getIbeaconMajor().setText(String.valueOf(device.getMajor())); 34 | actualHolder.getIbeaconMinor().setText(String.valueOf(device.getMinor())); 35 | actualHolder.getIbeaconTxPower().setText(String.valueOf(device.getCalibratedTxPower())); 36 | actualHolder.getIbeaconUUID().setText(device.getUUID()); 37 | actualHolder.getIbeaconDistance().setText( 38 | getContext().getString(R.string.formatter_meters, accuracy)); 39 | actualHolder.getIbeaconDistanceDescriptor().setText(device.getDistanceDescriptor().toString()); 40 | 41 | CommonBinding.bind(getContext(), actualHolder, device); 42 | actualHolder.getView().setOnClickListener(view -> navigation.openDetailsActivity(device)); 43 | } 44 | 45 | @Override 46 | public boolean canBind(RecyclerViewItem item) { 47 | return item instanceof IBeaconItem; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/binder/LeDeviceBinder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.binder 2 | 3 | import android.content.Context 4 | import uk.co.alt236.btlescan.ui.common.Navigation 5 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 8 | import uk.co.alt236.btlescan.ui.main.recyclerview.holder.LeDeviceHolder 9 | import uk.co.alt236.btlescan.ui.main.recyclerview.model.LeDeviceItem 10 | 11 | class LeDeviceBinder( 12 | context: Context, 13 | private val navigation: Navigation, 14 | ) : BaseViewBinder(context) { 15 | override fun bind( 16 | holder: BaseViewHolder, 17 | item: LeDeviceItem, 18 | ) { 19 | val actualHolder = holder as LeDeviceHolder 20 | val device = item.device 21 | 22 | CommonBinding.bind(context, actualHolder, device) 23 | actualHolder.view.setOnClickListener { navigation.openDetailsActivity(device) } 24 | } 25 | 26 | override fun canBind(item: RecyclerViewItem): Boolean = item is LeDeviceItem 27 | } 28 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/holder/CommonDeviceHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.holder 2 | 3 | import android.widget.TextView 4 | 5 | interface CommonDeviceHolder { 6 | val deviceName: TextView 7 | val deviceAddress: TextView 8 | val deviceRssi: TextView 9 | val deviceLastUpdated: TextView 10 | } 11 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/holder/IBeaconHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.main.recyclerview.model.IBeaconItem 8 | 9 | class IBeaconHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView), 12 | CommonDeviceHolder { 13 | override val deviceName: TextView = itemView.findViewById(R.id.device_name) as TextView 14 | override val deviceAddress: TextView = itemView.findViewById(R.id.device_address) as TextView 15 | override val deviceRssi: TextView = itemView.findViewById(R.id.device_rssi) as TextView 16 | override val deviceLastUpdated: TextView = itemView.findViewById(R.id.device_last_update) as TextView 17 | 18 | val ibeaconUUID: TextView = itemView.findViewById(R.id.ibeacon_uuid) as TextView 19 | val ibeaconMajor: TextView = itemView.findViewById(R.id.ibeacon_major) as TextView 20 | val ibeaconMinor: TextView = itemView.findViewById(R.id.ibeacon_minor) as TextView 21 | val ibeaconTxPower: TextView = itemView.findViewById(R.id.ibeacon_tx_power) as TextView 22 | val ibeaconDistance: TextView = itemView.findViewById(R.id.ibeacon_distance) as TextView 23 | val ibeaconDistanceDescriptor: TextView = itemView.findViewById(R.id.ibeacon_distance_descriptor) as TextView 24 | } 25 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/holder/LeDeviceHolder.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.holder 2 | 3 | import android.view.View 4 | import android.widget.TextView 5 | import uk.co.alt236.btlescan.R 6 | import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder 7 | import uk.co.alt236.btlescan.ui.main.recyclerview.model.LeDeviceItem 8 | 9 | class LeDeviceHolder( 10 | itemView: View, 11 | ) : BaseViewHolder(itemView), 12 | CommonDeviceHolder { 13 | override val deviceName: TextView = itemView.findViewById(R.id.device_name) as TextView 14 | override val deviceAddress: TextView = itemView.findViewById(R.id.device_address) as TextView 15 | override val deviceRssi: TextView = itemView.findViewById(R.id.device_rssi) as TextView 16 | override val deviceLastUpdated: TextView = itemView.findViewById(R.id.device_last_update) as TextView 17 | } 18 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/model/IBeaconItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.model 2 | 3 | import dev.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconDevice 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 5 | 6 | data class IBeaconItem( 7 | val device: IBeaconDevice, 8 | ) : RecyclerViewItem 9 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/model/LeDeviceItem.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.recyclerview.model 2 | 3 | import dev.alt236.bluetoothlelib.device.BluetoothLeDevice 4 | import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem 5 | 6 | data class LeDeviceItem( 7 | val device: BluetoothLeDevice, 8 | ) : RecyclerViewItem 9 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/share/CsvWriterHelper.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.share; 2 | 3 | /*package*/ class CsvWriterHelper { 4 | private static final String QUOTE = "\""; 5 | 6 | public static String addStuff(final Integer text) { 7 | return QUOTE + text + QUOTE + ","; 8 | } 9 | 10 | public static String addStuff(final Long text) { 11 | return QUOTE + text + QUOTE + ","; 12 | } 13 | 14 | public static String addStuff(final boolean value) { 15 | return QUOTE + value + QUOTE + ","; 16 | } 17 | 18 | public static String addStuff(String text) { 19 | if (text == null) { 20 | text = ""; 21 | } 22 | text = text.replace(QUOTE, "'"); 23 | 24 | return QUOTE + text.trim() + QUOTE + ","; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/share/Sharer.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.ui.main.share; 2 | 3 | import android.app.Activity; 4 | import android.net.Uri; 5 | import android.widget.Toast; 6 | 7 | import java.util.Locale; 8 | 9 | import uk.co.alt236.btlescan.R; 10 | import uk.co.alt236.btlescan.containers.BluetoothLeDeviceStore; 11 | import uk.co.alt236.btlescan.ui.common.Navigation; 12 | import uk.co.alt236.btlescan.util.TimeFormatter; 13 | 14 | public class Sharer { 15 | private static final String CSV_FILENAME_PREFIX = "bluetooth_le_%d"; 16 | private static final String CSV_FILENAME_SUFFIX = ".csv"; 17 | 18 | private final CsvFileWriter csvFileWriter = new CsvFileWriter(); 19 | 20 | public void shareDataAsEmail(final Activity activity, 21 | final BluetoothLeDeviceStore store) { 22 | 23 | final long timeInMillis = System.currentTimeMillis(); 24 | final String message = activity.getString(R.string.exporter_email_device_list_body); 25 | final String[] to = new String[0]; 26 | final String subject = activity.getString( 27 | R.string.exporter_email_device_list_subject, 28 | TimeFormatter.getIsoDateTime(timeInMillis)); 29 | 30 | final String filename = String.format(Locale.US, CSV_FILENAME_PREFIX, timeInMillis) + CSV_FILENAME_SUFFIX; 31 | final Uri uri = csvFileWriter.writeCsvFile(activity, filename, store.getDeviceList()); 32 | 33 | if (uri == null) { 34 | Toast.makeText(activity, R.string.error_failed_to_create_csv_to_share, Toast.LENGTH_SHORT).show(); 35 | } else { 36 | new Navigation(activity) 37 | .shareFileViaEmail(uri, to, subject, message); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/util/BluetoothAdapterWrapper.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.util 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.Activity 5 | import android.bluetooth.BluetoothAdapter 6 | import android.bluetooth.BluetoothManager 7 | import android.content.Context 8 | import android.content.Intent 9 | import android.content.pm.PackageManager 10 | 11 | class BluetoothAdapterWrapper( 12 | private val context: Context, 13 | ) { 14 | var bluetoothAdapter: BluetoothAdapter? = null 15 | 16 | init { 17 | val btManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager? 18 | checkNotNull(btManager) { "No bluetooth manager adapter present!" } 19 | bluetoothAdapter = btManager.adapter 20 | } 21 | 22 | @SuppressLint("MissingPermission") // We check before this is called 23 | fun askUserToEnableBluetoothIfNeeded(activity: Activity) { 24 | if (isBluetoothLeSupported && !isBluetoothOn) { 25 | val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) 26 | activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT) 27 | } 28 | } 29 | 30 | val isBluetoothLeSupported: Boolean 31 | get() = context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) 32 | 33 | val isBluetoothOn: Boolean 34 | get() = bluetoothAdapter?.isEnabled ?: false 35 | 36 | companion object { 37 | const val REQUEST_ENABLE_BT = 2001 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/util/BluetoothLeScanner.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.util 2 | 3 | import android.annotation.SuppressLint 4 | import android.bluetooth.BluetoothAdapter 5 | import android.bluetooth.le.ScanCallback 6 | import android.bluetooth.le.ScanFilter 7 | import android.bluetooth.le.ScanSettings 8 | import android.os.Handler 9 | import android.util.Log 10 | 11 | @Suppress("MemberVisibilityCanBePrivate") 12 | class BluetoothLeScanner( 13 | private val bluetoothAdapterWrapper: BluetoothAdapterWrapper, 14 | private val leScanCallback: ScanCallback, 15 | ) { 16 | private val mHandler: Handler = Handler() 17 | 18 | var isScanning = false 19 | private set 20 | 21 | fun startScan() { 22 | scanLeDevice(duration = -1) 23 | } 24 | 25 | fun scanLeDevice(duration: Int) { 26 | bluetoothAdapterWrapper.bluetoothAdapter?.let { startScan(it, duration) } 27 | } 28 | 29 | fun stopScan(reason: String = "[not given]") { 30 | bluetoothAdapterWrapper.bluetoothAdapter?.let { stopScan(it, reason) } 31 | } 32 | 33 | @SuppressLint("MissingPermission") // We check before this is called 34 | private fun startScan(adapter: BluetoothAdapter, duration: Int) { 35 | if (isScanning) { 36 | return 37 | } 38 | 39 | // Stops scanning after a pre-defined scan period. 40 | if (duration > 0) { 41 | mHandler.postDelayed({ 42 | stopScan("timeout") 43 | }, duration.toLong()) 44 | } 45 | 46 | Log.d(TAG, "~ Starting Scan (duration: $duration)") 47 | isScanning = true 48 | val filters = 49 | ArrayList().apply { 50 | this.add(ScanFilter.Builder().build()) 51 | } 52 | val settings = 53 | ScanSettings 54 | .Builder() 55 | .setScanMode( 56 | ScanSettings.SCAN_MODE_LOW_LATENCY, 57 | ).build() 58 | 59 | adapter.bluetoothLeScanner.startScan(filters, settings, leScanCallback) 60 | } 61 | 62 | @SuppressLint("MissingPermission") // We check before this is called 63 | private fun stopScan(adapter: BluetoothAdapter, reason: String) { 64 | Log.d(TAG, "~ Stopping Scan - reason: '$reason'") 65 | isScanning = false 66 | adapter.bluetoothLeScanner?.stopScan(leScanCallback) 67 | } 68 | 69 | private companion object { 70 | val TAG: String = BluetoothLeScanner::class.java.simpleName 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/util/Constants.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.util; 2 | 3 | import java.text.DecimalFormat; 4 | 5 | public class Constants { 6 | public static final DecimalFormat DOUBLE_TWO_DIGIT_ACCURACY = new DecimalFormat("#.##"); 7 | public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; 8 | } 9 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/util/TimeFormatter.java: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.util; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.Locale; 6 | 7 | public class TimeFormatter { 8 | private final static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz"; 9 | private final static SimpleDateFormat ISO_FORMATTER = new UtcDateFormatter(ISO_FORMAT, Locale.US); 10 | 11 | public static String getIsoDateTime(final Date date) { 12 | return ISO_FORMATTER.format(date); 13 | } 14 | 15 | public static String getIsoDateTime(final long millis) { 16 | return getIsoDateTime(new Date(millis)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /sample_app/src/main/java/uk/co/alt236/btlescan/util/UtcDateFormatter.kt: -------------------------------------------------------------------------------- 1 | package uk.co.alt236.btlescan.util 2 | 3 | import android.annotation.SuppressLint 4 | import java.text.DateFormatSymbols 5 | import java.text.SimpleDateFormat 6 | import java.util.Locale 7 | import java.util.TimeZone 8 | 9 | @Suppress("unused") 10 | class UtcDateFormatter : SimpleDateFormat { 11 | @SuppressLint("SimpleDateFormat") 12 | constructor(template: String) : super(template) { 13 | super.setTimeZone(TIME_ZONE_UTC) 14 | } 15 | 16 | @SuppressLint("SimpleDateFormat") 17 | constructor(template: String, symbols: DateFormatSymbols) : super(template, symbols) { 18 | super.setTimeZone(TIME_ZONE_UTC) 19 | } 20 | 21 | constructor(template: String, locale: Locale) : super(template, locale) { 22 | super.setTimeZone(TIME_ZONE_UTC) 23 | } 24 | 25 | /* 26 | * This function will throw an UnsupportedOperationException. 27 | * You are not be able to change the TimeZone of this object 28 | * 29 | * (non-Javadoc) 30 | * @see java.text.DateFormat#setTimeZone(java.util.TimeZone) 31 | */ 32 | override fun setTimeZone(timezone: TimeZone): Unit = 33 | throw UnsupportedOperationException("This SimpleDateFormat can only be in $TIME_ZONE_STRING") 34 | 35 | private companion object { 36 | private const val serialVersionUID = 1L 37 | private const val TIME_ZONE_STRING = "UTC" 38 | private val TIME_ZONE_UTC = TimeZone.getTimeZone(TIME_ZONE_STRING) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-hdpi/ic_action_share.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-hdpi/ic_action_share.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-hdpi/ic_bluetooth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-hdpi/ic_bluetooth.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-mdpi/ic_action_share.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-mdpi/ic_action_share.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-mdpi/ic_bluetooth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-mdpi/ic_bluetooth.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xhdpi/ic_action_share.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xhdpi/ic_action_share.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xhdpi/ic_bluetooth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xhdpi/ic_bluetooth.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xhdpi/ic_bluetooth_on.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xhdpi/ic_bluetooth_on.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xhdpi/ic_device_ibeacon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xhdpi/ic_device_ibeacon.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xxhdpi/ic_action_share.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xxhdpi/ic_action_share.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xxhdpi/ic_bluetooth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xxhdpi/ic_bluetooth.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xxxhdpi/ic_action_share.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xxxhdpi/ic_action_share.png -------------------------------------------------------------------------------- /sample_app/src/main/res/drawable-xxxhdpi/ic_bluetooth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/drawable-xxxhdpi/ic_bluetooth.png -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/actionbar_progress_indeterminate.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 10 | 11 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/activity_details.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 14 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/activity_gatt_services.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 25 | 26 | 33 | 34 | 39 | 40 | 43 | 44 | 49 | 50 | 53 | 54 | 55 | 61 | 62 | 69 | 70 | 75 | 76 | 79 | 80 | 85 | 86 | 89 | 90 | 95 | 96 | 99 | 100 | 105 | 106 | 109 | 110 | 115 | 116 | 119 | 120 | 121 | 127 | 128 | 134 | 135 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 18 | 19 | 26 | 27 | 37 | 38 | 47 | 48 | 58 | 59 | 60 | 65 | 66 | 70 | 71 | 77 | 78 | 83 | 84 | 89 | 90 | 91 | 98 | 99 | 103 | 104 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/dialog_textview.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_device_le.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_view_adrecord.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 | 21 | 22 | 27 | 28 | 31 | 32 | 37 | 38 | 41 | 42 | 47 | 48 | 51 | 52 | 57 | 58 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_view_device_info.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 14 | 15 | 20 | 21 | 24 | 25 | 30 | 31 | 34 | 35 | 40 | 41 | 44 | 45 | 50 | 51 | 54 | 55 | 60 | 61 | 64 | 65 | 70 | 71 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_view_header.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_view_ibeacon_details.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 14 | 15 | 20 | 21 | 24 | 25 | 30 | 31 | 34 | 35 | 40 | 41 | 44 | 45 | 50 | 51 | 54 | 55 | 60 | 61 | 64 | 65 | 70 | 71 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_view_rssi_info.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 14 | 15 | 20 | 21 | 24 | 25 | 30 | 31 | 34 | 35 | 40 | 41 | 44 | 45 | 50 | 51 | 54 | 55 | 60 | 61 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/list_item_view_textview.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /sample_app/src/main/res/layout/viewpart_list_item_device_common.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 13 | 14 | 18 | 19 | 26 | 27 | 33 | 34 | 41 | 42 | 48 | 49 | 56 | 57 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /sample_app/src/main/res/menu/details.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 |

19 | 20 | 21 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /sample_app/src/main/res/menu/gatt_services.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 26 | 32 | 37 | 42 | 43 | -------------------------------------------------------------------------------- /sample_app/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 26 | 27 | 32 | 37 | 43 | 48 | 49 | -------------------------------------------------------------------------------- /sample_app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample_app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample_app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample_app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample_app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alt236/Bluetooth-LE-Library---Android/d33bacd807b2f6be8df8e052942fa82c51aaeb31/sample_app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample_app/src/main/res/values-sw600dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /sample_app/src/main/res/values-sw720dp-land/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 128dp 8 | 9 | 10 | -------------------------------------------------------------------------------- /sample_app/src/main/res/values-v21/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 15 | -------------------------------------------------------------------------------- /sample_app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | #0082FC 3 | #66e0e0e0 4 | 5 | @color/bluetooth_blue 6 | #0069E3 7 | #F06292 8 | 9 | @color/colorAccent 10 | 11 | -------------------------------------------------------------------------------- /sample_app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16dp 5 | 16dp 6 | 7 | 8dp 8 | 9 | -------------------------------------------------------------------------------- /sample_app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Settings 5 | Connected 6 | Disconnected 7 | Connecting 8 | Invalid Device Data! 9 | No data 10 | Not supported 11 | Off 12 | On 13 | Supported 14 | unknown 15 | Unknown characteristic 16 | Unknown device 17 | Unknown service 18 | No known services 19 | 20 | 21 | %sm 22 | %sdb 23 | Items: %s 24 | \'%s\' 25 | 26 | 27 | About 28 | Connect 29 | Disconnect 30 | Scan 31 | Stop 32 | Share 33 | 34 | 35 | Bluetooth LE Scan Results (%s) 36 | Bluetooth LE Device GATT Results (%s, %s) 37 | Please find attached the scan results. 38 | Please select your email client: 39 | 40 | 41 | This is a sample application using the Bluetooth LE Library.\n\nGithub: https://github.com/alt236/Bluetooth-LE-Library---Android\n\nCopyright: Alexandros Schillings 42 | Device Info 43 | iBeacon Data 44 | Raw Ad Records 45 | RSSI Info 46 | Scan Record 47 | Advertisement: 48 | Length: 49 | As Array: 50 | As UTF-8: 51 | As Chars: 52 | Bluetooth LE: 53 | Bluetooth: 54 | Bonding State: 55 | Company ID: 56 | Data: 57 | Desc: 58 | Device address: 59 | Device Class: 60 | Major Class: 61 | Services: 62 | Device Name: 63 | Distance: 64 | First RSSI: 65 | First Timestamp: 66 | Last RSSI: 67 | Last Timestamp: 68 | MAC: 69 | Major: 70 | Minor: 71 | RSSI: 72 | Running Average RSSI: 73 | State: 74 | TX Power: 75 | UUID: 76 | Updated: 77 | Descriptor: 78 | 79 | Failed to create CSV file to share! 80 | The ACCESS_COARSE_LOCATION permission is needed to receive bluetooth scan results 81 | The ACCESS_FINE_LOCATION permission is needed to receive bluetooth scan results 82 | The BLUETOOTH_SCAN permission is needed to receive bluetooth scan results 83 | In order to access information about nearby bluetooth devices, the following permissions are needed 84 | You need to allow necessary permissions in Settings manually 85 | -------------------------------------------------------------------------------- /sample_app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 11 | 22 | 23 | 26 | 27 |