├── .gitignore
├── .travis.yml
├── BLE SIM icon.png
├── Battery Service.png
├── Health Thermometer Service.png
├── Heart Rate Service.png
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── io
│ │ └── github
│ │ └── webbluetoothcg
│ │ └── bletestperipheral
│ │ └── ApplicationTest.java
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── io
│ │ └── github
│ │ └── webbluetoothcg
│ │ └── bletestperipheral
│ │ ├── BatteryServiceFragment.java
│ │ ├── HealthThermometerServiceFragment.java
│ │ ├── HeartRateServiceFragment.java
│ │ ├── Peripheral.java
│ │ ├── Peripherals.java
│ │ └── ServiceFragment.java
│ └── res
│ ├── drawable
│ └── battery_icon.xml
│ ├── layout
│ ├── activity_peripherals.xml
│ ├── activity_peripherals_list.xml
│ ├── fragment_battery.xml
│ ├── fragment_health_thermometer.xml
│ └── fragment_heart_rate.xml
│ ├── menu
│ └── menu_peripheral.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
│ └── values
│ ├── body_sensor_location_values.xml
│ ├── color.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── ic_play_store.png
├── ic_play_store_wide.png
├── settings.gradle
└── travis
└── build.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 |
15 | # Gradle files
16 | .gradle/
17 | build/
18 |
19 | # Local configuration file (sdk path, etc)
20 | local.properties
21 |
22 | # Proguard folder generated by Eclipse
23 | proguard/
24 |
25 | # Log Files
26 | *.log
27 |
28 | # Idea files
29 | /.idea/
30 |
31 | # iml files
32 | *.iml
33 |
34 | # Mac Files
35 | .DS_Store
36 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | jdk: oraclejdk8
3 | android:
4 | components:
5 | # Install latest SDK and tools
6 | - platform-tools
7 | - tools
8 |
9 | # The BuildTools version
10 | - build-tools-26.0.2
11 |
12 | # The SDK version used to compile
13 | - android-22
14 |
15 | # Use extra android repo locations to find the appcompat-v7:21.0.0 support library
16 | - extra
17 |
18 | # Specify the build script to run.
19 | script: "./travis/build.sh"
20 |
--------------------------------------------------------------------------------
/BLE SIM icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/BLE SIM icon.png
--------------------------------------------------------------------------------
/Battery Service.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/Battery Service.png
--------------------------------------------------------------------------------
/Health Thermometer Service.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/Health Thermometer Service.png
--------------------------------------------------------------------------------
/Heart Rate Service.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/Heart Rate Service.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BLE Peripheral Simulator
2 | [](https://travis-ci.org/WebBluetoothCG/ble-test-peripheral-android)
3 |
4 | The BLE Peripheral Simulator is an Android app that allows developers to try
5 | out new features of Web Bluetooth without the need for a BLE Peripheral Device.
6 |
7 | You can build it from source or install it from the [Google Play Store](https://play.google.com/store/apps/details?id=io.github.webbluetoothcg.bletestperipheral).
8 |
9 | A developer can use the app to simulate a BLE Peripheral with one of three services:
10 |
11 | * Battery Service
12 | * Heart Rate Service
13 | * Health Thermometer Service
14 |
15 | The developer can use the new Web Bluetooth features to connect to the app to Read and Write Characteristics, Subscribe to Notifications for when the Characteristics change, and Read and Write Descriptors.
16 |
17 | From the app a developer can set the characteristics' values, send notifications and disconnect.
18 |
19 | 
20 | 
21 | 
22 |
23 | ### Caveats
24 |
25 | BLE peripheral mode was introduced in Android 5.0 Lollipop. Due to hardware chipset dependency, some devices don't have access to this feature. Here's a non-exhaustive list of devices that support BLE peripheral mode at the time of writing: Nexus 5X, Nexus 6P, Nexus 6, Nexus 9, Moto E 4G LTE, LG G4, Galaxy S6. See https://altbeacon.github.io/android-beacon-library/beacon-transmitter-devices.html for more.
26 |
27 | Source: http://stackoverflow.com/questions/26482611/chipsets-devices-supporting-android-5-ble-peripheral-mode
28 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 22
5 | buildToolsVersion '26.0.2'
6 | defaultConfig {
7 | applicationId "io.github.webbluetoothcg.bletestperipheral"
8 | minSdkVersion 21
9 | targetSdkVersion 22
10 | versionCode 10
11 | versionName '10.0'
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | lintOptions {
20 | quiet true
21 | checkReleaseBuilds false
22 | // if true, stop the gradle build if errors are found
23 | abortOnError false
24 | }
25 | }
26 |
27 | dependencies {
28 | compile fileTree(include: ['*.jar'], dir: 'libs')
29 | }
30 |
--------------------------------------------------------------------------------
/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 $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/src/androidTest/java/io/github/webbluetoothcg/bletestperipheral/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package io.github.webbluetoothcg.bletestperipheral;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 |
11 | public ApplicationTest() {
12 | super(Application.class);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
21 |
22 |
23 |
28 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/webbluetoothcg/bletestperipheral/BatteryServiceFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google Inc. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.webbluetoothcg.bletestperipheral;
18 |
19 | import android.app.Activity;
20 | import android.bluetooth.BluetoothGattCharacteristic;
21 | import android.bluetooth.BluetoothGattDescriptor;
22 | import android.bluetooth.BluetoothGattService;
23 | import android.os.Bundle;
24 | import android.os.ParcelUuid;
25 | import android.view.KeyEvent;
26 | import android.view.LayoutInflater;
27 | import android.view.View;
28 | import android.view.View.OnClickListener;
29 | import android.view.ViewGroup;
30 | import android.view.inputmethod.EditorInfo;
31 | import android.widget.Button;
32 | import android.widget.EditText;
33 | import android.widget.SeekBar;
34 | import android.widget.SeekBar.OnSeekBarChangeListener;
35 | import android.widget.TextView;
36 | import android.widget.TextView.OnEditorActionListener;
37 | import android.widget.Toast;
38 |
39 | import java.util.UUID;
40 |
41 |
42 | public class BatteryServiceFragment extends ServiceFragment {
43 |
44 | private static final UUID BATTERY_SERVICE_UUID = UUID
45 | .fromString("0000180F-0000-1000-8000-00805f9b34fb");
46 |
47 | private static final UUID BATTERY_LEVEL_UUID = UUID
48 | .fromString("00002A19-0000-1000-8000-00805f9b34fb");
49 | private static final int INITIAL_BATTERY_LEVEL = 50;
50 | private static final int BATTERY_LEVEL_MAX = 100;
51 | private static final String BATTERY_LEVEL_DESCRIPTION = "The current charge level of a " +
52 | "battery. 100% represents fully charged while 0% represents fully discharged.";
53 |
54 | private ServiceFragmentDelegate mDelegate;
55 | // UI
56 | private EditText mBatteryLevelEditText;
57 | private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() {
58 | @Override
59 | public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
60 | if (actionId == EditorInfo.IME_ACTION_DONE) {
61 | String newBatteryLevelString = textView.getText().toString();
62 | // Need to check if the string is empty since isDigitsOnly returns
63 | // true for empty strings.
64 | if (!newBatteryLevelString.isEmpty()
65 | && android.text.TextUtils.isDigitsOnly(newBatteryLevelString)) {
66 | int newBatteryLevel = Integer.parseInt(newBatteryLevelString);
67 | if (newBatteryLevel <= BATTERY_LEVEL_MAX) {
68 | setBatteryLevel(newBatteryLevel, textView);
69 | } else {
70 | Toast.makeText(getActivity(), R.string.batteryLevelTooHigh, Toast.LENGTH_SHORT)
71 | .show();
72 | }
73 | } else {
74 | Toast.makeText(getActivity(), R.string.batteryLevelIncorrect, Toast.LENGTH_SHORT)
75 | .show();
76 | }
77 | }
78 | return false;
79 | }
80 | };
81 | private SeekBar mBatteryLevelSeekBar;
82 | private final OnSeekBarChangeListener mOnSeekBarChangeListener = new OnSeekBarChangeListener() {
83 | @Override
84 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
85 | if (fromUser) {
86 | setBatteryLevel(progress, seekBar);
87 | }
88 | }
89 |
90 | @Override
91 | public void onStartTrackingTouch(SeekBar seekBar) {
92 |
93 | }
94 |
95 | @Override
96 | public void onStopTrackingTouch(SeekBar seekBar) {
97 |
98 | }
99 | };
100 |
101 | private final OnClickListener mNotifyButtonListener = new OnClickListener() {
102 | @Override
103 | public void onClick(View v) {
104 | mDelegate.sendNotificationToDevices(mBatteryLevelCharacteristic);
105 | }
106 | };
107 |
108 | // GATT
109 | private BluetoothGattService mBatteryService;
110 | private BluetoothGattCharacteristic mBatteryLevelCharacteristic;
111 |
112 | public BatteryServiceFragment() {
113 | mBatteryLevelCharacteristic =
114 | new BluetoothGattCharacteristic(BATTERY_LEVEL_UUID,
115 | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
116 | BluetoothGattCharacteristic.PERMISSION_READ);
117 |
118 | mBatteryLevelCharacteristic.addDescriptor(
119 | Peripheral.getClientCharacteristicConfigurationDescriptor());
120 |
121 | mBatteryLevelCharacteristic.addDescriptor(
122 | Peripheral.getCharacteristicUserDescriptionDescriptor(BATTERY_LEVEL_DESCRIPTION));
123 |
124 | mBatteryService = new BluetoothGattService(BATTERY_SERVICE_UUID,
125 | BluetoothGattService.SERVICE_TYPE_PRIMARY);
126 | mBatteryService.addCharacteristic(mBatteryLevelCharacteristic);
127 | }
128 |
129 | // Lifecycle callbacks
130 | @Override
131 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
132 | Bundle savedInstanceState) {
133 |
134 | View view = inflater.inflate(R.layout.fragment_battery, container, false);
135 |
136 | mBatteryLevelEditText = (EditText) view.findViewById(R.id.textView_batteryLevel);
137 | mBatteryLevelEditText.setOnEditorActionListener(mOnEditorActionListener);
138 | mBatteryLevelSeekBar = (SeekBar) view.findViewById(R.id.seekBar_batteryLevel);
139 | mBatteryLevelSeekBar.setOnSeekBarChangeListener(mOnSeekBarChangeListener);
140 | Button notifyButton = (Button) view.findViewById(R.id.button_batteryLevelNotify);
141 | notifyButton.setOnClickListener(mNotifyButtonListener);
142 |
143 | setBatteryLevel(INITIAL_BATTERY_LEVEL, null);
144 | return view;
145 | }
146 |
147 | @Override
148 | public void onAttach(Activity activity) {
149 | super.onAttach(activity);
150 | try {
151 | mDelegate = (ServiceFragmentDelegate) activity;
152 | } catch (ClassCastException e) {
153 | throw new ClassCastException(activity.toString()
154 | + " must implement ServiceFragmentDelegate");
155 | }
156 | }
157 |
158 | @Override
159 | public void onDetach() {
160 | super.onDetach();
161 | mDelegate = null;
162 | }
163 |
164 | public BluetoothGattService getBluetoothGattService() {
165 | return mBatteryService;
166 | }
167 |
168 | @Override
169 | public ParcelUuid getServiceUUID() {
170 | return new ParcelUuid(BATTERY_SERVICE_UUID);
171 | }
172 |
173 | private void setBatteryLevel(int newBatteryLevel, View source) {
174 | mBatteryLevelCharacteristic.setValue(newBatteryLevel,
175 | BluetoothGattCharacteristic.FORMAT_UINT8, /* offset */ 0);
176 | if (source != mBatteryLevelSeekBar) {
177 | mBatteryLevelSeekBar.setProgress(newBatteryLevel);
178 | }
179 | if (source != mBatteryLevelEditText) {
180 | mBatteryLevelEditText.setText(Integer.toString(newBatteryLevel));
181 | }
182 | }
183 |
184 | @Override
185 | public void notificationsEnabled(BluetoothGattCharacteristic characteristic, boolean indicate) {
186 | if (characteristic.getUuid() != BATTERY_LEVEL_UUID) {
187 | return;
188 | }
189 | if (indicate) {
190 | return;
191 | }
192 | getActivity().runOnUiThread(new Runnable() {
193 | @Override
194 | public void run() {
195 | Toast.makeText(getActivity(), R.string.notificationsEnabled, Toast.LENGTH_SHORT)
196 | .show();
197 | }
198 | });
199 | }
200 |
201 | @Override
202 | public void notificationsDisabled(BluetoothGattCharacteristic characteristic) {
203 | if (characteristic.getUuid() != BATTERY_LEVEL_UUID) {
204 | return;
205 | }
206 | getActivity().runOnUiThread(new Runnable() {
207 | @Override
208 | public void run() {
209 | Toast.makeText(getActivity(), R.string.notificationsNotEnabled, Toast.LENGTH_SHORT)
210 | .show();
211 | }
212 | });
213 | }
214 | }
215 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/webbluetoothcg/bletestperipheral/HealthThermometerServiceFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Google Inc. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.webbluetoothcg.bletestperipheral;
18 |
19 | import android.app.Activity;
20 | import android.bluetooth.BluetoothGatt;
21 | import android.bluetooth.BluetoothGattCharacteristic;
22 | import android.bluetooth.BluetoothGattDescriptor;
23 | import android.bluetooth.BluetoothGattService;
24 | import android.os.Bundle;
25 | import android.os.ParcelUuid;
26 | import android.view.KeyEvent;
27 | import android.view.LayoutInflater;
28 | import android.view.View;
29 | import android.view.ViewGroup;
30 | import android.view.inputmethod.EditorInfo;
31 | import android.widget.EditText;
32 | import android.widget.TextView;
33 | import android.widget.TextView.OnEditorActionListener;
34 | import android.widget.Toast;
35 |
36 | import java.nio.ByteBuffer;
37 | import java.nio.ByteOrder;
38 | import java.util.Timer;
39 | import java.util.TimerTask;
40 | import java.util.UUID;
41 |
42 | public class HealthThermometerServiceFragment extends ServiceFragment {
43 | /**
44 | * See
45 | * Health Thermometer Service
46 | * This service exposes two characteristics with descriptors:
47 | * - Measurement Interval Characteristic:
48 | * - Listen to notifications to from which you can subscribe to notifications
49 | * - CCCD Descriptor:
50 | * - Read/Write to get/set notifications.
51 | * - User Description Descriptor:
52 | * - Read/Write to get/set the description of the Characteristic.
53 | * - Temperature Measurement Characteristic:
54 | * - Read value to get the current interval of the temperature measurement timer.
55 | * - Write value resets the temperature measurement timer with the new value. This timer
56 | * is responsible for triggering value changed events every "Measurement Interval" value.
57 | * - CCCD Descriptor:
58 | * - Read/Write to get/set notifications.
59 | * - User Description Descriptor:
60 | * - Read/Write to get/set the description of the Characteristic.
61 | */
62 | private static final UUID HEALTH_THERMOMETER_SERVICE_UUID = UUID
63 | .fromString("00001809-0000-1000-8000-00805f9b34fb");
64 |
65 | /**
66 | * See
67 | * Temperature Measurement
68 | */
69 | private static final UUID TEMPERATURE_MEASUREMENT_UUID = UUID
70 | .fromString("00002A1C-0000-1000-8000-00805f9b34fb");
71 | private static final int TEMPERATURE_MEASUREMENT_VALUE_FORMAT = BluetoothGattCharacteristic.FORMAT_FLOAT;
72 | private static final float INITIAL_TEMPERATURE_MEASUREMENT_VALUE = 37.0f;
73 | private static final int EXPONENT_MASK = 0x7f800000;
74 | private static final int EXPONENT_SHIFT = 23;
75 | private static final int MANTISSA_MASK = 0x007fffff;
76 | private static final int MANTISSA_SHIFT = 0;
77 | private static final String TEMPERATURE_MEASUREMENT_DESCRIPTION = "This characteristic is used " +
78 | "to send a temperature measurement.";
79 |
80 | /**
81 | * See
82 | * Measurement Interval
83 | */
84 | private static final UUID MEASUREMENT_INTERVAL_UUID = UUID
85 | .fromString("00002A21-0000-1000-8000-00805f9b34fb");
86 | private static final int MEASUREMENT_INTERVAL_FORMAT = BluetoothGattCharacteristic.FORMAT_UINT16;
87 | private static final int INITIAL_MEASUREMENT_INTERVAL = 1;
88 | private static final int MIN_MEASUREMENT_INTERVAL = 1;
89 | private static final int MAX_MEASUREMENT_INTERVAL = (int) Math.pow(2, 16) - 1;
90 | private static final String MEASUREMENT_INTERVAL_DESCRIPTION = "This characteristic is used " +
91 | "to enable and control the interval between consecutive temperature measurements.";
92 |
93 | private BluetoothGattService mHealthThermometerService;
94 | private BluetoothGattCharacteristic mTemperatureMeasurementCharacteristic;
95 | private BluetoothGattCharacteristic mMeasurementIntervalCharacteristic;
96 | private BluetoothGattDescriptor mMeasurementIntervalCCCDescriptor;
97 |
98 | private ServiceFragmentDelegate mDelegate;
99 |
100 | private Timer mTimer;
101 |
102 | private EditText mEditTextTemperatureMeasurement;
103 | private final OnEditorActionListener mOnEditorActionListenerTemperatureMeasurement = new OnEditorActionListener() {
104 | @Override
105 | public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
106 | if (actionId == EditorInfo.IME_ACTION_DONE) {
107 | String newTemperatureMeasurementValueString = textView.getText().toString();
108 | if (isValidTemperatureMeasurementValue(newTemperatureMeasurementValueString)) {
109 | float newTemperatureMeasurementValue = Float.valueOf(newTemperatureMeasurementValueString);
110 | setTemperatureMeasurementValue(newTemperatureMeasurementValue);
111 | } else {
112 | Toast.makeText(getActivity(), R.string.temperatureMeasurementValueInvalid,
113 | Toast.LENGTH_SHORT).show();
114 | }
115 | }
116 | return false;
117 | }
118 | };
119 |
120 | private final OnEditorActionListener mOnEditorActionListenerMeasurementInterval = new OnEditorActionListener() {
121 | @Override
122 | public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
123 | if (actionId == EditorInfo.IME_ACTION_DONE) {
124 | int newMeasurementInterval = Integer.parseInt(textView.getText().toString());
125 | if (isValidMeasurementIntervalValue(newMeasurementInterval)) {
126 | mMeasurementIntervalCharacteristic.setValue(newMeasurementInterval,
127 | MEASUREMENT_INTERVAL_FORMAT,
128 | /* offset */ 0);
129 | resetTimer(newMeasurementInterval);
130 | } else {
131 | Toast.makeText(getActivity(), R.string.measurementIntervalInvalid,
132 | Toast.LENGTH_SHORT).show();
133 | }
134 | }
135 | return false;
136 | }
137 | };
138 | private EditText mEditTextMeasurementInterval;
139 |
140 | private TextView mTextViewNotifications;
141 |
142 | public HealthThermometerServiceFragment() {
143 | mTemperatureMeasurementCharacteristic =
144 | new BluetoothGattCharacteristic(TEMPERATURE_MEASUREMENT_UUID,
145 | BluetoothGattCharacteristic.PROPERTY_INDICATE,
146 | /* No permissions */ 0);
147 |
148 | mTemperatureMeasurementCharacteristic.addDescriptor(
149 | Peripheral.getClientCharacteristicConfigurationDescriptor());
150 |
151 | mTemperatureMeasurementCharacteristic.addDescriptor(
152 | Peripheral.getCharacteristicUserDescriptionDescriptor(TEMPERATURE_MEASUREMENT_DESCRIPTION));
153 |
154 | mMeasurementIntervalCharacteristic =
155 | new BluetoothGattCharacteristic(
156 | MEASUREMENT_INTERVAL_UUID,
157 | (BluetoothGattCharacteristic.PROPERTY_READ |
158 | BluetoothGattCharacteristic.PROPERTY_WRITE |
159 | BluetoothGattCharacteristic.PROPERTY_INDICATE),
160 | (BluetoothGattCharacteristic.PERMISSION_READ |
161 | BluetoothGattCharacteristic.PERMISSION_WRITE));
162 |
163 | mMeasurementIntervalCCCDescriptor = Peripheral.getClientCharacteristicConfigurationDescriptor();
164 | mMeasurementIntervalCharacteristic.addDescriptor(mMeasurementIntervalCCCDescriptor);
165 |
166 | mMeasurementIntervalCharacteristic.addDescriptor(
167 | Peripheral.getCharacteristicUserDescriptionDescriptor(MEASUREMENT_INTERVAL_DESCRIPTION));
168 |
169 | mHealthThermometerService = new BluetoothGattService(HEALTH_THERMOMETER_SERVICE_UUID,
170 | BluetoothGattService.SERVICE_TYPE_PRIMARY);
171 | mHealthThermometerService.addCharacteristic(mTemperatureMeasurementCharacteristic);
172 | mHealthThermometerService.addCharacteristic(mMeasurementIntervalCharacteristic);
173 | }
174 |
175 |
176 | @Override
177 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
178 | Bundle savedInstanceState) {
179 |
180 | View view = inflater.inflate(R.layout.fragment_health_thermometer, container, false);
181 | mEditTextTemperatureMeasurement = (EditText) view
182 | .findViewById(R.id.editText_temperatureMeasurementValue);
183 | mEditTextTemperatureMeasurement
184 | .setOnEditorActionListener(mOnEditorActionListenerTemperatureMeasurement);
185 | mEditTextMeasurementInterval = (EditText) view
186 | .findViewById(R.id.editText_measurementIntervalValue);
187 | mEditTextMeasurementInterval
188 | .setOnEditorActionListener(mOnEditorActionListenerMeasurementInterval);
189 |
190 | mEditTextTemperatureMeasurement.setText(Float.toString(INITIAL_TEMPERATURE_MEASUREMENT_VALUE));
191 | setTemperatureMeasurementValue(INITIAL_TEMPERATURE_MEASUREMENT_VALUE);
192 |
193 | mMeasurementIntervalCharacteristic.setValue(INITIAL_MEASUREMENT_INTERVAL,
194 | MEASUREMENT_INTERVAL_FORMAT,
195 | /* offset */ 0);
196 | mEditTextMeasurementInterval.setText(Integer.toString(INITIAL_MEASUREMENT_INTERVAL));
197 |
198 | mTextViewNotifications = (TextView) view.findViewById(R.id.textView_notifications);
199 | mTextViewNotifications.setText(R.string.notificationsNotEnabled);
200 |
201 | return view;
202 | }
203 |
204 | @Override
205 | public void onAttach(Activity activity) {
206 | super.onAttach(activity);
207 | try {
208 | mDelegate = (ServiceFragmentDelegate) activity;
209 | } catch (ClassCastException e) {
210 | throw new ClassCastException(activity.toString()
211 | + " must implement ServiceFragmentDelegate");
212 | }
213 | }
214 |
215 | @Override
216 | public void onDetach() {
217 | super.onDetach();
218 | mDelegate = null;
219 | }
220 |
221 | @Override
222 | public void onStop() {
223 | super.onStop();
224 | cancelTimer();
225 | }
226 |
227 | @Override
228 | public BluetoothGattService getBluetoothGattService() {
229 | return mHealthThermometerService;
230 | }
231 |
232 | @Override
233 | public ParcelUuid getServiceUUID() {
234 | return new ParcelUuid(HEALTH_THERMOMETER_SERVICE_UUID);
235 | }
236 |
237 | private void setTemperatureMeasurementValue(float temperatureMeasurementValue) {
238 |
239 | /* Set the org.bluetooth.characteristic.temperature_measurement
240 | * characteristic to a byte array of size 5 so
241 | * we can use setValue(value, format, offset);
242 | *
243 | * Flags (8bit) + Temperature Measurement Value (float) = 5 bytes
244 | *
245 | * Flags:
246 | * Temperature Units Flag (0) -> Celsius
247 | * Time Stamp Flag (0) -> Time Stamp field not present
248 | * Temperature Type Flag (0) -> Temperature Type field not present
249 | * Unused (00000)
250 | */
251 | mTemperatureMeasurementCharacteristic.setValue(new byte[]{0b00000000, 0, 0, 0, 0});
252 | // Characteristic Value: [flags, 0, 0, 0, 0]
253 |
254 | int bits = Float.floatToIntBits(temperatureMeasurementValue);
255 | int exponent = (bits & EXPONENT_MASK) >>> EXPONENT_SHIFT;
256 | int mantissa = (bits & MANTISSA_MASK) >>> MANTISSA_SHIFT;
257 |
258 | mTemperatureMeasurementCharacteristic.setValue(mantissa, exponent,
259 | TEMPERATURE_MEASUREMENT_VALUE_FORMAT,
260 | /* offset */ 1);
261 | // Characteristic Value: [flags, temperature measurement value]
262 | }
263 |
264 | private void setTemperatureMeasurementTimerInterval(int measurementIntervalValueSeconds) {
265 | mTimer = new Timer();
266 | mTimer.scheduleAtFixedRate(new TimerTask() {
267 | @Override
268 | public void run() {
269 | getActivity().runOnUiThread(new Runnable() {
270 | @Override
271 | public void run() {
272 | mDelegate.sendNotificationToDevices(mTemperatureMeasurementCharacteristic);
273 | }
274 | });
275 | }
276 | }, 0 /* delay */, measurementIntervalValueSeconds * 1000);
277 | }
278 |
279 | private void cancelTimer() {
280 | if (mTimer != null) {
281 | mTimer.cancel();
282 | }
283 | }
284 |
285 | private void resetTimer(int measurementIntervalValue) {
286 | cancelTimer();
287 | setTemperatureMeasurementTimerInterval(measurementIntervalValue);
288 | }
289 |
290 | private boolean isValidTemperatureMeasurementValue(String s) {
291 | try {
292 | float value = Float.valueOf(s);
293 | return true;
294 | } catch (NumberFormatException e) {
295 | return false;
296 | }
297 | }
298 |
299 | private boolean isValidMeasurementIntervalValue(int value) {
300 | return (value >= MIN_MEASUREMENT_INTERVAL) && (value <= MAX_MEASUREMENT_INTERVAL);
301 | }
302 |
303 | @Override
304 | public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) {
305 | if (offset != 0) {
306 | return BluetoothGatt.GATT_INVALID_OFFSET;
307 | }
308 | // Measurement Interval is a 16bit characteristic
309 | if (value.length != 2) {
310 | return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
311 | }
312 | ByteBuffer byteBuffer = ByteBuffer.wrap(value);
313 | byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
314 | final int newMeasurementIntervalValue = byteBuffer.getShort();
315 | if (!isValidMeasurementIntervalValue(newMeasurementIntervalValue)) {
316 | return BluetoothGatt.GATT_FAILURE;
317 | }
318 | getActivity().runOnUiThread(new Runnable() {
319 | @Override
320 | public void run() {
321 | mMeasurementIntervalCharacteristic.setValue(newMeasurementIntervalValue,
322 | MEASUREMENT_INTERVAL_FORMAT,
323 | /* offset */ 0);
324 | if (mMeasurementIntervalCCCDescriptor.getValue() == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE) {
325 | resetTimer(newMeasurementIntervalValue);
326 | mTextViewNotifications.setText(R.string.notificationsEnabled);
327 | }
328 | }
329 | });
330 | return BluetoothGatt.GATT_SUCCESS;
331 | }
332 |
333 | @Override
334 | public void notificationsDisabled(BluetoothGattCharacteristic characteristic) {
335 | if (characteristic.getUuid() != TEMPERATURE_MEASUREMENT_UUID) {
336 | return;
337 | }
338 | cancelTimer();
339 | getActivity().runOnUiThread(new Runnable() {
340 | @Override
341 | public void run() {
342 | mTextViewNotifications.setText(R.string.notificationsNotEnabled);
343 | }
344 | });
345 | }
346 |
347 | @Override
348 | public void notificationsEnabled(BluetoothGattCharacteristic characteristic, boolean indicate) {
349 | if (characteristic.getUuid() != TEMPERATURE_MEASUREMENT_UUID) {
350 | return;
351 | }
352 | if (!indicate) {
353 | return;
354 | }
355 | getActivity().runOnUiThread(new Runnable() {
356 | @Override
357 | public void run() {
358 | int newMeasurementInterval = Integer.parseInt(mEditTextMeasurementInterval.getText()
359 | .toString());
360 | if (isValidMeasurementIntervalValue(newMeasurementInterval)) {
361 | mMeasurementIntervalCharacteristic.setValue(newMeasurementInterval,
362 | MEASUREMENT_INTERVAL_FORMAT,
363 | /* offset */ 0);
364 | resetTimer(newMeasurementInterval);
365 | mTextViewNotifications.setText(R.string.notificationsEnabled);
366 | }
367 | }
368 | });
369 | }
370 |
371 | }
372 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/webbluetoothcg/bletestperipheral/HeartRateServiceFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google Inc. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.webbluetoothcg.bletestperipheral;
18 |
19 | import android.app.Activity;
20 | import android.bluetooth.BluetoothGatt;
21 | import android.bluetooth.BluetoothGattCharacteristic;
22 | import android.bluetooth.BluetoothGattDescriptor;
23 | import android.bluetooth.BluetoothGattService;
24 | import android.os.Bundle;
25 | import android.os.ParcelUuid;
26 | import android.util.Log;
27 | import android.view.KeyEvent;
28 | import android.view.LayoutInflater;
29 | import android.view.View;
30 | import android.view.View.OnClickListener;
31 | import android.view.ViewGroup;
32 | import android.view.inputmethod.EditorInfo;
33 | import android.widget.AdapterView;
34 | import android.widget.AdapterView.OnItemSelectedListener;
35 | import android.widget.Button;
36 | import android.widget.EditText;
37 | import android.widget.Spinner;
38 | import android.widget.TextView;
39 | import android.widget.TextView.OnEditorActionListener;
40 | import android.widget.Toast;
41 |
42 | import java.util.Arrays;
43 | import java.util.UUID;
44 |
45 | public class HeartRateServiceFragment extends ServiceFragment {
46 | private static final String TAG = HeartRateServiceFragment.class.getCanonicalName();
47 | private static final int MIN_UINT = 0;
48 | private static final int MAX_UINT8 = (int) Math.pow(2, 8) - 1;
49 | private static final int MAX_UINT16 = (int) Math.pow(2, 16) - 1;
50 | /**
51 | * See
52 | * Heart Rate Service
53 | */
54 | private static final UUID HEART_RATE_SERVICE_UUID = UUID
55 | .fromString("0000180D-0000-1000-8000-00805f9b34fb");
56 |
57 | /**
58 | * See
59 | * Heart Rate Measurement
60 | */
61 | private static final UUID HEART_RATE_MEASUREMENT_UUID = UUID
62 | .fromString("00002A37-0000-1000-8000-00805f9b34fb");
63 | private static final int HEART_RATE_MEASUREMENT_VALUE_FORMAT = BluetoothGattCharacteristic.FORMAT_UINT8;
64 | private static final int INITIAL_HEART_RATE_MEASUREMENT_VALUE = 60;
65 | private static final int EXPENDED_ENERGY_FORMAT = BluetoothGattCharacteristic.FORMAT_UINT16;
66 | private static final int INITIAL_EXPENDED_ENERGY = 0;
67 | private static final String HEART_RATE_MEASUREMENT_DESCRIPTION = "Used to send a heart rate " +
68 | "measurement";
69 |
70 | /**
71 | * See
72 | * Body Sensor Location
73 | */
74 | private static final UUID BODY_SENSOR_LOCATION_UUID = UUID
75 | .fromString("00002A38-0000-1000-8000-00805f9b34fb");
76 | private static final int LOCATION_OTHER = 0;
77 |
78 | /**
79 | * See
80 | * Heart Rate Control Point
81 | */
82 | private static final UUID HEART_RATE_CONTROL_POINT_UUID = UUID
83 | .fromString("00002A39-0000-1000-8000-00805f9b34fb");
84 |
85 | private BluetoothGattService mHeartRateService;
86 | private BluetoothGattCharacteristic mHeartRateMeasurementCharacteristic;
87 | private BluetoothGattCharacteristic mBodySensorLocationCharacteristic;
88 | private BluetoothGattCharacteristic mHeartRateControlPoint;
89 |
90 | private ServiceFragmentDelegate mDelegate;
91 |
92 | private EditText mEditTextHeartRateMeasurement;
93 | private final OnEditorActionListener mOnEditorActionListenerHeartRateMeasurement = new OnEditorActionListener() {
94 | @Override
95 | public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
96 | if (actionId == EditorInfo.IME_ACTION_DONE) {
97 | String newHeartRateMeasurementValueString = textView.getText().toString();
98 | if (isValidCharacteristicValue(newHeartRateMeasurementValueString,
99 | HEART_RATE_MEASUREMENT_VALUE_FORMAT)) {
100 | int newHeartRateMeasurementValue = Integer.parseInt(newHeartRateMeasurementValueString);
101 | mHeartRateMeasurementCharacteristic.setValue(newHeartRateMeasurementValue,
102 | HEART_RATE_MEASUREMENT_VALUE_FORMAT,
103 | /* offset */ 1);
104 | } else {
105 | Toast.makeText(getActivity(), R.string.heartRateMeasurementValueInvalid,
106 | Toast.LENGTH_SHORT).show();
107 | }
108 | }
109 | return false;
110 | }
111 | };
112 |
113 | private final OnEditorActionListener mOnEditorActionListenerEnergyExpended = new OnEditorActionListener() {
114 | @Override
115 | public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
116 | if (actionId == EditorInfo.IME_ACTION_DONE) {
117 | String newEnergyExpendedString = textView.getText().toString();
118 | if (isValidCharacteristicValue(newEnergyExpendedString,
119 | EXPENDED_ENERGY_FORMAT)) {
120 | int newEnergyExpended = Integer.parseInt(newEnergyExpendedString);
121 | mHeartRateMeasurementCharacteristic.setValue(newEnergyExpended,
122 | EXPENDED_ENERGY_FORMAT,
123 | /* offset */ 2);
124 | } else {
125 | Toast.makeText(getActivity(), R.string.energyExpendedInvalid,
126 | Toast.LENGTH_SHORT).show();
127 | }
128 | }
129 | return false;
130 | }
131 | };
132 | private EditText mEditTextEnergyExpended;
133 | private Spinner mSpinnerBodySensorLocation;
134 |
135 | private final OnItemSelectedListener mLocationSpinnerOnItemSelectedListener =
136 | new OnItemSelectedListener() {
137 | @Override
138 | public void onItemSelected(AdapterView> parent, View view, int position, long id) {
139 | setBodySensorLocationValue(position);
140 | }
141 |
142 | @Override
143 | public void onNothingSelected(AdapterView> parent) {
144 | }
145 | };
146 |
147 | private final OnClickListener mNotifyButtonListener = new OnClickListener() {
148 | @Override
149 | public void onClick(View v) {
150 | mDelegate.sendNotificationToDevices(mHeartRateMeasurementCharacteristic);
151 | }
152 | };
153 |
154 | public HeartRateServiceFragment() {
155 | mHeartRateMeasurementCharacteristic =
156 | new BluetoothGattCharacteristic(HEART_RATE_MEASUREMENT_UUID,
157 | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
158 | /* No permissions */ 0);
159 |
160 | mHeartRateMeasurementCharacteristic.addDescriptor(
161 | Peripheral.getClientCharacteristicConfigurationDescriptor());
162 |
163 | mHeartRateMeasurementCharacteristic.addDescriptor(
164 | Peripheral.getCharacteristicUserDescriptionDescriptor(HEART_RATE_MEASUREMENT_DESCRIPTION));
165 |
166 | mBodySensorLocationCharacteristic =
167 | new BluetoothGattCharacteristic(BODY_SENSOR_LOCATION_UUID,
168 | BluetoothGattCharacteristic.PROPERTY_READ,
169 | BluetoothGattCharacteristic.PERMISSION_READ);
170 |
171 | mHeartRateControlPoint =
172 | new BluetoothGattCharacteristic(HEART_RATE_CONTROL_POINT_UUID,
173 | BluetoothGattCharacteristic.PROPERTY_WRITE,
174 | BluetoothGattCharacteristic.PERMISSION_WRITE);
175 |
176 | mHeartRateService = new BluetoothGattService(HEART_RATE_SERVICE_UUID,
177 | BluetoothGattService.SERVICE_TYPE_PRIMARY);
178 | mHeartRateService.addCharacteristic(mHeartRateMeasurementCharacteristic);
179 | mHeartRateService.addCharacteristic(mBodySensorLocationCharacteristic);
180 | mHeartRateService.addCharacteristic(mHeartRateControlPoint);
181 | }
182 |
183 |
184 | @Override
185 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
186 | Bundle savedInstanceState) {
187 |
188 | View view = inflater.inflate(R.layout.fragment_heart_rate, container, false);
189 | mSpinnerBodySensorLocation = (Spinner) view.findViewById(R.id.spinner_bodySensorLocation);
190 | mSpinnerBodySensorLocation.setOnItemSelectedListener(mLocationSpinnerOnItemSelectedListener);
191 | mEditTextHeartRateMeasurement = (EditText) view
192 | .findViewById(R.id.editText_heartRateMeasurementValue);
193 | mEditTextHeartRateMeasurement
194 | .setOnEditorActionListener(mOnEditorActionListenerHeartRateMeasurement);
195 | mEditTextEnergyExpended = (EditText) view
196 | .findViewById(R.id.editText_energyExpended);
197 | mEditTextEnergyExpended
198 | .setOnEditorActionListener(mOnEditorActionListenerEnergyExpended);
199 | Button notifyButton = (Button) view.findViewById(R.id.button_heartRateMeasurementNotify);
200 | notifyButton.setOnClickListener(mNotifyButtonListener);
201 |
202 | setHeartRateMeasurementValue(INITIAL_HEART_RATE_MEASUREMENT_VALUE,
203 | INITIAL_EXPENDED_ENERGY);
204 | setBodySensorLocationValue(LOCATION_OTHER);
205 | return view;
206 | }
207 |
208 | @Override
209 | public void onAttach(Activity activity) {
210 | super.onAttach(activity);
211 | try {
212 | mDelegate = (ServiceFragmentDelegate) activity;
213 | } catch (ClassCastException e) {
214 | throw new ClassCastException(activity.toString()
215 | + " must implement ServiceFragmentDelegate");
216 | }
217 | }
218 |
219 | @Override
220 | public void onDetach() {
221 | super.onDetach();
222 | mDelegate = null;
223 | }
224 |
225 | @Override
226 | public BluetoothGattService getBluetoothGattService() {
227 | return mHeartRateService;
228 | }
229 |
230 | @Override
231 | public ParcelUuid getServiceUUID() {
232 | return new ParcelUuid(HEART_RATE_SERVICE_UUID);
233 | }
234 |
235 | private void setHeartRateMeasurementValue(int heartRateMeasurementValue, int expendedEnergy) {
236 |
237 | Log.d(TAG, Arrays.toString(mHeartRateMeasurementCharacteristic.getValue()));
238 | /* Set the org.bluetooth.characteristic.heart_rate_measurement
239 | * characteristic to a byte array of size 4 so
240 | * we can use setValue(value, format, offset);
241 | *
242 | * Flags (8bit) + Heart Rate Measurement Value (uint8) + Energy Expended (uint16) = 4 bytes
243 | *
244 | * Flags = 1 << 3:
245 | * Heart Rate Format (0) -> UINT8
246 | * Sensor Contact Status (00) -> Not Supported
247 | * Energy Expended (1) -> Field Present
248 | * RR-Interval (0) -> Field not pressent
249 | * Unused (000)
250 | */
251 | mHeartRateMeasurementCharacteristic.setValue(new byte[]{0b00001000, 0, 0, 0});
252 | // Characteristic Value: [flags, 0, 0, 0]
253 | mHeartRateMeasurementCharacteristic.setValue(heartRateMeasurementValue,
254 | HEART_RATE_MEASUREMENT_VALUE_FORMAT,
255 | /* offset */ 1);
256 | // Characteristic Value: [flags, heart rate value, 0, 0]
257 | mEditTextHeartRateMeasurement.setText(Integer.toString(heartRateMeasurementValue));
258 | mHeartRateMeasurementCharacteristic.setValue(expendedEnergy,
259 | EXPENDED_ENERGY_FORMAT,
260 | /* offset */ 2);
261 | // Characteristic Value: [flags, heart rate value, energy expended (LSB), energy expended (MSB)]
262 | mEditTextEnergyExpended.setText(Integer.toString(expendedEnergy));
263 | }
264 | private void setBodySensorLocationValue(int location) {
265 | mBodySensorLocationCharacteristic.setValue(new byte[]{(byte) location});
266 | mSpinnerBodySensorLocation.setSelection(location);
267 | }
268 |
269 | private boolean isValidCharacteristicValue(String s, int format) {
270 | try {
271 | int value = Integer.parseInt(s);
272 | if (format == BluetoothGattCharacteristic.FORMAT_UINT8) {
273 | return (value >= MIN_UINT) && (value <= MAX_UINT8);
274 | } else if (format == BluetoothGattCharacteristic.FORMAT_UINT16) {
275 | return (value >= MIN_UINT) && (value <= MAX_UINT16);
276 | } else {
277 | throw new IllegalArgumentException(format + " is not a valid argument");
278 | }
279 | } catch (NumberFormatException e) {
280 | return false;
281 | }
282 | }
283 |
284 | @Override
285 | public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) {
286 | if (offset != 0) {
287 | return BluetoothGatt.GATT_INVALID_OFFSET;
288 | }
289 | // Heart Rate control point is a 8bit characteristic
290 | if (value.length != 1) {
291 | return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
292 | }
293 | if ((value[0] & 1) == 1) {
294 | getActivity().runOnUiThread(new Runnable() {
295 | @Override
296 | public void run() {
297 | mHeartRateMeasurementCharacteristic.setValue(INITIAL_EXPENDED_ENERGY,
298 | EXPENDED_ENERGY_FORMAT, /* offset */ 2);
299 | mEditTextEnergyExpended.setText(Integer.toString(INITIAL_EXPENDED_ENERGY));
300 | }
301 | });
302 | }
303 | return BluetoothGatt.GATT_SUCCESS;
304 | }
305 |
306 | @Override
307 | public void notificationsEnabled(BluetoothGattCharacteristic characteristic, boolean indicate) {
308 | if (characteristic.getUuid() != HEART_RATE_MEASUREMENT_UUID) {
309 | return;
310 | }
311 | if (indicate) {
312 | return;
313 | }
314 | getActivity().runOnUiThread(new Runnable() {
315 | @Override
316 | public void run() {
317 | Toast.makeText(getActivity(), R.string.notificationsEnabled, Toast.LENGTH_SHORT)
318 | .show();
319 | }
320 | });
321 | }
322 |
323 | @Override
324 | public void notificationsDisabled(BluetoothGattCharacteristic characteristic) {
325 | if (characteristic.getUuid() != HEART_RATE_MEASUREMENT_UUID) {
326 | return;
327 | }
328 | getActivity().runOnUiThread(new Runnable() {
329 | @Override
330 | public void run() {
331 | Toast.makeText(getActivity(), R.string.notificationsNotEnabled, Toast.LENGTH_SHORT)
332 | .show();
333 | }
334 | });
335 | }
336 | }
337 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/webbluetoothcg/bletestperipheral/Peripheral.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google Inc. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.webbluetoothcg.bletestperipheral;
18 |
19 | import android.app.Activity;
20 | import android.bluetooth.BluetoothAdapter;
21 | import android.bluetooth.BluetoothDevice;
22 | import android.bluetooth.BluetoothGatt;
23 | import android.bluetooth.BluetoothGattCharacteristic;
24 | import android.bluetooth.BluetoothGattDescriptor;
25 | import android.bluetooth.BluetoothGattServer;
26 | import android.bluetooth.BluetoothGattServerCallback;
27 | import android.bluetooth.BluetoothGattService;
28 | import android.bluetooth.BluetoothManager;
29 | import android.bluetooth.le.AdvertiseCallback;
30 | import android.bluetooth.le.AdvertiseData;
31 | import android.bluetooth.le.AdvertiseSettings;
32 | import android.bluetooth.le.BluetoothLeAdvertiser;
33 | import android.content.Context;
34 | import android.content.Intent;
35 | import android.os.Bundle;
36 | import android.util.Log;
37 | import android.view.Menu;
38 | import android.view.MenuInflater;
39 | import android.view.MenuItem;
40 | import android.view.WindowManager;
41 | import android.widget.TextView;
42 | import android.widget.Toast;
43 |
44 | import java.util.Arrays;
45 | import java.util.HashSet;
46 | import java.util.UUID;
47 |
48 | import io.github.webbluetoothcg.bletestperipheral.ServiceFragment.ServiceFragmentDelegate;
49 |
50 | public class Peripheral extends Activity implements ServiceFragmentDelegate {
51 |
52 | private static final int REQUEST_ENABLE_BT = 1;
53 | private static final String TAG = Peripheral.class.getCanonicalName();
54 | private static final String CURRENT_FRAGMENT_TAG = "CURRENT_FRAGMENT";
55 |
56 | private static final UUID CHARACTERISTIC_USER_DESCRIPTION_UUID = UUID
57 | .fromString("00002901-0000-1000-8000-00805f9b34fb");
58 | private static final UUID CLIENT_CHARACTERISTIC_CONFIGURATION_UUID = UUID
59 | .fromString("00002902-0000-1000-8000-00805f9b34fb");
60 |
61 | private TextView mAdvStatus;
62 | private TextView mConnectionStatus;
63 | private ServiceFragment mCurrentServiceFragment;
64 | private BluetoothGattService mBluetoothGattService;
65 | private HashSet mBluetoothDevices;
66 | private BluetoothManager mBluetoothManager;
67 | private BluetoothAdapter mBluetoothAdapter;
68 | private AdvertiseData mAdvData;
69 | private AdvertiseData mAdvScanResponse;
70 | private AdvertiseSettings mAdvSettings;
71 | private BluetoothLeAdvertiser mAdvertiser;
72 | private final AdvertiseCallback mAdvCallback = new AdvertiseCallback() {
73 | @Override
74 | public void onStartFailure(int errorCode) {
75 | super.onStartFailure(errorCode);
76 | Log.e(TAG, "Not broadcasting: " + errorCode);
77 | int statusText;
78 | switch (errorCode) {
79 | case ADVERTISE_FAILED_ALREADY_STARTED:
80 | statusText = R.string.status_advertising;
81 | Log.w(TAG, "App was already advertising");
82 | break;
83 | case ADVERTISE_FAILED_DATA_TOO_LARGE:
84 | statusText = R.string.status_advDataTooLarge;
85 | break;
86 | case ADVERTISE_FAILED_FEATURE_UNSUPPORTED:
87 | statusText = R.string.status_advFeatureUnsupported;
88 | break;
89 | case ADVERTISE_FAILED_INTERNAL_ERROR:
90 | statusText = R.string.status_advInternalError;
91 | break;
92 | case ADVERTISE_FAILED_TOO_MANY_ADVERTISERS:
93 | statusText = R.string.status_advTooManyAdvertisers;
94 | break;
95 | default:
96 | statusText = R.string.status_notAdvertising;
97 | Log.wtf(TAG, "Unhandled error: " + errorCode);
98 | }
99 | mAdvStatus.setText(statusText);
100 | }
101 |
102 | @Override
103 | public void onStartSuccess(AdvertiseSettings settingsInEffect) {
104 | super.onStartSuccess(settingsInEffect);
105 | Log.v(TAG, "Broadcasting");
106 | mAdvStatus.setText(R.string.status_advertising);
107 | }
108 | };
109 |
110 | private BluetoothGattServer mGattServer;
111 | private final BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() {
112 | @Override
113 | public void onConnectionStateChange(BluetoothDevice device, final int status, int newState) {
114 | super.onConnectionStateChange(device, status, newState);
115 | if (status == BluetoothGatt.GATT_SUCCESS) {
116 | if (newState == BluetoothGatt.STATE_CONNECTED) {
117 | mBluetoothDevices.add(device);
118 | updateConnectedDevicesStatus();
119 | Log.v(TAG, "Connected to device: " + device.getAddress());
120 | } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
121 | mBluetoothDevices.remove(device);
122 | updateConnectedDevicesStatus();
123 | Log.v(TAG, "Disconnected from device");
124 | }
125 | } else {
126 | mBluetoothDevices.remove(device);
127 | updateConnectedDevicesStatus();
128 | // There are too many gatt errors (some of them not even in the documentation) so we just
129 | // show the error to the user.
130 | final String errorMessage = getString(R.string.status_errorWhenConnecting) + ": " + status;
131 | runOnUiThread(new Runnable() {
132 | @Override
133 | public void run() {
134 | Toast.makeText(Peripheral.this, errorMessage, Toast.LENGTH_LONG).show();
135 | }
136 | });
137 | Log.e(TAG, "Error when connecting: " + status);
138 | }
139 | }
140 |
141 | @Override
142 | public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
143 | BluetoothGattCharacteristic characteristic) {
144 | super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
145 | Log.d(TAG, "Device tried to read characteristic: " + characteristic.getUuid());
146 | Log.d(TAG, "Value: " + Arrays.toString(characteristic.getValue()));
147 | if (offset != 0) {
148 | mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset,
149 | /* value (optional) */ null);
150 | return;
151 | }
152 | mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS,
153 | offset, characteristic.getValue());
154 | }
155 |
156 | @Override
157 | public void onNotificationSent(BluetoothDevice device, int status) {
158 | super.onNotificationSent(device, status);
159 | Log.v(TAG, "Notification sent. Status: " + status);
160 | }
161 |
162 | @Override
163 | public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
164 | BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded,
165 | int offset, byte[] value) {
166 | super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite,
167 | responseNeeded, offset, value);
168 | Log.v(TAG, "Characteristic Write request: " + Arrays.toString(value));
169 | int status = mCurrentServiceFragment.writeCharacteristic(characteristic, offset, value);
170 | if (responseNeeded) {
171 | mGattServer.sendResponse(device, requestId, status,
172 | /* No need to respond with an offset */ 0,
173 | /* No need to respond with a value */ null);
174 | }
175 | }
176 |
177 | @Override
178 | public void onDescriptorReadRequest(BluetoothDevice device, int requestId,
179 | int offset, BluetoothGattDescriptor descriptor) {
180 | super.onDescriptorReadRequest(device, requestId, offset, descriptor);
181 | Log.d(TAG, "Device tried to read descriptor: " + descriptor.getUuid());
182 | Log.d(TAG, "Value: " + Arrays.toString(descriptor.getValue()));
183 | if (offset != 0) {
184 | mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset,
185 | /* value (optional) */ null);
186 | return;
187 | }
188 | mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset,
189 | descriptor.getValue());
190 | }
191 |
192 | @Override
193 | public void onDescriptorWriteRequest(BluetoothDevice device, int requestId,
194 | BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded,
195 | int offset,
196 | byte[] value) {
197 | super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded,
198 | offset, value);
199 | Log.v(TAG, "Descriptor Write Request " + descriptor.getUuid() + " " + Arrays.toString(value));
200 | int status = BluetoothGatt.GATT_SUCCESS;
201 | if (descriptor.getUuid() == CLIENT_CHARACTERISTIC_CONFIGURATION_UUID) {
202 | BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
203 | boolean supportsNotifications = (characteristic.getProperties() &
204 | BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0;
205 | boolean supportsIndications = (characteristic.getProperties() &
206 | BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0;
207 |
208 | if (!(supportsNotifications || supportsIndications)) {
209 | status = BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED;
210 | } else if (value.length != 2) {
211 | status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
212 | } else if (Arrays.equals(value, BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE)) {
213 | status = BluetoothGatt.GATT_SUCCESS;
214 | mCurrentServiceFragment.notificationsDisabled(characteristic);
215 | descriptor.setValue(value);
216 | } else if (supportsNotifications &&
217 | Arrays.equals(value, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) {
218 | status = BluetoothGatt.GATT_SUCCESS;
219 | mCurrentServiceFragment.notificationsEnabled(characteristic, false /* indicate */);
220 | descriptor.setValue(value);
221 | } else if (supportsIndications &&
222 | Arrays.equals(value, BluetoothGattDescriptor.ENABLE_INDICATION_VALUE)) {
223 | status = BluetoothGatt.GATT_SUCCESS;
224 | mCurrentServiceFragment.notificationsEnabled(characteristic, true /* indicate */);
225 | descriptor.setValue(value);
226 | } else {
227 | status = BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED;
228 | }
229 | } else {
230 | status = BluetoothGatt.GATT_SUCCESS;
231 | descriptor.setValue(value);
232 | }
233 | if (responseNeeded) {
234 | mGattServer.sendResponse(device, requestId, status,
235 | /* No need to respond with offset */ 0,
236 | /* No need to respond with a value */ null);
237 | }
238 | }
239 | };
240 |
241 | /////////////////////////////////
242 | ////// Lifecycle Callbacks //////
243 | /////////////////////////////////
244 |
245 | @Override
246 | protected void onCreate(Bundle savedInstanceState) {
247 | super.onCreate(savedInstanceState);
248 | setContentView(R.layout.activity_peripherals);
249 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
250 | mAdvStatus = (TextView) findViewById(R.id.textView_advertisingStatus);
251 | mConnectionStatus = (TextView) findViewById(R.id.textView_connectionStatus);
252 | mBluetoothDevices = new HashSet<>();
253 | mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
254 | mBluetoothAdapter = mBluetoothManager.getAdapter();
255 |
256 | // If we are not being restored from a previous state then create and add the fragment.
257 | if (savedInstanceState == null) {
258 | int peripheralIndex = getIntent().getIntExtra(Peripherals.EXTRA_PERIPHERAL_INDEX,
259 | /* default */ -1);
260 | if (peripheralIndex == 0) {
261 | mCurrentServiceFragment = new BatteryServiceFragment();
262 | } else if (peripheralIndex == 1) {
263 | mCurrentServiceFragment = new HeartRateServiceFragment();
264 | } else if (peripheralIndex == 2) {
265 | mCurrentServiceFragment = new HealthThermometerServiceFragment();
266 | } else {
267 | Log.wtf(TAG, "Service doesn't exist");
268 | }
269 | getFragmentManager()
270 | .beginTransaction()
271 | .add(R.id.fragment_container, mCurrentServiceFragment, CURRENT_FRAGMENT_TAG)
272 | .commit();
273 | } else {
274 | mCurrentServiceFragment = (ServiceFragment) getFragmentManager()
275 | .findFragmentByTag(CURRENT_FRAGMENT_TAG);
276 | }
277 | mBluetoothGattService = mCurrentServiceFragment.getBluetoothGattService();
278 |
279 | mAdvSettings = new AdvertiseSettings.Builder()
280 | .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
281 | .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
282 | .setConnectable(true)
283 | .build();
284 | mAdvData = new AdvertiseData.Builder()
285 | .setIncludeTxPowerLevel(true)
286 | .addServiceUuid(mCurrentServiceFragment.getServiceUUID())
287 | .build();
288 | mAdvScanResponse = new AdvertiseData.Builder()
289 | .setIncludeDeviceName(true)
290 | .build();
291 | }
292 |
293 | @Override
294 | public boolean onCreateOptionsMenu(Menu menu) {
295 | MenuInflater inflater = getMenuInflater();
296 | inflater.inflate(R.menu.menu_peripheral, menu);
297 | return true /* show menu */;
298 | }
299 |
300 | @Override
301 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
302 | super.onActivityResult(requestCode, resultCode, data);
303 | if (requestCode == REQUEST_ENABLE_BT) {
304 | if (resultCode == RESULT_OK) {
305 | if (!mBluetoothAdapter.isMultipleAdvertisementSupported()) {
306 | Toast.makeText(this, R.string.bluetoothAdvertisingNotSupported, Toast.LENGTH_LONG).show();
307 | Log.e(TAG, "Advertising not supported");
308 | }
309 | onStart();
310 | } else {
311 | //TODO(g-ortuno): UX for asking the user to activate bt
312 | Toast.makeText(this, R.string.bluetoothNotEnabled, Toast.LENGTH_LONG).show();
313 | Log.e(TAG, "Bluetooth not enabled");
314 | finish();
315 | }
316 | }
317 | }
318 |
319 |
320 | @Override
321 | protected void onStart() {
322 | super.onStart();
323 | resetStatusViews();
324 | // If the user disabled Bluetooth when the app was in the background,
325 | // openGattServer() will return null.
326 | mGattServer = mBluetoothManager.openGattServer(this, mGattServerCallback);
327 | if (mGattServer == null) {
328 | ensureBleFeaturesAvailable();
329 | return;
330 | }
331 | // Add a service for a total of three services (Generic Attribute and Generic Access
332 | // are present by default).
333 | mGattServer.addService(mBluetoothGattService);
334 |
335 | if (mBluetoothAdapter.isMultipleAdvertisementSupported()) {
336 | mAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
337 | mAdvertiser.startAdvertising(mAdvSettings, mAdvData, mAdvScanResponse, mAdvCallback);
338 | } else {
339 | mAdvStatus.setText(R.string.status_noLeAdv);
340 | }
341 | }
342 |
343 | @Override
344 | public boolean onOptionsItemSelected(MenuItem item) {
345 | if (item.getItemId() == R.id.action_disconnect_devices) {
346 | disconnectFromDevices();
347 | return true /* event_consumed */;
348 | }
349 | return false /* event_consumed */;
350 | }
351 |
352 | @Override
353 | protected void onStop() {
354 | super.onStop();
355 | if (mGattServer != null) {
356 | mGattServer.close();
357 | }
358 | if (mBluetoothAdapter.isEnabled() && mAdvertiser != null) {
359 | // If stopAdvertising() gets called before close() a null
360 | // pointer exception is raised.
361 | mAdvertiser.stopAdvertising(mAdvCallback);
362 | }
363 | resetStatusViews();
364 | }
365 |
366 | @Override
367 | public void sendNotificationToDevices(BluetoothGattCharacteristic characteristic) {
368 | boolean indicate = (characteristic.getProperties()
369 | & BluetoothGattCharacteristic.PROPERTY_INDICATE)
370 | == BluetoothGattCharacteristic.PROPERTY_INDICATE;
371 | for (BluetoothDevice device : mBluetoothDevices) {
372 | // true for indication (acknowledge) and false for notification (unacknowledge).
373 | mGattServer.notifyCharacteristicChanged(device, characteristic, indicate);
374 | }
375 | }
376 |
377 | private void resetStatusViews() {
378 | mAdvStatus.setText(R.string.status_notAdvertising);
379 | updateConnectedDevicesStatus();
380 | }
381 |
382 | private void updateConnectedDevicesStatus() {
383 | final String message = getString(R.string.status_devicesConnected) + " "
384 | + mBluetoothManager.getConnectedDevices(BluetoothGattServer.GATT).size();
385 | runOnUiThread(new Runnable() {
386 | @Override
387 | public void run() {
388 | mConnectionStatus.setText(message);
389 | }
390 | });
391 | }
392 |
393 | ///////////////////////
394 | ////// Bluetooth //////
395 | ///////////////////////
396 | public static BluetoothGattDescriptor getClientCharacteristicConfigurationDescriptor() {
397 | BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
398 | CLIENT_CHARACTERISTIC_CONFIGURATION_UUID,
399 | (BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE));
400 | descriptor.setValue(new byte[]{0, 0});
401 | return descriptor;
402 | }
403 |
404 | public static BluetoothGattDescriptor getCharacteristicUserDescriptionDescriptor(String defaultValue) {
405 | BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
406 | CHARACTERISTIC_USER_DESCRIPTION_UUID,
407 | (BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE));
408 | try {
409 | descriptor.setValue(defaultValue.getBytes("UTF-8"));
410 | } finally {
411 | return descriptor;
412 | }
413 | }
414 |
415 | private void ensureBleFeaturesAvailable() {
416 | if (mBluetoothAdapter == null) {
417 | Toast.makeText(this, R.string.bluetoothNotSupported, Toast.LENGTH_LONG).show();
418 | Log.e(TAG, "Bluetooth not supported");
419 | finish();
420 | } else if (!mBluetoothAdapter.isEnabled()) {
421 | // Make sure bluetooth is enabled.
422 | Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
423 | startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
424 | }
425 | }
426 | private void disconnectFromDevices() {
427 | Log.d(TAG, "Disconnecting devices...");
428 | for (BluetoothDevice device : mBluetoothManager.getConnectedDevices(
429 | BluetoothGattServer.GATT)) {
430 | Log.d(TAG, "Devices: " + device.getAddress() + " " + device.getName());
431 | mGattServer.cancelConnection(device);
432 | }
433 | }
434 | }
435 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/webbluetoothcg/bletestperipheral/Peripherals.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google Inc. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.webbluetoothcg.bletestperipheral;
18 |
19 | import android.app.ListActivity;
20 | import android.content.Intent;
21 | import android.os.Bundle;
22 | import android.view.View;
23 | import android.widget.ArrayAdapter;
24 | import android.widget.ListView;
25 |
26 |
27 | public class Peripherals extends ListActivity {
28 |
29 | private static final String[] PERIPHERALS_NAMES = new String[]{"Battery", "Heart Rate Monitor", "Health Thermometer"};
30 | public final static String EXTRA_PERIPHERAL_INDEX = "PERIPHERAL_INDEX";
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_peripherals_list);
36 | ArrayAdapter adapter = new ArrayAdapter<>(this,
37 | /* layout for the list item */ android.R.layout.simple_list_item_1,
38 | /* id of the TextView to use */ android.R.id.text1,
39 | /* values for the list */ PERIPHERALS_NAMES);
40 | setListAdapter(adapter);
41 | }
42 |
43 | @Override
44 | protected void onListItemClick(ListView l, View v, int position, long id) {
45 | super.onListItemClick(l, v, position, id);
46 |
47 | Intent intent = new Intent(this, Peripheral.class);
48 | intent.putExtra(EXTRA_PERIPHERAL_INDEX, position);
49 | startActivity(intent);
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/webbluetoothcg/bletestperipheral/ServiceFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Google Inc. All rights reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package io.github.webbluetoothcg.bletestperipheral;
18 |
19 | import android.app.Fragment;
20 | import android.bluetooth.BluetoothGattCharacteristic;
21 | import android.bluetooth.BluetoothGattDescriptor;
22 | import android.bluetooth.BluetoothGattService;
23 | import android.os.ParcelUuid;
24 |
25 | public abstract class ServiceFragment extends Fragment{
26 | public abstract BluetoothGattService getBluetoothGattService();
27 | public abstract ParcelUuid getServiceUUID();
28 |
29 | /**
30 | * Function to communicate to the ServiceFragment that a device wants to write to a
31 | * characteristic.
32 | *
33 | * The ServiceFragment should check that the value being written is valid and
34 | * return a code appropriately. The ServiceFragment should update the UI to reflect the change.
35 | * @param characteristic Characteristic to write to
36 | * @param value Value to write to the characteristic
37 | * @return {@link android.bluetooth.BluetoothGatt#GATT_SUCCESS} if the write operation
38 | * was completed successfully. See {@link android.bluetooth.BluetoothGatt} for GATT return codes.
39 | */
40 | public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) {
41 | throw new UnsupportedOperationException("Method writeCharacteristic not overridden");
42 | };
43 |
44 | /**
45 | * Function to notify to the ServiceFragment that a device has disabled notifications on a
46 | * CCC descriptor.
47 | *
48 | * The ServiceFragment should update the UI to reflect the change.
49 | * @param characteristic Characteristic written to
50 | */
51 | public void notificationsDisabled(BluetoothGattCharacteristic characteristic) {
52 | throw new UnsupportedOperationException("Method notificationsDisabled not overridden");
53 | };
54 |
55 | /**
56 | * Function to notify to the ServiceFragment that a device has enabled notifications on a
57 | * CCC descriptor.
58 | *
59 | * The ServiceFragment should update the UI to reflect the change.
60 | * @param characteristic Characteristic written to
61 | * @param indicate Boolean that says if it's indicate or notify.
62 | */
63 | public void notificationsEnabled(BluetoothGattCharacteristic characteristic, boolean indicate) {
64 | throw new UnsupportedOperationException("Method notificationsEnabled not overridden");
65 | };
66 |
67 | /**
68 | * This interface must be implemented by activities that contain a ServiceFragment to allow an
69 | * interaction in the fragment to be communicated to the activity.
70 | */
71 | public interface ServiceFragmentDelegate {
72 | void sendNotificationToDevices(BluetoothGattCharacteristic characteristic);
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/battery_icon.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_peripherals.xml:
--------------------------------------------------------------------------------
1 |
16 |
26 |
34 |
41 |
42 |
51 |
58 |
59 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_peripherals_list.xml:
--------------------------------------------------------------------------------
1 |
16 |
23 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_battery.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
22 |
24 |
31 |
38 |
43 |
48 |
56 |
57 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_health_thermometer.xml:
--------------------------------------------------------------------------------
1 |
16 |
21 |
22 |
29 |
36 |
37 |
45 |
53 |
54 |
61 |
69 |
70 |
71 |
79 |
80 |
81 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_heart_rate.xml:
--------------------------------------------------------------------------------
1 |
16 |
21 |
22 |
29 |
36 |
44 |
52 |
60 |
66 |
75 |
84 |
85 |
92 |
93 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_peripheral.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
20 | 64dp
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/values/body_sensor_location_values.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 | - (0) Other
21 | - (1) Chest
22 | - (2) Wrist
23 | - (3) Finger
24 | - (4) Hand
25 | - (5) Ear Lobe
26 | - (6) Foot
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/color.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 | #009688
21 |
22 | #00796B
23 |
24 | #00B8D4
25 |
26 |
27 | #757575
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | 16dp
19 | 16dp
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 | BLE Peripheral Simulator
18 | Peripherals
19 | Peripheral
20 | Notify
21 |
22 |
23 | BLE Peripheral Simulator closing: Bluetooth Not Supported
24 | BLE Peripheral Simulator closing: Bluetooth is Not Enabled
25 | BLE Peripheral Simulator closing: BLE Advertising Not Supported
26 |
27 |
28 | Advertising Status
29 | Advertising (Keep Screen On)
30 | Not Advertising
31 | Not Advertising. Advertisement is larger than 31 bytes.
32 | Not Advertising. Advertising not supported.
33 | Not Advertising. Internal error occurred.
34 | Not Advertising. No advertising instance is available.
35 |
36 |
37 | Connection Status
38 | Devices Connected:
39 | An error occurred when connecting to a device. Error Code
40 |
41 |
42 | Battery Service
43 | Batter Level shouldn\'t exceed 100
44 | Please enter a number between 0 and 100
45 |
46 |
47 | Body Sensor Location
48 | Heart Rate Service
49 | Heart Rate
50 | Energy Expended
51 | Please enter a number between 0 and 255
52 | Please enter a number between 0 and 65535
53 |
54 |
55 | Health Thermometer Service
56 | Temperature (°C)
57 | Measurement Interval (s)
58 | Please enter a valid float number
59 | Please enter a number between 0 and 65535
60 | Notifications enabled
61 | Notifications not enabled
62 |
63 | LE Advertising is not available. Please pair with a device to be
64 | discoverable.
65 |
66 | Disconnect Devices
67 |
68 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
24 |
25 |
26 |
29 |
30 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | maven { url 'https://maven.google.com' }
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:3.0.0'
10 |
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/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
19 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Nov 07 13:33:09 AEDT 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/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 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/ic_play_store.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/ic_play_store.png
--------------------------------------------------------------------------------
/ic_play_store_wide.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WebBluetoothCG/ble-test-peripheral-android/d6477927e7fe90bb03c18632d52e5846a13bf387/ic_play_store_wide.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/travis/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ./gradlew build --full-stacktrace
3 |
--------------------------------------------------------------------------------