├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.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-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── us
│ │ │ └── cpluspl
│ │ │ └── yonixw
│ │ │ └── readheartbatmiband2
│ │ │ ├── IOHelper.java
│ │ │ ├── Consts.java
│ │ │ ├── HearBeatVoice.java
│ │ │ ├── SoundHelper.java
│ │ │ ├── MainActivity.java
│ │ │ └── BLEMiBand2Helper.java
│ ├── test
│ │ └── java
│ │ │ └── us
│ │ │ └── cpluspl
│ │ │ └── yonixw
│ │ │ └── readheartbatmiband2
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── us
│ │ └── cpluspl
│ │ └── yonixw
│ │ └── readheartbatmiband2
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── yoni-voice
├── h1.wav
├── h2.wav
├── o1.wav
├── o2.wav
├── o3.wav
├── o4.wav
├── o5.wav
├── o6.wav
├── o7.wav
├── o8.wav
├── o9.wav
├── t1.wav
├── t2.wav
├── t3.wav
├── t4.wav
├── t5.wav
├── t6.wav
├── t7.wav
├── t8.wav
├── t9.wav
├── ve.wav
├── empty.wav
├── esre.wav
├── intro.wav
├── units.wav
└── invalid.wav
├── .gitignore
├── README.md
├── gradle.properties
├── LICENSE
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/yoni-voice/h1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/h1.wav
--------------------------------------------------------------------------------
/yoni-voice/h2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/h2.wav
--------------------------------------------------------------------------------
/yoni-voice/o1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o1.wav
--------------------------------------------------------------------------------
/yoni-voice/o2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o2.wav
--------------------------------------------------------------------------------
/yoni-voice/o3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o3.wav
--------------------------------------------------------------------------------
/yoni-voice/o4.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o4.wav
--------------------------------------------------------------------------------
/yoni-voice/o5.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o5.wav
--------------------------------------------------------------------------------
/yoni-voice/o6.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o6.wav
--------------------------------------------------------------------------------
/yoni-voice/o7.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o7.wav
--------------------------------------------------------------------------------
/yoni-voice/o8.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o8.wav
--------------------------------------------------------------------------------
/yoni-voice/o9.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/o9.wav
--------------------------------------------------------------------------------
/yoni-voice/t1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t1.wav
--------------------------------------------------------------------------------
/yoni-voice/t2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t2.wav
--------------------------------------------------------------------------------
/yoni-voice/t3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t3.wav
--------------------------------------------------------------------------------
/yoni-voice/t4.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t4.wav
--------------------------------------------------------------------------------
/yoni-voice/t5.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t5.wav
--------------------------------------------------------------------------------
/yoni-voice/t6.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t6.wav
--------------------------------------------------------------------------------
/yoni-voice/t7.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t7.wav
--------------------------------------------------------------------------------
/yoni-voice/t8.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t8.wav
--------------------------------------------------------------------------------
/yoni-voice/t9.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/t9.wav
--------------------------------------------------------------------------------
/yoni-voice/ve.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/ve.wav
--------------------------------------------------------------------------------
/yoni-voice/empty.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/empty.wav
--------------------------------------------------------------------------------
/yoni-voice/esre.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/esre.wav
--------------------------------------------------------------------------------
/yoni-voice/intro.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/intro.wav
--------------------------------------------------------------------------------
/yoni-voice/units.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/units.wav
--------------------------------------------------------------------------------
/yoni-voice/invalid.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/yoni-voice/invalid.wav
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ReadHeartBatMiBand2
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yonixw/mi-band-2/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .idea/
10 | gradle/
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # mi-band-2
2 | Target: Read heart beat from mi and button press detection
3 |
4 | Committing step by step! Use it to learn.
5 |
6 | # Mi-Band-UUID Backup:
7 | https://github.com/yonixw/mi-band-2/wiki/Mi-Band-UUID
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/us/cpluspl/yonixw/readheartbatmiband2/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/us/cpluspl/yonixw/readheartbatmiband2/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/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 C:\Users\YoniWas\AppData\Local\Android\Sdk/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 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.3"
6 |
7 | defaultConfig {
8 | applicationId "us.cpluspl.yonixw.readheartbatmiband2"
9 | minSdkVersion 19
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.3.0'
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Yehonatan Water Man
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/java/us/cpluspl/yonixw/readheartbatmiband2/IOHelper.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import android.content.Context;
4 | import android.os.Environment;
5 | import android.util.Log;
6 |
7 | import java.io.File;
8 |
9 | /**
10 | * Created by YoniWas on 05/02/2017.
11 | */
12 | public class IOHelper {
13 | /* Checks if external storage is available for read and write */
14 | public static boolean isExternalStorageWritable() {
15 | String state = Environment.getExternalStorageState();
16 | if (Environment.MEDIA_MOUNTED.equals(state)) {
17 | return true;
18 | }
19 | return false;
20 | }
21 |
22 | /* Checks if external storage is available to at least read */
23 | public static boolean isExternalStorageReadable() {
24 | String state = Environment.getExternalStorageState();
25 | if (Environment.MEDIA_MOUNTED.equals(state) ||
26 | Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
27 | return true;
28 | }
29 | return false;
30 | }
31 |
32 |
33 | public static File getStorageDir(Context context) {
34 | // Get the directory for the app's private directory (remove @ uninstall).
35 | File file = context.getExternalFilesDir(null);
36 | if (!file.exists() && !file.mkdirs()) {
37 | Log.e(MainActivity.LOG_TAG, "Directory not created " + file.getAbsolutePath());
38 | }
39 | return file;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
13 |
14 |
20 |
21 |
28 |
29 |
36 |
37 |
44 |
45 |
54 |
55 |
--------------------------------------------------------------------------------
/app/src/main/java/us/cpluspl/yonixw/readheartbatmiband2/Consts.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import java.util.UUID;
4 |
5 | /**
6 | * Created by YoniWas on 22/02/2017.
7 | */
8 | public class Consts {
9 |
10 | //this is common for all BTLE devices. see http://stackoverflow.com/questions/18699251/finding-out-android-bluetooth-le-gatt-profiles
11 | public static final String BASE_UUID = "0000%s-0000-1000-8000-00805f9b34fb";
12 |
13 | public static final UUID UUID_SERVICE_GENERIC = UUID.fromString(String.format(BASE_UUID, "1800"));
14 | public static final UUID UUID_SERVICE_MIBAND_SERVICE = UUID.fromString(String.format(BASE_UUID, "FEE0"));
15 | public static final UUID UUID_SERVICE_MIBAND2_SERVICE = UUID.fromString(String.format(BASE_UUID, "FEE1"));
16 | public static final UUID UUID_SERVICE_HEARTBEAT = UUID.fromString(String.format(BASE_UUID, "180D"));
17 |
18 | // General service
19 | public static final UUID UUID_CHARACTERISTIC_DEVICE_NAME = UUID.fromString(String.format(BASE_UUID, "2A00"));
20 |
21 | // Miband service 1
22 | public static final UUID UUID_BUTTON_TOUCH = UUID.fromString("00000010-0000-3512-2118-0009af100700");
23 |
24 | //Heart beat service
25 | public static final UUID UUID_START_HEARTRATE_CONTROL_POINT = UUID.fromString("00002a39-0000-1000-8000-00805f9b34fb");
26 | public static final UUID UUID_NOTIFICATION_HEARTRATE = UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb");
27 | public static final byte[] BYTE_LAST_HEART_RATE_SCAN = {21, 1, 1};
28 | public static final byte[] BYTE_NEW_HEART_RATE_SCAN = {21, 2, 1};
29 | public static final UUID UUID_DESCRIPTOR_UPDATE_NOTIFICATION = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
30 |
31 | final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
32 | public static String bytesToHex(byte[] bytes) {
33 | //http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
34 | char[] hexChars = new char[bytes.length * 2];
35 | for ( int j = 0; j < bytes.length; j++ ) {
36 | int v = bytes[j] & 0xFF;
37 | hexChars[j * 2] = hexArray[v >>> 4];
38 | hexChars[j * 2 + 1] = hexArray[v & 0x0F];
39 | }
40 | return new String(hexChars);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/src/main/java/us/cpluspl/yonixw/readheartbatmiband2/HearBeatVoice.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | /**
4 | * Created by YoniWas on 03/03/2017.
5 | */
6 | public class HearBeatVoice {
7 | static String cantRead = "invalid";
8 | static String andWord = "ve";
9 | static String nullSound = "empty";
10 | static String tensPostfix = "esre";
11 |
12 | static String intro = "intro"; // My hear beat is:
13 | static String units = "units"; // beat per minute.
14 |
15 | // ones - "o1" to "o9"
16 | // tens - "t1" to "t9"
17 | // hundreds - "h1" to "h9" // (but hear beat is never more than 200 ...)
18 |
19 | static String str(Integer i) {
20 | return Integer.toString(i);
21 | }
22 |
23 | // For numbers < 100
24 | static void addLessThan100(SoundHelper sh, int Hearbeat) {
25 | int t = (Hearbeat % 100)/10; // Tens
26 | int o = Hearbeat % 10; // Ones
27 |
28 | if (t == 0 && o ==0) {
29 | sh.addWAVSound(nullSound);
30 | }
31 | else if (o == 0) {
32 | // only tens:
33 | sh.addWAVSound("t" + str(t));
34 | }
35 | // From now on we assume ther are ones.
36 | else if (Hearbeat >= 20 ) {
37 | sh.addWAVSound("t" + str(t)); // shloshim
38 |
39 | sh.addWAVSound(andWord); // ve
40 | sh.addWAVSound("o" + str(o)); // Hamesh
41 |
42 | }
43 | else if (Hearbeat > 10 ) {
44 | sh.addWAVSound("o" + str(o));
45 | sh.addWAVSound(tensPostfix);
46 | }
47 | else { // Only ones... (t == 0)
48 | sh.addWAVSound("o" + str(o));
49 | }
50 | }
51 |
52 | public static void readHeartbeat(SoundHelper sh, int Hearbeat) {
53 | int h = Hearbeat/100; // Hundreds
54 | int h11 = (Hearbeat % 100) ; // Number without hundreds
55 |
56 | if (Hearbeat < 0 ) return;
57 |
58 |
59 |
60 |
61 | if (Hearbeat == 0 ) {
62 | sh.addWAVSound(cantRead); // Mi band couldnt read heartbeat.
63 | }
64 | else {
65 | sh.addWAVSound(intro);
66 |
67 | if (h > 0 && h11 >= 20 ) {
68 | sh.addWAVSound("h" + str(h)); // Mea
69 | }
70 | else if (h > 0 && h11 < 20) {
71 | sh.addWAVSound("h" + str(h)); // Mea
72 | sh.addWAVSound(andWord); // ve
73 | }
74 | // Else less than 100.
75 |
76 | addLessThan100(sh,Hearbeat);
77 |
78 | sh.addWAVSound(units);
79 | }
80 |
81 |
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/us/cpluspl/yonixw/readheartbatmiband2/SoundHelper.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import android.content.Context;
4 | import android.media.MediaPlayer;
5 | import android.net.Uri;
6 | import android.util.Log;
7 | import android.widget.Toast;
8 |
9 | import java.io.File;
10 | import java.net.URI;
11 | import java.util.ArrayList;
12 |
13 | /**
14 | * Created by YoniWas on 05/02/2017.
15 | */
16 | public class SoundHelper {
17 |
18 | Context myContext;
19 | ArrayList loadedSounds = new ArrayList() ;
20 |
21 | public SoundHelper(Context context) {
22 | myContext =context;
23 | }
24 |
25 | private MediaPlayer getMediaPlayer( String localFileName) {
26 | Uri filePath = Uri.fromFile(new File (IOHelper.getStorageDir(myContext), localFileName));
27 | MediaPlayer mp = MediaPlayer.create(
28 | myContext,
29 | filePath
30 | );
31 | if (mp == null) {
32 | String logMessage = "Can't load file '" + localFileName
33 | + "'\nIn place: '" + filePath.toString() + "';";
34 | Log.d(MainActivity.LOG_TAG, logMessage);
35 | Toast.makeText(myContext, "Cant load file:" + localFileName, Toast.LENGTH_LONG).show();
36 | }
37 |
38 | return mp;
39 | }
40 |
41 | private void addSound(String shortName) {
42 | // To see the voices added by our helpers.
43 | Log.d(MainActivity.LOG_TAG, "Added voice: " + shortName);
44 |
45 | loadedSounds.add(getMediaPlayer(shortName));
46 | }
47 |
48 | /**
49 | * Add sound to the media player. the file must have wav extention even if the format is mp3
50 | * @param shortName the name of the file (ex. /../../music.wav => music)
51 | */
52 | public void addWAVSound(String shortName) {
53 | addSound(shortName + ".wav");
54 | }
55 |
56 | public void releaseAllSounds() {
57 | for (MediaPlayer m : loadedSounds) {
58 | m.release();
59 | }
60 | loadedSounds.clear();
61 | }
62 |
63 | public void playAllAsync() {
64 | Thread r = new Thread() {
65 |
66 |
67 | @Override
68 | public void run() {
69 | int counter = 0;
70 | for (MediaPlayer m : loadedSounds) {
71 | Log.d(MainActivity.LOG_TAG, "Playing sound no. " + counter);
72 | m.start();
73 | while (m.isPlaying()) {
74 | try {
75 | Thread.sleep(100,0); // lower cpu if we wait and not just busy wait
76 | } catch (InterruptedException e) { e.printStackTrace();}
77 | }
78 |
79 | counter++;
80 | }
81 |
82 | raisePlayBackFinishEvent();
83 | }
84 | };
85 |
86 |
87 | r.start();
88 | }
89 |
90 | // Event when all activites done.
91 | public interface PlaybackFinishListener {
92 | public void onPlaybackFinish() ;
93 | }
94 |
95 | private PlaybackFinishListener myPlaybackFinishListener = null;
96 | public void setPlaybackFinishListener(PlaybackFinishListener listener) {
97 | myPlaybackFinishListener = listener;
98 | }
99 |
100 | private void raisePlayBackFinishEvent() {
101 | Log.d(MainActivity.LOG_TAG, "Playback Finished!");
102 | if(myPlaybackFinishListener !=null) {
103 | myPlaybackFinishListener.onPlaybackFinish();
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/us/cpluspl/yonixw/readheartbatmiband2/MainActivity.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import android.bluetooth.BluetoothGatt;
4 | import android.bluetooth.BluetoothGattCharacteristic;
5 | import android.media.AudioManager;
6 | import android.os.Handler;
7 | import android.os.Looper;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.os.Bundle;
10 | import android.util.Log;
11 | import android.view.View;
12 |
13 | import android.bluetooth.BluetoothAdapter;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import java.util.Calendar;
18 | import java.util.Date;
19 | import java.util.UUID;
20 |
21 | public class MainActivity extends AppCompatActivity implements BLEMiBand2Helper.BLEAction {
22 | public static final String LOG_TAG = "Yoni";
23 |
24 | Handler handler = new Handler(Looper.getMainLooper());
25 | BLEMiBand2Helper helper = null;
26 |
27 | TextView txtPath;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_main);
33 |
34 | helper = new BLEMiBand2Helper(MainActivity.this, handler);
35 | helper.addListener(this);
36 |
37 | initSoundHelper();
38 |
39 | // Get save path:
40 | txtPath = (TextView) findViewById(R.id.txtPath);
41 | txtPath.setText( getApplicationContext().getExternalFilesDir(null).getAbsolutePath());
42 |
43 | // Setup Bluetooth:
44 | helper.findBluetoothDevice(myBluetoothAdapter, "MI");
45 | helper.ConnectToGatt();
46 |
47 | try {
48 | Thread.sleep(3000);
49 | } catch (InterruptedException e) {
50 | e.printStackTrace();
51 | }
52 | getTouchNotifications();
53 | setupHeartBeat();
54 | }
55 |
56 |
57 | @Override
58 | protected void onDestroy() {
59 | if (helper != null)
60 | helper.DisconnectGatt();
61 | super.onDestroy();
62 | }
63 |
64 | // Like network card, connect to all devices in Bluetooth (like PC in Netowrk)
65 | final BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
66 |
67 | public void btnRun(View view) {
68 | helper.findBluetoothDevice(myBluetoothAdapter, "MI");
69 | helper.ConnectToGatt();
70 | }
71 |
72 |
73 | public void setupHeartBeat() {
74 | /*
75 | Steps to read heartbeat:
76 | - Register Notification (like in touch press)
77 | - Extra step with description
78 | - Write predefined bytes to control_point to trigger measurement
79 | - Listener will get result
80 | */
81 |
82 | if (helper != null)
83 | helper.getNotificationsWithDescriptor(
84 | Consts.UUID_SERVICE_HEARTBEAT,
85 | Consts.UUID_NOTIFICATION_HEARTRATE,
86 | Consts.UUID_DESCRIPTOR_UPDATE_NOTIFICATION
87 | );
88 |
89 | // Need to wait before first trigger, maybe something about the descriptor....
90 | /*
91 | Toast.makeText(MainActivity.this, "Wait for heartbeat setup...", Toast.LENGTH_LONG).show();
92 | try {
93 | Thread.sleep(5000,0);
94 | } catch (InterruptedException e) {
95 | e.printStackTrace();
96 | }
97 | */
98 | }
99 |
100 | public void getNewHeartBeat() {
101 | if (helper == null || !helper.isConnected()) {
102 | Toast.makeText(MainActivity.this, "Please setup first!", Toast.LENGTH_SHORT).show();
103 | return;
104 | }
105 |
106 | helper.writeData(
107 | Consts.UUID_SERVICE_HEARTBEAT,
108 | Consts.UUID_START_HEARTRATE_CONTROL_POINT,
109 | Consts.BYTE_NEW_HEART_RATE_SCAN
110 | );
111 | }
112 |
113 | public void getTouchNotifications() {
114 | helper.getNotifications(
115 | Consts.UUID_SERVICE_MIBAND_SERVICE,
116 | Consts.UUID_BUTTON_TOUCH);
117 | }
118 |
119 | public void btnTest(View view) throws InterruptedException {
120 | getTouchNotifications();
121 | }
122 |
123 | public void btnSetuphearRate(View view) throws InterruptedException {
124 | setupHeartBeat();
125 | }
126 |
127 | public void btnTestHeartRate(View view) throws InterruptedException {
128 | getNewHeartBeat();
129 | }
130 |
131 | /* =========== EVENTS (background thread) =============== */
132 |
133 | @Override
134 | public void onDisconnect() {
135 |
136 | }
137 |
138 | @Override
139 | public void onConnect() {
140 |
141 | }
142 |
143 | @Override
144 | public void onRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
145 |
146 | }
147 |
148 | @Override
149 | public void onWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
150 |
151 | }
152 |
153 | @Override
154 | public void onNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
155 | UUID alertUUID = characteristic.getUuid();
156 | if (alertUUID.equals(Consts.UUID_NOTIFICATION_HEARTRATE)) {
157 | final byte hearbeat =
158 | characteristic.getValue()[1];
159 |
160 | handler.post(new Runnable() {
161 |
162 | @Override
163 | public void run() {
164 | Toast.makeText(MainActivity.this,
165 | "Heartbeat: " + Byte.toString(hearbeat)
166 | , Toast.LENGTH_SHORT).show();
167 |
168 | // Set max volume and read heart beat.
169 | setMaxVolume();
170 | HearBeatVoice.readHeartbeat(mySounds, hearbeat);
171 | mySounds.playAllAsync();
172 | }
173 | });
174 | }
175 | else if (alertUUID.equals(Consts.UUID_BUTTON_TOUCH)) {
176 | handler.post(new Runnable() {
177 |
178 | @Override
179 | public void run() {
180 | getNewHeartBeat();
181 | Toast.makeText(MainActivity.this,
182 | "Button Press! "
183 | , Toast.LENGTH_SHORT).show();
184 | }
185 | });
186 | }
187 | }
188 |
189 |
190 |
191 | /* =========== Sounds =============== */
192 |
193 | int currentVolume = 0;
194 | AudioManager audiManager;
195 |
196 | public void setMaxVolume() {
197 | currentVolume = audiManager.getStreamVolume(audiManager.STREAM_MUSIC);
198 | int amStreamMusicMaxVol =
199 | (int) (audiManager.getStreamMaxVolume(audiManager.STREAM_MUSIC) * 0.60f);
200 |
201 | audiManager.setStreamVolume(audiManager.STREAM_MUSIC, amStreamMusicMaxVol, 0);
202 | }
203 |
204 | public void resumeVolume() {
205 | audiManager.setStreamVolume(audiManager.STREAM_MUSIC, currentVolume, 0);
206 | }
207 |
208 | SoundHelper mySounds;
209 | private void initSoundHelper() {
210 | audiManager = (AudioManager)getSystemService(getApplicationContext().AUDIO_SERVICE);
211 | mySounds = new SoundHelper(getApplicationContext());
212 |
213 | mySounds.setPlaybackFinishListener(new SoundHelper.PlaybackFinishListener() {
214 | @Override
215 | public void onPlaybackFinish() {
216 | Log.d(LOG_TAG,"Got SoundHelper finish event!");
217 | mySounds.releaseAllSounds();
218 | resumeVolume();
219 | }
220 | });
221 | }
222 | }
223 |
224 | /*
225 | Credit and thanks:
226 |
227 | https://github.com/lwis/miband-notifier/
228 | http://allmydroids.blogspot.co.il/2014/12/xiaomi-mi-band-ble-protocol-reverse.html
229 | https://github.com/Freeyourgadget/Gadgetbridge
230 | http://stackoverflow.com/questions/20043388/working-with-ble-android-4-3-how-to-write-characteristics
231 |
232 | // Available services\Characteristics:
233 | http://jellygom.com/2016/09/30/Mi-Band-UUID.html
234 | https://github.com/Freeyourgadget/Gadgetbridge/blob/master/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/devices/miband/MiBand2Service.java
235 | https://devzone.nordicsemi.com/question/310/notificationindication-difference/
236 |
237 | // Heartbeat info
238 | http://stackoverflow.com/questions/36311874/heart-rate-measuring-using-xiaomi-miband-and-ble
239 | https://github.com/AlexanderHryk/MiFood/
240 | again: http://stackoverflow.com/questions/20043388/working-with-ble-android-4-3-how-to-write-characteristics
241 | https://github.com/dkhmelenko/miband-android/blob/master/miband-sdk/src/main/java/com/khmelenko/lab/miband/model/Protocol.java
242 |
243 | http://stackoverflow.com/questions/7378936/how-to-show-toast-message-from-background-thread
244 | http://stackoverflow.com/questions/6270132/create-a-custom-event-in-java
245 |
246 | http://stackoverflow.com/questions/6537023/how-can-i-perform-arithmetic-operation-with-dates-in-java
247 | */
248 |
--------------------------------------------------------------------------------
/app/src/main/java/us/cpluspl/yonixw/readheartbatmiband2/BLEMiBand2Helper.java:
--------------------------------------------------------------------------------
1 | package us.cpluspl.yonixw.readheartbatmiband2;
2 |
3 | import android.bluetooth.BluetoothAdapter;
4 | import android.bluetooth.BluetoothDevice;
5 | import android.bluetooth.BluetoothGatt;
6 | import android.bluetooth.BluetoothGattCallback;
7 | import android.bluetooth.BluetoothGattCharacteristic;
8 | import android.bluetooth.BluetoothGattDescriptor;
9 | import android.bluetooth.BluetoothGattService;
10 | import android.bluetooth.BluetoothProfile;
11 | import android.content.Context;
12 | import android.os.Looper;
13 | import android.util.Log;
14 | import android.widget.Toast;
15 |
16 | import java.util.ArrayList;
17 | import java.util.Arrays;
18 | import java.util.UUID;
19 | import java.util.logging.Handler;
20 |
21 | /**
22 | * Created by YoniWas on 27/02/2017.
23 | */
24 | public class BLEMiBand2Helper {
25 | public static final String TAG = "YONI-MI-2";
26 |
27 | private Context myContext = null;
28 | private android.os.Handler myHandler = null;
29 |
30 | private BluetoothDevice activeDevice = null; // The mi band
31 | private boolean isConnectedToGatt = false; // the gatt connection
32 | private BluetoothGatt myGatBand = null;
33 |
34 |
35 | private BLEMiBand2Helper() {}
36 |
37 | public BLEMiBand2Helper(Context context, android.os.Handler handler) {
38 | myContext = context;
39 | myHandler = handler;
40 | }
41 |
42 | public boolean isConnected() {
43 | return isConnectedToGatt;
44 | }
45 |
46 | /* ========= Handling Initializing ============== */
47 |
48 | void findBluetoothDevice(BluetoothAdapter myBluetoothAdapter,
49 | String filter) {
50 | Log.d(TAG, "(*) Initialising Bluetooth connection for device: " + filter);
51 |
52 | if(myBluetoothAdapter.isEnabled()) {
53 | for (BluetoothDevice pairedDevice : myBluetoothAdapter.getBondedDevices()) {
54 | if (pairedDevice.getName().contains(filter /*Like MI*/)) {
55 | Log.d(TAG, "\tDevice Name: " + pairedDevice.getName());
56 | Log.d(TAG, "\tDevice MAC: " + pairedDevice.getAddress());
57 |
58 | activeDevice = pairedDevice;
59 | break;
60 | }
61 | }
62 | }
63 |
64 | Log.d(TAG, "\tDidnt find any device!");
65 | }
66 |
67 | public void ConnectToGatt() {
68 | if (activeDevice != null) {
69 | // GATT is Just another specification:
70 | // https://www.bluetooth.com/specifications/gatt/services
71 | Log.d(TAG, "(*) Establishing connection to gatt");
72 | myGatBand = activeDevice.connectGatt(myContext, true ,myGattCallback );
73 | }
74 | else {
75 | Log.d(TAG, "(*) Cant Establish connection to gatt, device is null");
76 | }
77 | }
78 |
79 | public void DisconnectGatt() {
80 | if(myGatBand != null && isConnectedToGatt)
81 | {
82 | myHandler.post(new Runnable()
83 | {
84 | @Override public void run()
85 | {
86 | myGatBand.disconnect();
87 | myGatBand.close();
88 | myGatBand = null;
89 | isConnectedToGatt = false;
90 | }
91 | });
92 | }
93 | }
94 |
95 | private BluetoothGattCallback myGattCallback = new BluetoothGattCallback()
96 | {
97 | @Override
98 | public void onServicesDiscovered(BluetoothGatt gatt, int status)
99 | {
100 | if(status == BluetoothGatt.GATT_SUCCESS)
101 | {
102 |
103 | }
104 | Log.d(TAG, "Service discovered with status " + status);
105 | }
106 |
107 | @Override
108 | public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
109 | {
110 | switch(newState)
111 | {
112 | case BluetoothProfile.STATE_CONNECTED:
113 | Log.d(TAG, "Gatt state: connected");
114 | gatt.discoverServices();
115 | isConnectedToGatt = true;
116 | raiseonConnect();
117 | break;
118 | default:
119 | Log.d(TAG, "Gatt state: not connected");
120 | isConnectedToGatt = false;
121 | raiseonDisconnect();
122 | break;
123 | }
124 | }
125 |
126 | @Override
127 | public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
128 | {
129 | Log.d(TAG, "Write successful: " + Arrays.toString(characteristic.getValue()));
130 | raiseonWrite(gatt,characteristic,status);
131 | super.onCharacteristicWrite(gatt,characteristic,status);
132 | }
133 |
134 | @Override
135 | public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
136 | Log.d(TAG, "Read successful: " + Arrays.toString(characteristic.getValue()));
137 | raiseonRead(gatt,characteristic,status);
138 | super.onCharacteristicRead(gatt, characteristic, status);
139 | }
140 |
141 | @Override
142 | public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
143 | Log.d(TAG, " - Notifiaction UUID: " + characteristic.getUuid().toString());
144 | Log.d(TAG, " - Notifiaction value: " + Arrays.toString(characteristic.getValue()));
145 | raiseonNotification(gatt, characteristic);
146 | super.onCharacteristicChanged(gatt, characteristic);
147 | }
148 |
149 |
150 | };
151 |
152 | public interface BLEAction {
153 | void onDisconnect();
154 | void onConnect();
155 | void onRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status);
156 | void onWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status);
157 | void onNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic);
158 | }
159 |
160 | /* ========= Handling Events ============== */
161 |
162 | private ArrayList listeners = new ArrayList();
163 |
164 | public void addListener(BLEAction toAdd) {
165 | listeners.add(toAdd);
166 | }
167 |
168 | public void removeListener(BLEAction toDel) {
169 | listeners.remove(toDel);
170 | }
171 |
172 | public void raiseonNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
173 | // Notify everybody that may be interested.
174 | for (BLEAction listener : listeners)
175 | listener.onNotification( gatt,characteristic);
176 | }
177 |
178 | public void raiseonRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,int status) {
179 | // Notify everybody that may be interested.
180 | for (BLEAction listener : listeners)
181 | listener.onRead( gatt,characteristic,status);
182 | }
183 |
184 | public void raiseonWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,int status) {
185 | // Notify everybody that may be interested.
186 | for (BLEAction listener : listeners)
187 | listener.onWrite( gatt,characteristic,status);
188 | }
189 |
190 | public void raiseonDisconnect() {
191 | // Notify everybody that may be interested.
192 | for (BLEAction listener : listeners)
193 | listener.onDisconnect();
194 | }
195 |
196 | public void raiseonConnect() {
197 | // Notify everybody that may be interested.
198 | for (BLEAction listener : listeners)
199 | listener.onConnect();
200 | }
201 |
202 |
203 | /* ========= Handling Data ============== */
204 |
205 | public void readData(UUID service, UUID Characteristics) {
206 | if (!isConnectedToGatt || myGatBand == null) {
207 | Log.d(TAG, "Cant read from BLE, not initialized.");
208 | return;
209 | }
210 |
211 | Log.d(TAG, "* Getting gatt service, UUID:" + service.toString());
212 | BluetoothGattService myGatService =
213 | myGatBand.getService(service /*Consts.UUID_SERVICE_GENERIC*/);
214 | if (myGatService != null) {
215 | Log.d(TAG, "* Getting gatt Characteristic. UUID: " + Characteristics.toString());
216 |
217 | BluetoothGattCharacteristic myGatChar
218 | = myGatService.getCharacteristic(Characteristics /*Consts.UUID_CHARACTERISTIC_DEVICE_NAME*/);
219 | if (myGatChar != null) {
220 | Log.d(TAG, "* Reading data");
221 |
222 | boolean status = myGatBand.readCharacteristic(myGatChar);
223 | Log.d(TAG, "* Read status :" + status);
224 | }
225 | }
226 | }
227 |
228 | public void writeData(UUID service, UUID Characteristics,byte[] data) {
229 | if (!isConnectedToGatt || myGatBand == null) {
230 | Log.d(TAG, "Cant read from BLE, not initialized.");
231 | return;
232 | }
233 |
234 | Log.d(TAG, "* Getting gatt service, UUID:" + service.toString());
235 | BluetoothGattService myGatService =
236 | myGatBand.getService(service /*Consts.UUID_SERVICE_HEARTBEAT*/);
237 | if (myGatService != null) {
238 | Log.d(TAG, "* Getting gatt Characteristic. UUID: " + Characteristics.toString());
239 |
240 | BluetoothGattCharacteristic myGatChar
241 | = myGatService.getCharacteristic(Characteristics /*Consts.UUID_START_HEARTRATE_CONTROL_POINT*/);
242 | if (myGatChar != null) {
243 | Log.d(TAG, "* Writing trigger");
244 | myGatChar.setValue(data /*Consts.BYTE_NEW_HEART_RATE_SCAN*/);
245 |
246 | boolean status = myGatBand.writeCharacteristic(myGatChar);
247 | Log.d(TAG, "* Writting trigger status :" + status);
248 | }
249 | }
250 | }
251 |
252 | public void getNotifications(UUID service, UUID Characteristics) {
253 | if (!isConnectedToGatt || myGatBand == null) {
254 | Log.d(TAG, "Cant get notifications from BLE, not initialized.");
255 | return;
256 | }
257 |
258 | Log.d(TAG, "* Getting gatt service, UUID:" + service.toString());
259 | BluetoothGattService myGatService =
260 | myGatBand.getService(service/*Consts.UUID_SERVICE_MIBAND_SERVICE*/);
261 | if (myGatService != null) {
262 | Log.d(TAG, "* Getting gatt Characteristic. UUID: " + Characteristics.toString());
263 |
264 | BluetoothGattCharacteristic myGatChar
265 | = myGatService.getCharacteristic(Characteristics/*Consts.UUID_BUTTON_TOUCH*/);
266 | if (myGatChar != null) {
267 | Log.d(TAG, "* Statring listening");
268 |
269 | // second parametes is for starting\stopping the listener.
270 | boolean status = myGatBand.setCharacteristicNotification(myGatChar, true);
271 | Log.d(TAG, "* Set notification status :" + status);
272 | }
273 | }
274 | }
275 |
276 | /**
277 | * Get notification but also set descriptor to Enable notification. You need to wait couple of
278 | * seconds before you could use it (at least in the mi band 2)
279 | * @param service
280 | * @param Characteristics
281 | */
282 | public void getNotificationsWithDescriptor(UUID service, UUID Characteristics, UUID Descriptor) {
283 | if (!isConnectedToGatt || myGatBand == null) {
284 | Log.d(TAG, "Cant get notifications from BLE, not initialized.");
285 | return;
286 | }
287 |
288 | Log.d(TAG, "* Getting gatt service, UUID:" + service.toString());
289 | BluetoothGattService myGatService =
290 | myGatBand.getService(service/*Consts.UUID_SERVICE_MIBAND_SERVICE*/);
291 | if (myGatService != null) {
292 | Log.d(TAG, "* Getting gatt Characteristic. UUID: " + Characteristics.toString());
293 |
294 | BluetoothGattCharacteristic myGatChar
295 | = myGatService.getCharacteristic(Characteristics/*Consts.UUID_BUTTON_TOUCH*/);
296 | if (myGatChar != null) {
297 | Log.d(TAG, "* Statring listening");
298 |
299 | // second parametes is for starting\stopping the listener.
300 | boolean status = myGatBand.setCharacteristicNotification(myGatChar, true);
301 | Log.d(TAG, "* Set notification status :" + status);
302 |
303 | BluetoothGattDescriptor myDescriptor
304 | = myGatChar.getDescriptor(Descriptor/*Consts.UUID_DESCRIPTOR_UPDATE_NOTIFICATION*/);
305 | if (myDescriptor != null) {
306 | Log.d(TAG, "Writing decriptor: " + Descriptor.toString());
307 | myDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
308 | status = myGatBand.writeDescriptor(myDescriptor);
309 | Log.d(TAG, "Writing decriptors result: " + status);
310 | }
311 | }
312 | }
313 | }
314 |
315 | }
316 |
317 |
318 |
319 |
320 |
321 |
--------------------------------------------------------------------------------