├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── layout
│ │ │ ├── activity_main.xml
│ │ │ ├── keyboard_fragment.xml
│ │ │ ├── d_pad_fragment.xml
│ │ │ ├── configuration_fragment.xml
│ │ │ ├── mouse_fragment.xml
│ │ │ └── consumer_fragment.xml
│ │ ├── drawable
│ │ │ ├── border.xml
│ │ │ ├── ic_stop_black_24dp.xml
│ │ │ ├── ic_eject_black_24dp.xml
│ │ │ ├── ic_skip_next_black_24dp.xml
│ │ │ ├── ic_skip_previous_black_24dp.xml
│ │ │ ├── ic_pause_play_black_24dp.xml
│ │ │ ├── ic_arrow_back_black_24dp.xml
│ │ │ ├── ic_arrow_forward_black_24dp.xml
│ │ │ ├── ic_arrow_upward_black_24dp.xml
│ │ │ ├── ic_arrow_downward_black_24dp.xml
│ │ │ ├── ic_volume_down_black_24dp.xml
│ │ │ ├── ic_hotel_black_24dp.xml
│ │ │ ├── ic_looks_one_black_24dp.xml
│ │ │ ├── ic_looks_4_black_24dp.xml
│ │ │ ├── ic_brightness_3_black_24dp.xml
│ │ │ ├── ic_looks_5_black_24dp.xml
│ │ │ ├── ic_brightness_low_black_24dp.xml
│ │ │ ├── ic_looks_two_black_24dp.xml
│ │ │ ├── ic_volume_up_black_24dp.xml
│ │ │ ├── ic_refresh_black_24dp.xml
│ │ │ ├── ic_power_settings_new_black_24dp.xml
│ │ │ ├── ic_looks_3_black_24dp.xml
│ │ │ ├── ic_brightness_high_black_24dp.xml
│ │ │ ├── ic_usb_black_24dp.xml
│ │ │ ├── ic_photo_camera_black_24dp.xml
│ │ │ └── ic_volume_off_black_24dp.xml
│ │ └── values
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── example
│ │ └── alek
│ │ └── ble_hid_example
│ │ ├── CustomViewPager.java
│ │ ├── UUIDs.java
│ │ ├── ApplicationConfiguration.java
│ │ ├── DPadFragment.java
│ │ ├── ConsumerControlUsage.java
│ │ ├── ConfigurationFragment.java
│ │ ├── KeyboardFragment.java
│ │ ├── ApplicationLaunchButtonsUsage.java
│ │ ├── MouseFragment.java
│ │ ├── ConsumerFragment.java
│ │ ├── ApplicationControlUsage.java
│ │ ├── MainActivity.java
│ │ ├── KeyboardUsage.java
│ │ └── HidBleService.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── screenshots
├── d_pad.png
├── mouse.png
├── consumer.png
├── keyboard.png
└── configuration.png
├── .idea
├── copyright
│ └── profiles_settings.xml
├── modules.xml
├── runConfigurations.xml
├── compiler.xml
└── misc.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── .gitignore
├── README.md
├── gradlew.bat
├── gradlew
└── LICENSE
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/screenshots/d_pad.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aleksander-Drewnicki/BLE_HID_EXAMPLE/HEAD/screenshots/d_pad.png
--------------------------------------------------------------------------------
/screenshots/mouse.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aleksander-Drewnicki/BLE_HID_EXAMPLE/HEAD/screenshots/mouse.png
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/screenshots/consumer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aleksander-Drewnicki/BLE_HID_EXAMPLE/HEAD/screenshots/consumer.png
--------------------------------------------------------------------------------
/screenshots/keyboard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aleksander-Drewnicki/BLE_HID_EXAMPLE/HEAD/screenshots/keyboard.png
--------------------------------------------------------------------------------
/screenshots/configuration.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aleksander-Drewnicki/BLE_HID_EXAMPLE/HEAD/screenshots/configuration.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aleksander-Drewnicki/BLE_HID_EXAMPLE/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/border.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
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-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_stop_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_eject_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 | #101010
7 | #888888
8 | #FFFFFF
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_skip_next_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_skip_previous_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_pause_play_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_back_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_forward_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_upward_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_downward_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_volume_down_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_hotel_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_looks_one_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_looks_4_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_brightness_3_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_looks_5_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4dp
4 | 16dp
5 |
6 | 16dp
7 | 24dp
8 |
9 |
10 | 24sp
11 | 32sp
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_brightness_low_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_looks_two_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_volume_up_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_refresh_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_power_settings_new_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_looks_3_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_brightness_high_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_usb_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_photo_camera_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
12 |
13 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/alek/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/main/res/drawable/ic_volume_off_black_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/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 |
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
14 |
15 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | applicationId "com.example.alek.hid2"
8 | minSdkVersion 21
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 |
21 | void
22 | }
23 |
24 | dependencies {
25 | compile fileTree(dir: 'libs', include: ['*.jar'])
26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
27 | exclude group: 'com.android.support', module: 'support-annotations'
28 | })
29 | compile 'com.android.support:appcompat-v7:25.2.0'
30 | testCompile 'junit:junit:4.12'
31 | }
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # Keystore files
46 | # Uncomment the following line if you do not want to check your keystore files in.
47 | #*.jks
48 |
49 | # External native build folder generated in Android Studio 2.2 and later
50 | .externalNativeBuild
51 |
52 | # Google Services (e.g. APIs or Firebase)
53 | google-services.json
54 |
55 | # Freeline
56 | freeline.py
57 | freeline/
58 | freeline_project_description.json
59 |
60 | # fastlane
61 | fastlane/report.xml
62 | fastlane/Preview.html
63 | fastlane/screenshots
64 | fastlane/test_output
65 | fastlane/readme.md
66 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/CustomViewPager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.content.Context;
19 | import android.support.v4.view.ViewPager;
20 | import android.util.AttributeSet;
21 | import android.view.MotionEvent;
22 |
23 | public class CustomViewPager extends ViewPager {
24 | private boolean swipeEnable = true;
25 |
26 | public CustomViewPager(Context context) {
27 | super(context);
28 | }
29 |
30 | public CustomViewPager(Context context, AttributeSet attrs) {
31 | super(context, attrs);
32 | }
33 |
34 | public void swipePossible(boolean enable) {
35 | swipeEnable = enable;
36 | }
37 |
38 | @Override
39 | public boolean onInterceptTouchEvent(MotionEvent ev) {
40 | return swipeEnable && super.onInterceptTouchEvent(ev);
41 | }
42 |
43 | @Override
44 | public boolean onTouchEvent(MotionEvent ev) {
45 | return swipeEnable && super.onTouchEvent(ev);
46 | }
47 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/UUIDs.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | final class UUIDs {
19 | // HID related UUIDs
20 | public static final String SERVICE_HID = "00001812-0000-1000-8000-00805F9B34FB";
21 | public static final String CHAR_REPORT = "00002A4D-0000-1000-8000-00805F9B34FB";
22 | public static final String CHAR_REPORT_MAP = "00002A4B-0000-1000-8000-00805F9B34FB";
23 | public static final String CHAR_HID_INFORMATION = "00002A4A-0000-1000-8000-00805F9B34FB";
24 | public static final String CHAR_HID_CONTROL_POINT = "00002A4C-0000-1000-8000-00805F9B34FB";
25 | public static final String DESC_REPORT_REFERENCE = "00002908-0000-1000-8000-00805F9B34FB";
26 | public static final String DESC_CCC = "00002902-0000-1000-8000-00805F9B34FB";
27 |
28 | // DIS related UUIDs
29 | public static final String SERVICE_DIS = "0000180A-0000-1000-8000-00805F9B34FB";
30 | public static final String CHAR_PNP_ID = "00002A50-0000-1000-8000-00805F9B34FB";
31 |
32 | // BAS related UUIDs
33 | public static final String SERVICE_BAS = "0000180F-0000-1000-8000-00805F9B34FB";
34 | public static final String CHAR_BATTERY_LEVEL = "00002A19-0000-1000-8000-00805F9B34FB";
35 |
36 | private UUIDs() {
37 | }
38 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BLE_HID_EXAMPLE
3 | Saved_Force_Bond
4 | Saved_Enable_Consumer
5 | Saved_Enable_Mouse
6 | Saved_Enable_Keyboard
7 | Saved_Basic_Mode
8 | BLE_HID_EXAMPLE_prefs
9 | Configuration
10 | D-Pad
11 | Mouse
12 | Consumer control
13 | Force pairing
14 | Enter text
15 | Music/Player control
16 | Basic mode
17 | Send text
18 | Send Single Character
19 | Consumer
20 | Keyboard On
21 | Keyboard Off
22 | Reboot application
23 | Device not connected
24 | Volume control
25 | List of connected devices
26 | Keyboard
27 | Brightness control
28 | Miscellaneous
29 | System Control
30 | Application Launch
31 | Application Control
32 |
33 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BLE_HID_EXAMPLE
2 | Example of HID over GATT (Bluetooth Low Energy) Android Application. Application emulates the peripheral, server BLE device like mouse or keyboard, which could be connected by some central device like PC or smartphone.
3 | It is working in 2 modes: basic - which could be handled by various operating systems and advanced - which communicates with Linux based and Android operating systems only.
4 | Application is made of 2 (basic mode) or 5 (advance mode) full screen fragments.
5 | When more than one device is connected to the application then the same notifications are sent to the all devices.
6 |
7 | ## Configuration fragment
8 | 
9 |
10 | - Force pairing switch - if enabled the device tries to start pairing with remote device, usable when the central doesn't start the pairing.
11 | - Basic mode switch - if enabled only consumer control feature is supported by application, otherwise consumer control, mouse, keyboard and the D-Pad
12 | - Reboot application button - it is recommended to reboot the application after switching the mode
13 | - List of currently connected devices - device name and its address is shown
14 |
15 | ## Consumer control fragment
16 | 
17 |
18 | - Music/player control buttons - previous track, stop playing, play/pause, next track
19 | - Volume control buttons - decrease volume, mute, increase volume
20 | - Brightness control buttons - decrease brightness, increase brightness
21 | - Miscellaneous buttons - eject (e.g. CD/DVD), take a snapshot
22 | - System control buttons (advance mode only) - perform: hibernation, sleep. shut down, restart
23 | - Application launch spinner (advance mode only) - start selected application e.g. calculator or WEB browser
24 | - Application control spinner (advance mode only) - perform selected action on currently focused application e.g. show help
25 |
26 | ## Mouse fragment (advance mode only)
27 | 
28 |
29 | - Buttons (1, 2, 3, 4, 5) - emulates mouse's buttons click
30 | - Touchpad area - move cursor, double click emulates a click by first (left) mouse button
31 | - Device's volume up and volume down button - emulates the scroll wheel
32 |
33 | ## Keyboard fragment (advance mode only)
34 | 
35 |
36 | - Send phrase text view & 'send text button' - written text will be sent after clicking the button
37 | - Send single character spinner - selected character will be sent
38 | - Keyboard On/Off button - enables/disables the software keyboard, on each click selected character will be sent immediately
39 |
40 | ## D-Pad fragment (advance mode only)
41 | 
42 |
43 | - Arrow button - send up/down/left/right arrow character
44 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/ApplicationConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.content.Context;
19 | import android.content.SharedPreferences;
20 |
21 | class ApplicationConfiguration {
22 | final static public int FORCE_BOND_FEAT = 0x01;
23 | final static public int CONSUMER_FEAT = 0x02;
24 | final static public int MOUSE_FEAT = 0x03;
25 | final static public int KEYBOARD_FEAT = 0x04;
26 | final static public int BASIC_FEAT = 0x05;
27 | private final static int TRUE = 1;
28 | private final static int FALSE = 0;
29 | final static private int[][] FEAT_ID_ARRAY = {
30 | /* ID, string ID, default value */
31 | {FORCE_BOND_FEAT, R.string.saved_force_bond, FALSE},
32 | {CONSUMER_FEAT, R.string.saved_enable_consumer, TRUE},
33 | {MOUSE_FEAT, R.string.saved_enable_mouse, FALSE},
34 | {KEYBOARD_FEAT, R.string.saved_enable_keyboard, FALSE},
35 | {BASIC_FEAT, R.string.saved_basic_mode, TRUE},
36 | };
37 |
38 | static void initializeConfiguration(Context context) {
39 | // Get values if exist - set them otherwise, all are true by defaults
40 | SharedPreferences sharedPref = context.getSharedPreferences(
41 | context.getString(R.string.app_name_prefs), Context.MODE_PRIVATE);
42 | SharedPreferences.Editor editor = sharedPref.edit();
43 |
44 | for (int[] elem : FEAT_ID_ARRAY) {
45 | int id = elem[1];
46 | int def_val = elem[2];
47 |
48 | if (!sharedPref.contains(context.getString(id))) {
49 | editor.putInt(context.getString(id), def_val);
50 | }
51 | }
52 |
53 | editor.apply();
54 | }
55 |
56 | static void setConfigurationField(Context context, int feature, boolean value) {
57 | SharedPreferences sharedPref = context.getSharedPreferences(
58 | context.getString(R.string.app_name_prefs), Context.MODE_PRIVATE);
59 | SharedPreferences.Editor editor = sharedPref.edit();
60 |
61 | for (int[] pair : FEAT_ID_ARRAY) {
62 | int feat = pair[0];
63 | int id = pair[1];
64 |
65 | if (feat == feature) {
66 | editor.putInt(context.getString(id), value ? TRUE : FALSE);
67 | editor.apply();
68 | return;
69 | }
70 | }
71 | }
72 |
73 | static boolean getConfigurationField(Context context, int feature) {
74 | SharedPreferences sharedPref = context.getSharedPreferences(
75 | context.getString(R.string.app_name_prefs), Context.MODE_PRIVATE);
76 |
77 | for (int[] pair : FEAT_ID_ARRAY) {
78 | int feat = pair[0];
79 | int id = pair[1];
80 |
81 | if (feat == feature) {
82 | return (sharedPref.contains(context.getString(id))) &&
83 | (sharedPref.getInt(context.getString(id), FALSE) == TRUE);
84 | }
85 | }
86 |
87 | return false;
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/DPadFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.os.Bundle;
19 | import android.support.annotation.Nullable;
20 | import android.support.v4.app.Fragment;
21 | import android.view.LayoutInflater;
22 | import android.view.MotionEvent;
23 | import android.view.View;
24 | import android.view.ViewGroup;
25 | import android.view.ViewTreeObserver;
26 |
27 | public class DPadFragment extends Fragment implements View.OnTouchListener {
28 |
29 | public static DPadFragment newInstance() {
30 | return new DPadFragment();
31 | }
32 |
33 | @Override
34 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
35 | return inflater.inflate(R.layout.d_pad_fragment, container, false);
36 | }
37 |
38 | @Override
39 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
40 | final View final_view = view;
41 | ViewTreeObserver observer = final_view.getViewTreeObserver();
42 |
43 | getActivity().findViewById(R.id.d_pad_up).setOnTouchListener(this);
44 | getActivity().findViewById(R.id.d_pad_left).setOnTouchListener(this);
45 | getActivity().findViewById(R.id.d_pad_right).setOnTouchListener(this);
46 | getActivity().findViewById(R.id.d_pad_down).setOnTouchListener(this);
47 |
48 | observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
49 | @Override
50 | public void onGlobalLayout() {
51 | int ids[] = {R.id.d_pad_up, R.id.d_pad_left, R.id.d_pad_right, R.id.d_pad_down};
52 |
53 | for (int id : ids) {
54 | View v = getActivity().findViewById(id);
55 | v.setMinimumHeight(v.getWidth());
56 | }
57 | final_view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
58 | }
59 | });
60 | }
61 |
62 | @Override
63 | public boolean onTouch(View v, MotionEvent event) {
64 | MainActivity activity = (MainActivity) getActivity();
65 | byte toSend = 0;
66 | byte value;
67 |
68 | switch (v.getId()) {
69 | /* D-Pad keys */
70 | case R.id.d_pad_up:
71 | value = KeyboardUsage.getUsage("Up");
72 | break;
73 | case R.id.d_pad_left:
74 | value = KeyboardUsage.getUsage("Left");
75 | break;
76 | case R.id.d_pad_right:
77 | value = KeyboardUsage.getUsage("Right");
78 | break;
79 | case R.id.d_pad_down:
80 | value = KeyboardUsage.getUsage("Down");
81 | break;
82 | default:
83 | return false;
84 | }
85 |
86 | if (event.getAction() == MotionEvent.ACTION_DOWN) {
87 | toSend |= value;
88 | } else if (event.getAction() == MotionEvent.ACTION_UP) {
89 | toSend = 0;
90 | } else {
91 | return false;
92 | }
93 |
94 | activity.sendNotification(ReportField.REPORT_FIELD_KEYBOARD_KEYS, toSend);
95 |
96 | return true;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/keyboard_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
19 |
20 |
28 |
29 |
37 |
38 |
47 |
48 |
53 |
54 |
60 |
61 |
67 |
68 |
75 |
76 |
77 |
78 |
87 |
88 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/ConsumerControlUsage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | public class ConsumerControlUsage {
19 | public static final String BRIGHT_UP = "Bright Up";
20 | public static final String BRIGHT_DOWN = "Bright Down";
21 | public static final String SCAN_NEXT_TRACK = "Scan Next Track";
22 | public static final String SCAN_PREVIOUS_TRACK = "Scan Previous Track";
23 | public static final String STOP = "Stop";
24 | public static final String PLAY_PAUSE = "Play/Pause";
25 | public static final String MUTE = "Mute";
26 | public static final String VOLUME_UP = "Volume UP";
27 | public static final String VOLUME_DOWN = "Volume Down";
28 | public static final String EJECT = "Eject";
29 | public static final String SNAPSHOT = "Snapshot";
30 | public static final String SYSTEM_SLEEP = "System Sleep";
31 | public static final String SYSTEM_HIBERNATE = "System Hibernate";
32 | public static final String SYSTEM_POWER_DOWN = "System Power Down";
33 | public static final String SYSTEM_COLD_RESTART = "System Cold Restart";
34 | public static final String SYSTEM_WARM_RESTART = "System Warm Restart";
35 |
36 | public static final ConsumerControlUsage[] AC_USAGES = {
37 | /* Consumer Control Page */
38 | new ConsumerControlUsage(0x0001, BRIGHT_UP),
39 | new ConsumerControlUsage(0x0002, BRIGHT_DOWN),
40 | new ConsumerControlUsage(0x0004, SCAN_NEXT_TRACK),
41 | new ConsumerControlUsage(0x0008, SCAN_PREVIOUS_TRACK),
42 | new ConsumerControlUsage(0x0010, STOP),
43 | new ConsumerControlUsage(0x0020, PLAY_PAUSE),
44 | new ConsumerControlUsage(0x0040, MUTE),
45 | new ConsumerControlUsage(0x0080, VOLUME_UP),
46 | new ConsumerControlUsage(0x0100, VOLUME_DOWN),
47 | new ConsumerControlUsage(0x0200, EJECT),
48 | new ConsumerControlUsage(0x0400, SNAPSHOT),
49 |
50 | /* Generic Desktop Page */
51 | new ConsumerControlUsage(0x0800, SYSTEM_SLEEP),
52 | new ConsumerControlUsage(0x1000, SYSTEM_HIBERNATE),
53 | new ConsumerControlUsage(0x2000, SYSTEM_POWER_DOWN),
54 | new ConsumerControlUsage(0x4000, SYSTEM_COLD_RESTART),
55 | new ConsumerControlUsage(0x8000, SYSTEM_WARM_RESTART),
56 | };
57 | public final short usage;
58 | public final String name;
59 | public int button_id;
60 |
61 | public ConsumerControlUsage(int b_id, int u, String n) {
62 | button_id = b_id;
63 | usage = (short) u;
64 | name = n;
65 | }
66 |
67 | public ConsumerControlUsage(int u, String n) {
68 | this(-1, u, n);
69 | }
70 |
71 | static short getUsage(int b_id) {
72 | for (ConsumerControlUsage AC_USAGE : AC_USAGES) {
73 | if (b_id == AC_USAGE.button_id) {
74 | return AC_USAGE.usage;
75 | }
76 | }
77 |
78 | return 0;
79 | }
80 |
81 | static public void bindButtonId(int id, String name) {
82 | for (ConsumerControlUsage AC_USAGE : AC_USAGES) {
83 | if (AC_USAGE.name.equals(name)) {
84 | AC_USAGE.button_id = id;
85 | return;
86 | }
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/d_pad_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
23 |
24 |
32 |
33 |
40 |
41 |
51 |
52 |
62 |
63 |
73 |
74 |
84 |
85 |
86 |
87 |
88 |
97 |
98 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/configuration_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
17 |
18 |
26 |
27 |
33 |
34 |
41 |
42 |
47 |
48 |
49 |
55 |
56 |
63 |
64 |
69 |
70 |
71 |
79 |
80 |
85 |
86 |
93 |
94 |
97 |
98 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/mouse_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
23 |
24 |
32 |
33 |
37 |
38 |
45 |
46 |
53 |
54 |
55 |
59 |
60 |
67 |
68 |
75 |
76 |
83 |
84 |
85 |
91 |
92 |
93 |
94 |
103 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/ConfigurationFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.content.Intent;
19 | import android.os.Bundle;
20 | import android.support.v4.app.Fragment;
21 | import android.support.v4.content.IntentCompat;
22 | import android.view.LayoutInflater;
23 | import android.view.View;
24 | import android.view.ViewGroup;
25 | import android.widget.CompoundButton;
26 | import android.widget.Switch;
27 | import android.widget.TextView;
28 |
29 | public class ConfigurationFragment extends Fragment implements
30 | CompoundButton.OnCheckedChangeListener, View.OnClickListener {
31 | private static final String BASIC_STRING_ENABLED = "Consumer";
32 | private static final String BASIC_STRING_DISABLED = BASIC_STRING_ENABLED +
33 | " + Mouse\nKeyboard + D-Pad";
34 |
35 | public static ConfigurationFragment newInstance() {
36 | return new ConfigurationFragment();
37 | }
38 |
39 | @Override
40 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
41 | return inflater.inflate(R.layout.configuration_fragment, container, false);
42 | }
43 |
44 | @Override
45 | public void onViewCreated(View view, Bundle savedInstanceState) {
46 | super.onViewCreated(view, savedInstanceState);
47 | int[][] ids = {
48 | {R.id.conf_pair_switch, ApplicationConfiguration.FORCE_BOND_FEAT},
49 | {R.id.conf_basic_switch, ApplicationConfiguration.BASIC_FEAT},
50 | };
51 |
52 | for (int[] pair : ids) {
53 | Switch sw = (Switch) getActivity().findViewById(pair[0]);
54 |
55 | if (sw == null) {
56 | continue;
57 | }
58 |
59 | sw.setChecked(ApplicationConfiguration.getConfigurationField(getContext(), pair[1]));
60 | sw.setOnCheckedChangeListener(this);
61 | }
62 |
63 | ((TextView) getActivity().findViewById(R.id.conf_feat_text)).setText(((Switch)
64 | getActivity().findViewById(R.id.conf_basic_switch)).isChecked() ?
65 | BASIC_STRING_ENABLED : BASIC_STRING_DISABLED);
66 |
67 | getActivity().findViewById(R.id.conf_reboot_button).setOnClickListener(this);
68 | }
69 |
70 | @Override
71 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
72 | MainActivity mainActivity = (MainActivity) getActivity();
73 |
74 | switch (buttonView.getId()) {
75 | case R.id.conf_pair_switch:
76 | ApplicationConfiguration.setConfigurationField(getContext(),
77 | ApplicationConfiguration.FORCE_BOND_FEAT, isChecked);
78 | break;
79 | case R.id.conf_basic_switch:
80 | ApplicationConfiguration.setConfigurationField(getContext(),
81 | ApplicationConfiguration.BASIC_FEAT, isChecked);
82 |
83 | ApplicationConfiguration.setConfigurationField(getContext(),
84 | ApplicationConfiguration.CONSUMER_FEAT, true);
85 |
86 | ApplicationConfiguration.setConfigurationField(getContext(),
87 | ApplicationConfiguration.MOUSE_FEAT, !isChecked);
88 |
89 | ApplicationConfiguration.setConfigurationField(getContext(),
90 | ApplicationConfiguration.KEYBOARD_FEAT, !isChecked);
91 |
92 | ((TextView) getActivity().findViewById(R.id.conf_feat_text)).setText(isChecked ?
93 | BASIC_STRING_ENABLED : BASIC_STRING_DISABLED);
94 | break;
95 | default:
96 | return;
97 | }
98 |
99 | mainActivity.pager.getAdapter().notifyDataSetChanged();
100 | mainActivity.pager.setAdapter(mainActivity.pagerAdapter);
101 | }
102 |
103 | @Override
104 | public void onClick(View v) {
105 | if (v.getId() == R.id.conf_reboot_button) {
106 | Intent i = getActivity().getBaseContext().getPackageManager()
107 | .getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName());
108 |
109 | i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
110 | ((MainActivity) getActivity()).restartGattDatabase();
111 | startActivity(i);
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/KeyboardFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.content.Context;
19 | import android.graphics.Color;
20 | import android.os.Bundle;
21 | import android.support.annotation.Nullable;
22 | import android.support.v4.app.Fragment;
23 | import android.view.LayoutInflater;
24 | import android.view.MotionEvent;
25 | import android.view.View;
26 | import android.view.ViewGroup;
27 | import android.view.inputmethod.InputMethodManager;
28 | import android.widget.AdapterView;
29 | import android.widget.ArrayAdapter;
30 | import android.widget.Button;
31 | import android.widget.CompoundButton;
32 | import android.widget.EditText;
33 | import android.widget.Spinner;
34 | import android.widget.TextView;
35 | import android.widget.ToggleButton;
36 |
37 | import java.util.Objects;
38 |
39 | public class KeyboardFragment extends Fragment implements Button.OnTouchListener,
40 | AdapterView.OnItemSelectedListener, View.OnClickListener {
41 |
42 | public static KeyboardFragment newInstance() {
43 | return new KeyboardFragment();
44 | }
45 |
46 | @Override
47 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
48 | return inflater.inflate(R.layout.keyboard_fragment, container, false);
49 | }
50 |
51 | @Override
52 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
53 | getActivity().findViewById(R.id.keyboard_button_send).setOnClickListener(this);
54 |
55 | // Keyboard character spinner configuration
56 | Spinner spinner_kb = (Spinner) getActivity().findViewById(R.id.keyboard_spinner_character);
57 | spinner_kb.setOnItemSelectedListener(this);
58 | ArrayAdapter dataAdapter_kb = new ArrayAdapter<>(getContext(),
59 | android.R.layout.simple_spinner_item, KeyboardUsage.getUsageNames());
60 | dataAdapter_kb.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
61 | spinner_kb.setAdapter(dataAdapter_kb);
62 |
63 | ((ToggleButton) getActivity().findViewById(R.id.keyboard_toggle_kb)).setOnCheckedChangeListener(
64 | new CompoundButton.OnCheckedChangeListener() {
65 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
66 | InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
67 | Context.INPUT_METHOD_SERVICE);
68 | if (!isChecked) {
69 | getActivity().findViewById(R.id.keyboard_sub_main_layout).requestFocus();
70 | imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
71 | } else {
72 | getActivity().findViewById(R.id.keyboard_sub_main_layout).requestFocus();
73 | imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
74 | }
75 | }
76 | });
77 | }
78 |
79 | @Override
80 | public void onPause() {
81 | super.onPause();
82 |
83 | ((ToggleButton) getActivity().findViewById(R.id.keyboard_toggle_kb)).setChecked(false);
84 | }
85 |
86 | @Override
87 | public boolean onTouch(View v, MotionEvent event) {
88 | short toSend = 0;
89 | int value = ConsumerControlUsage.getUsage(v.getId());
90 | MainActivity activity = (MainActivity) getActivity();
91 |
92 | if (value == 0) {
93 | return false;
94 | }
95 |
96 | if (event.getAction() == MotionEvent.ACTION_DOWN) {
97 | toSend |= value;
98 | } else if (event.getAction() == MotionEvent.ACTION_UP) {
99 | toSend &= ~value;
100 | toSend &= 0xffff;
101 | } else {
102 | return false;
103 | }
104 |
105 | activity.sendNotification(ReportField.REPORT_FIELD_CONSUMER_CONTROL, toSend);
106 |
107 | return true;
108 | }
109 |
110 | @Override
111 | public void onItemSelected(AdapterView> parent, View view, int position, long id) {
112 | MainActivity activity = (MainActivity) getActivity();
113 | short value = 0;
114 |
115 | if (parent.getChildAt(0) != null) {
116 | ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
117 |
118 | if (parent.getId() == R.id.keyboard_spinner_character) {
119 | for (int i = 0; i < KeyboardUsage.KEYBOARD_USAGES.length; i++) {
120 | if (Objects.equals(parent.getItemAtPosition(position).toString(),
121 | KeyboardUsage.KEYBOARD_USAGES[i].description)) {
122 | value = KeyboardUsage.KEYBOARD_USAGES[i].meta;
123 | value += (short) (KeyboardUsage.KEYBOARD_USAGES[i].usage << 8);
124 | break;
125 | }
126 | }
127 |
128 | activity.sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, (int) value);
129 | activity.sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, 0);
130 | }
131 | }
132 | }
133 |
134 | @Override
135 | public void onNothingSelected(AdapterView> parent) {
136 | ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
137 | }
138 |
139 | @Override
140 | public void onClick(View v) {
141 | MainActivity activity = (MainActivity) getActivity();
142 |
143 | switch (v.getId()) {
144 | case R.id.keyboard_button_send:
145 | activity.sendNotification(((EditText) getActivity().findViewById(
146 | R.id.keyboard_edit_text)).getText().toString());
147 | }
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/ApplicationLaunchButtonsUsage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | public class ApplicationLaunchButtonsUsage {
22 | public static final ApplicationLaunchButtonsUsage[] AL_USAGES = {
23 | new ApplicationLaunchButtonsUsage(0x0181, "Configuration Tool"),
24 | new ApplicationLaunchButtonsUsage(0x0182, "Programmable Button Configuration "),
25 | new ApplicationLaunchButtonsUsage(0x0183, "Consumer Control Configuration"),
26 | new ApplicationLaunchButtonsUsage(0x0184, "Word Processor"),
27 | new ApplicationLaunchButtonsUsage(0x0185, "Text Editor"),
28 | new ApplicationLaunchButtonsUsage(0x0186, "Spreadsheet"),
29 | new ApplicationLaunchButtonsUsage(0x0187, "Graphics Editor"),
30 | new ApplicationLaunchButtonsUsage(0x0188, "Presentation App"),
31 | new ApplicationLaunchButtonsUsage(0x0189, "Database App "),
32 | new ApplicationLaunchButtonsUsage(0x018A, "Email Reader"),
33 | new ApplicationLaunchButtonsUsage(0x018B, "Newsreader"),
34 | new ApplicationLaunchButtonsUsage(0x018C, "Voicemail"),
35 | new ApplicationLaunchButtonsUsage(0x018D, "Contacts/Address Book"),
36 | new ApplicationLaunchButtonsUsage(0x018E, "Calendar/Schedule "),
37 | new ApplicationLaunchButtonsUsage(0x018F, "Task/Project Manager"),
38 | new ApplicationLaunchButtonsUsage(0x0190, "Log/Journal/Timecard"),
39 | new ApplicationLaunchButtonsUsage(0x0191, "Checkbook/Finance"),
40 | new ApplicationLaunchButtonsUsage(0x0192, "Calculator"),
41 | new ApplicationLaunchButtonsUsage(0x0193, "A/V Capture/Playback"),
42 | new ApplicationLaunchButtonsUsage(0x0194, "Local Machine Browser"),
43 | new ApplicationLaunchButtonsUsage(0x0195, "LAN/WAN Browser"),
44 | new ApplicationLaunchButtonsUsage(0x0196, "Internet Browser"),
45 | new ApplicationLaunchButtonsUsage(0x0197, "Remote Networking/ISP Connect "),
46 | new ApplicationLaunchButtonsUsage(0x0198, "Network Conference"),
47 | new ApplicationLaunchButtonsUsage(0x0199, "Network Chat"),
48 | new ApplicationLaunchButtonsUsage(0x019A, "Telephony/Dialer"),
49 | new ApplicationLaunchButtonsUsage(0x019B, "Logon"),
50 | new ApplicationLaunchButtonsUsage(0x019C, "Logoff"),
51 | new ApplicationLaunchButtonsUsage(0x019D, "Logon/Logoff"),
52 | new ApplicationLaunchButtonsUsage(0x019E, "Terminal Lock/Screensaver"),
53 | new ApplicationLaunchButtonsUsage(0x019F, "Control Panel"),
54 | new ApplicationLaunchButtonsUsage(0x01A0, "Command Line Processor/Run"),
55 | new ApplicationLaunchButtonsUsage(0x01A1, "Process/Task Manager"),
56 | new ApplicationLaunchButtonsUsage(0x01A2, "Select Task/Application"),
57 | new ApplicationLaunchButtonsUsage(0x01A3, "Next Task/Application"),
58 | new ApplicationLaunchButtonsUsage(0x01A4, "Previous Task/Application"),
59 | new ApplicationLaunchButtonsUsage(0x01A5, "Preemptive Halt Task/Application"),
60 | new ApplicationLaunchButtonsUsage(0x01A6, "Integrated Help Center"),
61 | new ApplicationLaunchButtonsUsage(0x01A7, "Documents"),
62 | new ApplicationLaunchButtonsUsage(0x01A8, "Thesaurus"),
63 | new ApplicationLaunchButtonsUsage(0x01A9, "Dictionary"),
64 | new ApplicationLaunchButtonsUsage(0x01AA, "Desktop"),
65 | new ApplicationLaunchButtonsUsage(0x01AB, "Spell Check"),
66 | new ApplicationLaunchButtonsUsage(0x01AC, "Grammar Check"),
67 | new ApplicationLaunchButtonsUsage(0x01AD, "Wireless Status"),
68 | new ApplicationLaunchButtonsUsage(0x01AE, "Keyboard Layout"),
69 | new ApplicationLaunchButtonsUsage(0x01AF, "Virus Protection"),
70 | new ApplicationLaunchButtonsUsage(0x01B0, "Encryption"),
71 | new ApplicationLaunchButtonsUsage(0x01B1, "Screen Saver"),
72 | new ApplicationLaunchButtonsUsage(0x01B2, "Alarms"),
73 | new ApplicationLaunchButtonsUsage(0x01B3, "Clock"),
74 | new ApplicationLaunchButtonsUsage(0x01B4, "File Browser"),
75 | new ApplicationLaunchButtonsUsage(0x01B5, "Power Status"),
76 | new ApplicationLaunchButtonsUsage(0x01B6, "Image Browser"),
77 | new ApplicationLaunchButtonsUsage(0x01B7, "Audio Browser"),
78 | new ApplicationLaunchButtonsUsage(0x01B8, "Movie Browser"),
79 | new ApplicationLaunchButtonsUsage(0x01B9, "Digital Rights Manager"),
80 | new ApplicationLaunchButtonsUsage(0x01BA, "Digital Wallet"),
81 | // new ApplicationLaunchButtonsUsage(0x01BB, "Reserved"),
82 | new ApplicationLaunchButtonsUsage(0x01BC, "Instant Messaging"),
83 | new ApplicationLaunchButtonsUsage(0x01BD, "OEM Features/ Tips/Tutorial Browser"),
84 | new ApplicationLaunchButtonsUsage(0x01BE, "OEM Help"),
85 | new ApplicationLaunchButtonsUsage(0x01BF, "Online Community"),
86 | new ApplicationLaunchButtonsUsage(0x01C0, "Entertainment Content Browser "),
87 | new ApplicationLaunchButtonsUsage(0x01C1, "Online Shopping Browser"),
88 | new ApplicationLaunchButtonsUsage(0x01C2, "SmartCard Information/Help"),
89 | new ApplicationLaunchButtonsUsage(0x01C3, "Market Monitor/Finance Browser"),
90 | new ApplicationLaunchButtonsUsage(0x01C4, "Customized Corporate News Browser"),
91 | new ApplicationLaunchButtonsUsage(0x01C5, "Online Activity Browser"),
92 | new ApplicationLaunchButtonsUsage(0x01C6, "Research/Search Browser"),
93 | new ApplicationLaunchButtonsUsage(0x01C7, "Audio Player"),
94 | };
95 | public final short usage;
96 | private final String name;
97 |
98 | private ApplicationLaunchButtonsUsage(int u, String n) {
99 | usage = (short) u;
100 | name = n;
101 | }
102 |
103 | static public List getUsageNames() {
104 | List l = new ArrayList<>();
105 |
106 | for (ApplicationLaunchButtonsUsage AL_USAGE : AL_USAGES) {
107 | l.add(AL_USAGE.name);
108 | }
109 |
110 | return l;
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/MouseFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.os.Bundle;
19 | import android.support.annotation.Nullable;
20 | import android.support.v4.app.Fragment;
21 | import android.support.v4.view.VelocityTrackerCompat;
22 | import android.view.GestureDetector;
23 | import android.view.LayoutInflater;
24 | import android.view.MotionEvent;
25 | import android.view.VelocityTracker;
26 | import android.view.View;
27 | import android.view.ViewGroup;
28 | import android.view.ViewTreeObserver;
29 |
30 | public class MouseFragment extends Fragment implements View.OnTouchListener {
31 | private int i = 0;
32 | private float x = 0.0f;
33 | private float y = 0.0f;
34 |
35 | public static MouseFragment newInstance() {
36 | return new MouseFragment();
37 | }
38 |
39 | @Override
40 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
41 | return inflater.inflate(R.layout.mouse_fragment, container, false);
42 | }
43 |
44 | @Override
45 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
46 | final View final_view = view;
47 | ViewTreeObserver observer = final_view.getViewTreeObserver();
48 |
49 | observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
50 | @Override
51 | public void onGlobalLayout() {
52 | View mc = getActivity().findViewById(R.id.mouse_mouse_cursor);
53 |
54 | if (mc != null) {
55 | mc.setMinimumHeight(mc.getWidth());
56 | }
57 |
58 | final_view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
59 | }
60 | });
61 |
62 | getActivity().findViewById(R.id.mouse_button_mouse_1).setOnTouchListener(this);
63 | getActivity().findViewById(R.id.mouse_button_mouse_2).setOnTouchListener(this);
64 | getActivity().findViewById(R.id.mouse_button_mouse_3).setOnTouchListener(this);
65 | getActivity().findViewById(R.id.mouse_button_mouse_4).setOnTouchListener(this);
66 | getActivity().findViewById(R.id.mouse_button_mouse_5).setOnTouchListener(this);
67 |
68 | getActivity().findViewById(R.id.mouse_mouse_cursor).setOnTouchListener(new View.OnTouchListener() {
69 | final MainActivity activity = (MainActivity) getActivity();
70 | private final GestureDetector gestureDetector = new GestureDetector(getContext(),
71 | new GestureDetector.SimpleOnGestureListener() {
72 | @Override
73 | public boolean onDoubleTap(MotionEvent e) {
74 | activity.sendNotification(ReportField.REPORT_FIELD_MOUSE_BUTTONS, 0x01);
75 | activity.sendNotification(ReportField.REPORT_FIELD_MOUSE_BUTTONS, 0x00);
76 | return super.onDoubleTap(e);
77 | }
78 | });
79 | private VelocityTracker mVelocityTracker = null;
80 |
81 | @Override
82 | public boolean onTouch(View v, MotionEvent event) {
83 | CustomViewPager pager = (CustomViewPager) getActivity().findViewById(R.id.viewPager);
84 |
85 | int index = event.getActionIndex();
86 | int action = event.getActionMasked();
87 | int pointerId = event.getPointerId(index);
88 |
89 | switch (action) {
90 | case MotionEvent.ACTION_DOWN:
91 | pager.swipePossible(false);
92 |
93 | if (mVelocityTracker == null) {
94 | mVelocityTracker = VelocityTracker.obtain();
95 | } else {
96 | mVelocityTracker.clear();
97 | }
98 |
99 | mVelocityTracker.addMovement(event);
100 | break;
101 | case MotionEvent.ACTION_MOVE:
102 | mVelocityTracker.addMovement(event);
103 | mVelocityTracker.computeCurrentVelocity(10000);
104 |
105 | if ((++i >= 3)) {
106 | x /= 150 * 3;
107 | y /= 150 * 3;
108 |
109 | byte _x = (byte) (x > 127 ? 127 : (x < -127 ? -127 : x));
110 | byte _y = (byte) (y > 127 ? 127 : (y < -127 ? -127 : y));
111 | int toSend = _x | (((short) _y) << 8);
112 |
113 | activity.sendNotification(ReportField.REPORT_FIELD_MOUSE_XY, toSend);
114 | i = 0;
115 | x = 0.0f;
116 | y = 0.0f;
117 | } else {
118 | x += VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId);
119 | y += VelocityTrackerCompat.getYVelocity(mVelocityTracker, pointerId);
120 | }
121 |
122 | break;
123 | case MotionEvent.ACTION_UP:
124 | pager.swipePossible(true);
125 | mVelocityTracker.recycle();
126 | mVelocityTracker = null;
127 | break;
128 | }
129 |
130 | gestureDetector.onTouchEvent(event);
131 |
132 | return true;
133 | }
134 | });
135 | }
136 |
137 | @Override
138 | public boolean onTouch(View v, MotionEvent event) {
139 | MainActivity activity = (MainActivity) getActivity();
140 | short toSend = 0;
141 | int value;
142 |
143 | switch (v.getId()) {
144 | /* Mouse keys */
145 | case R.id.mouse_button_mouse_1:
146 | value = 0x01;
147 | break;
148 | case R.id.mouse_button_mouse_2:
149 | value = 0x02;
150 | break;
151 | case R.id.mouse_button_mouse_3:
152 | value = 0x04;
153 | break;
154 | case R.id.mouse_button_mouse_4:
155 | value = 0x08;
156 | break;
157 | case R.id.mouse_button_mouse_5:
158 | value = 0x10;
159 | break;
160 | default:
161 | return false;
162 | }
163 |
164 | if (event.getAction() == MotionEvent.ACTION_DOWN) {
165 | toSend |= value;
166 | } else if (event.getAction() == MotionEvent.ACTION_UP) {
167 | toSend &= ~value;
168 | toSend &= 0xffff;
169 | } else {
170 | return false;
171 | }
172 |
173 | activity.sendNotification(ReportField.REPORT_FIELD_MOUSE_BUTTONS, toSend);
174 |
175 | return true;
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/ConsumerFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.graphics.Color;
19 | import android.os.Bundle;
20 | import android.support.annotation.Nullable;
21 | import android.support.v4.app.Fragment;
22 | import android.view.LayoutInflater;
23 | import android.view.MotionEvent;
24 | import android.view.View;
25 | import android.view.ViewGroup;
26 | import android.widget.AdapterView;
27 | import android.widget.ArrayAdapter;
28 | import android.widget.Button;
29 | import android.widget.ImageButton;
30 | import android.widget.LinearLayout;
31 | import android.widget.Spinner;
32 | import android.widget.TextView;
33 |
34 | import java.util.ArrayList;
35 | import java.util.List;
36 |
37 | import static android.view.View.INVISIBLE;
38 |
39 | public class ConsumerFragment extends Fragment implements Button.OnTouchListener,
40 | AdapterView.OnItemSelectedListener {
41 |
42 | public static ConsumerFragment newInstance() {
43 | return new ConsumerFragment();
44 | }
45 |
46 | private void setOnTouchListenerForEach(LinearLayout layout) {
47 | for (int i = 0; i < layout.getChildCount(); i++) {
48 | View v = layout.getChildAt(i);
49 |
50 | if (v instanceof LinearLayout) {
51 | setOnTouchListenerForEach((LinearLayout) v);
52 | } else if (v instanceof ImageButton) {
53 | v.setOnTouchListener(this);
54 | }
55 | }
56 | }
57 |
58 | @Override
59 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
60 | View v = inflater.inflate(R.layout.consumer_fragment, container, false);
61 |
62 | ConsumerControlUsage.bindButtonId(R.id.cons_button_bright_plus,
63 | ConsumerControlUsage.BRIGHT_UP);
64 | ConsumerControlUsage.bindButtonId(R.id.cons_button_bright_minus,
65 | ConsumerControlUsage.BRIGHT_DOWN);
66 | ConsumerControlUsage.bindButtonId(R.id.cons_button_next,
67 | ConsumerControlUsage.SCAN_NEXT_TRACK);
68 | ConsumerControlUsage.bindButtonId(R.id.cons_button_previous,
69 | ConsumerControlUsage.SCAN_PREVIOUS_TRACK);
70 | ConsumerControlUsage.bindButtonId(R.id.cons_button_stop,
71 | ConsumerControlUsage.STOP);
72 | ConsumerControlUsage.bindButtonId(R.id.cons_button_start_stop,
73 | ConsumerControlUsage.PLAY_PAUSE);
74 | ConsumerControlUsage.bindButtonId(R.id.cons_button_mute,
75 | ConsumerControlUsage.MUTE);
76 | ConsumerControlUsage.bindButtonId(R.id.cons_button_vol_plus,
77 | ConsumerControlUsage.VOLUME_UP);
78 | ConsumerControlUsage.bindButtonId(R.id.cons_button_vol_minus,
79 | ConsumerControlUsage.VOLUME_DOWN);
80 | ConsumerControlUsage.bindButtonId(R.id.cons_button_eject,
81 | ConsumerControlUsage.EJECT);
82 | ConsumerControlUsage.bindButtonId(R.id.cons_button_snapshot,
83 | ConsumerControlUsage.SNAPSHOT);
84 | ConsumerControlUsage.bindButtonId(R.id.cons_button_system_sleep,
85 | ConsumerControlUsage.SYSTEM_SLEEP);
86 | ConsumerControlUsage.bindButtonId(R.id.cons_button_system_hibernation,
87 | ConsumerControlUsage.SYSTEM_HIBERNATE);
88 | ConsumerControlUsage.bindButtonId(R.id.cons_button_system_power_down,
89 | ConsumerControlUsage.SYSTEM_POWER_DOWN);
90 | ConsumerControlUsage.bindButtonId(R.id.cons_button_system_restart,
91 | ConsumerControlUsage.SYSTEM_WARM_RESTART);
92 |
93 | return v;
94 | }
95 |
96 | @Override
97 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
98 | setOnTouchListenerForEach((LinearLayout) getActivity().findViewById(R.id.cons_sub_main_layout));
99 |
100 | // Application launch spinner configuration
101 | List lal = new ArrayList<>();
102 | lal.add("SELECT VALUE");
103 | lal.addAll(ApplicationLaunchButtonsUsage.getUsageNames());
104 |
105 | Spinner spinner_al = (Spinner) getActivity().findViewById(R.id.cons_spinner_al_hidden);
106 | spinner_al.setOnItemSelectedListener(this);
107 | ArrayAdapter dataAdapter_al = new ArrayAdapter<>(getContext(),
108 | android.R.layout.simple_spinner_item, lal);
109 | dataAdapter_al.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
110 | spinner_al.setAdapter(dataAdapter_al);
111 | spinner_al.setSelection(0);
112 |
113 | // Application control spinner configuration
114 | List lac = new ArrayList<>();
115 | lac.add("SELECT VALUE");
116 | lac.addAll(ApplicationControlUsage.getUsageNames());
117 |
118 | Spinner spinner_ac = (Spinner) getActivity().findViewById(R.id.cons_spinner_ac_hidden);
119 | spinner_ac.setOnItemSelectedListener(this);
120 | ArrayAdapter dataAdapter_ac = new ArrayAdapter<>(getContext(),
121 | android.R.layout.simple_spinner_item, lac);
122 | dataAdapter_ac.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
123 | spinner_ac.setAdapter(dataAdapter_ac);
124 | spinner_ac.setSelection(0);
125 |
126 | if (ApplicationConfiguration.getConfigurationField(getContext(),
127 | ApplicationConfiguration.BASIC_FEAT)) {
128 | getActivity().findViewById(R.id.cons_system_text_hidden).setVisibility(INVISIBLE);
129 | getActivity().findViewById(R.id.cons_system_button_layout_hidden).setVisibility(INVISIBLE);
130 | getActivity().findViewById(R.id.cons_launch_text_hidden).setVisibility(INVISIBLE);
131 | getActivity().findViewById(R.id.cons_control_text_hidden).setVisibility(INVISIBLE);
132 | getActivity().findViewById(R.id.cons_spinner_al_hidden).setVisibility(INVISIBLE);
133 | getActivity().findViewById(R.id.cons_spinner_ac_hidden).setVisibility(INVISIBLE);
134 | }
135 | }
136 |
137 | @Override
138 | public void onPause() {
139 | super.onPause();
140 |
141 | Spinner spinner_al = (Spinner) getActivity().findViewById(R.id.cons_spinner_al_hidden);
142 | Spinner spinner_ac = (Spinner) getActivity().findViewById(R.id.cons_spinner_ac_hidden);
143 |
144 | spinner_al.setSelection(0);
145 | spinner_ac.setSelection(0);
146 | }
147 |
148 | @Override
149 | public boolean onTouch(View v, MotionEvent event) {
150 | short toSend = 0;
151 | int value = ConsumerControlUsage.getUsage(v.getId());
152 | MainActivity activity = (MainActivity) getActivity();
153 |
154 | if (value == 0) {
155 | return false;
156 | }
157 |
158 | if (event.getAction() == MotionEvent.ACTION_DOWN) {
159 | toSend |= value;
160 | } else if (event.getAction() == MotionEvent.ACTION_UP) {
161 | toSend &= ~value;
162 | toSend &= 0xffff;
163 | } else {
164 | return false;
165 | }
166 |
167 | activity.sendNotification(ReportField.REPORT_FIELD_CONSUMER_CONTROL, toSend);
168 |
169 | return true;
170 | }
171 |
172 | @Override
173 | public void onItemSelected(AdapterView> parent, View view, int position, long id) {
174 | MainActivity activity = (MainActivity) getActivity();
175 | short value;
176 |
177 | if (parent.getChildAt(0) != null) {
178 | ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
179 |
180 | switch (parent.getId()) {
181 | case R.id.cons_spinner_al_hidden:
182 | if (position == 0) {
183 | /* Dummy item */
184 | return;
185 | }
186 |
187 | value = ApplicationLaunchButtonsUsage.AL_USAGES[position - 1].usage;
188 | activity.sendNotification(ReportField.REPORT_FIELD_LAUNCHER_BUTTON, (int) value);
189 | activity.sendNotification(ReportField.REPORT_FIELD_LAUNCHER_BUTTON, 0);
190 | break;
191 | case R.id.cons_spinner_ac_hidden:
192 | if (position == 0) {
193 | /* Dummy item */
194 | return;
195 | }
196 |
197 | value = ApplicationControlUsage.AC_USAGES[position - 1].usage;
198 | activity.sendNotification(ReportField.REPORT_FIELD_CONTROL_BUTTON, (int) value);
199 | activity.sendNotification(ReportField.REPORT_FIELD_CONTROL_BUTTON, 0);
200 | break;
201 | }
202 | }
203 | }
204 |
205 | @Override
206 | public void onNothingSelected(AdapterView> parent) {
207 | if (parent.getChildAt(0) != null) {
208 | ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
209 | }
210 | }
211 | }
212 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/ApplicationControlUsage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | public class ApplicationControlUsage {
22 | public static final ApplicationControlUsage[] AC_USAGES = {
23 | new ApplicationControlUsage(0x0201, "New"),
24 | new ApplicationControlUsage(0x0202, "Open"),
25 | new ApplicationControlUsage(0x0203, "Close"),
26 | new ApplicationControlUsage(0x0204, "Exit"),
27 | new ApplicationControlUsage(0x0205, "Maximize"),
28 | new ApplicationControlUsage(0x0206, "Minimize"),
29 | new ApplicationControlUsage(0x0207, "Save"),
30 | new ApplicationControlUsage(0x0208, "Print"),
31 | new ApplicationControlUsage(0x0209, "Properties"),
32 | new ApplicationControlUsage(0x021A, "Undo"),
33 | new ApplicationControlUsage(0x021B, "Copy"),
34 | new ApplicationControlUsage(0x021C, "Cut"),
35 | new ApplicationControlUsage(0x021D, "Paste"),
36 | new ApplicationControlUsage(0x021E, "Select All"),
37 | new ApplicationControlUsage(0x021F, "Find"),
38 | new ApplicationControlUsage(0x0220, "Find and Replace"),
39 | new ApplicationControlUsage(0x0221, "Search"),
40 | new ApplicationControlUsage(0x0222, "Go To"),
41 | new ApplicationControlUsage(0x0223, "Home"),
42 | new ApplicationControlUsage(0x0224, "Back"),
43 | new ApplicationControlUsage(0x0225, "Forward"),
44 | new ApplicationControlUsage(0x0226, "Stop"),
45 | new ApplicationControlUsage(0x0227, "Refresh"),
46 | new ApplicationControlUsage(0x0228, "Previous Link"),
47 | new ApplicationControlUsage(0x0229, "Next Link"),
48 | new ApplicationControlUsage(0x022A, "Bookmarks"),
49 | new ApplicationControlUsage(0x022B, "History"),
50 | new ApplicationControlUsage(0x022C, "Subscriptions"),
51 | new ApplicationControlUsage(0x022D, "Zoom In"),
52 | new ApplicationControlUsage(0x022E, "Zoom Out"),
53 | new ApplicationControlUsage(0x022F, "Zoom"),
54 | new ApplicationControlUsage(0x0230, "Full Screen View"),
55 | new ApplicationControlUsage(0x0231, "Normal View"),
56 | new ApplicationControlUsage(0x0232, "View Toggle"),
57 | new ApplicationControlUsage(0x0233, "Scroll Up"),
58 | new ApplicationControlUsage(0x0234, "Scroll Down"),
59 | new ApplicationControlUsage(0x0235, "Scroll"),
60 | new ApplicationControlUsage(0x0236, "Pan Left"),
61 | new ApplicationControlUsage(0x0237, "Pan Right"),
62 | new ApplicationControlUsage(0x0238, "Pan"),
63 | new ApplicationControlUsage(0x0239, "New Window"),
64 | new ApplicationControlUsage(0x023A, "Tile Horizontally"),
65 | new ApplicationControlUsage(0x023B, "Tile Vertically"),
66 | new ApplicationControlUsage(0x023C, "Format"),
67 | new ApplicationControlUsage(0x023D, "Edit"),
68 | new ApplicationControlUsage(0x023E, "Bold"),
69 | new ApplicationControlUsage(0x023F, "Italics"),
70 | new ApplicationControlUsage(0x0240, "Underline"),
71 | new ApplicationControlUsage(0x0241, "Strikethrough"),
72 | new ApplicationControlUsage(0x0242, "Subscript"),
73 | new ApplicationControlUsage(0x0243, "Superscript"),
74 | new ApplicationControlUsage(0x0244, "All Caps"),
75 | new ApplicationControlUsage(0x0245, "Rotate"),
76 | new ApplicationControlUsage(0x0246, "Resize"),
77 | new ApplicationControlUsage(0x0247, "Flip horizontal"),
78 | new ApplicationControlUsage(0x0248, "Flip Vertical"),
79 | new ApplicationControlUsage(0x0249, "Mirror Horizontal"),
80 | new ApplicationControlUsage(0x024A, "Mirror Vertical"),
81 | new ApplicationControlUsage(0x024B, "Font Select"),
82 | new ApplicationControlUsage(0x024C, "Font Color"),
83 | new ApplicationControlUsage(0x024D, "Font Size"),
84 | new ApplicationControlUsage(0x024E, "Justify Left"),
85 | new ApplicationControlUsage(0x024F, "Justify Center H"),
86 | new ApplicationControlUsage(0x0250, "Justify Right"),
87 | new ApplicationControlUsage(0x0251, "Justify Block H"),
88 | new ApplicationControlUsage(0x0252, "Justify Top"),
89 | new ApplicationControlUsage(0x0253, "Justify Center V"),
90 | new ApplicationControlUsage(0x0254, "Justify Bottom"),
91 | new ApplicationControlUsage(0x0255, "Justify Block V"),
92 | new ApplicationControlUsage(0x0256, "Indent Decrease"),
93 | new ApplicationControlUsage(0x0257, "Indent Increase"),
94 | new ApplicationControlUsage(0x0258, "Numbered List"),
95 | new ApplicationControlUsage(0x0259, "Restart Numbering"),
96 | new ApplicationControlUsage(0x025A, "Bulleted List"),
97 | new ApplicationControlUsage(0x025B, "Promote"),
98 | new ApplicationControlUsage(0x025C, "Demote"),
99 | new ApplicationControlUsage(0x025D, "Yes"),
100 | new ApplicationControlUsage(0x025E, "No"),
101 | new ApplicationControlUsage(0x025F, "Cancel"),
102 | new ApplicationControlUsage(0x0260, "Catalog"),
103 | new ApplicationControlUsage(0x0261, "Buy/Checkout"),
104 | new ApplicationControlUsage(0x0262, "Add to Cart"),
105 | new ApplicationControlUsage(0x0263, "Expand"),
106 | new ApplicationControlUsage(0x0264, "Expand All"),
107 | new ApplicationControlUsage(0x0265, "Collapse"),
108 | new ApplicationControlUsage(0x0266, "Collapse All"),
109 | new ApplicationControlUsage(0x0267, "Print Preview"),
110 | new ApplicationControlUsage(0x0268, "Paste Special"),
111 | new ApplicationControlUsage(0x0269, "Insert Mode"),
112 | new ApplicationControlUsage(0x026A, "Delete"),
113 | new ApplicationControlUsage(0x026B, "Lock"),
114 | new ApplicationControlUsage(0x026C, "Unlock"),
115 | new ApplicationControlUsage(0x026D, "Protect"),
116 | new ApplicationControlUsage(0x026E, "Unprotect"),
117 | new ApplicationControlUsage(0x026F, "Attach Comment"),
118 | new ApplicationControlUsage(0x0270, "Delete Comment"),
119 | new ApplicationControlUsage(0x0271, "View Comment"),
120 | new ApplicationControlUsage(0x0272, "Select Word"),
121 | new ApplicationControlUsage(0x0273, "Select Sentence"),
122 | new ApplicationControlUsage(0x0274, "Select Paragraph"),
123 | new ApplicationControlUsage(0x0275, "Select Column"),
124 | new ApplicationControlUsage(0x0276, "Select Row"),
125 | new ApplicationControlUsage(0x0277, "Select Table"),
126 | new ApplicationControlUsage(0x0278, "Select Object"),
127 | new ApplicationControlUsage(0x0279, "Redo/Repeat"),
128 | new ApplicationControlUsage(0x027A, "Sort"),
129 | new ApplicationControlUsage(0x027B, "Sort Ascending"),
130 | new ApplicationControlUsage(0x027C, "Sort Descending"),
131 | new ApplicationControlUsage(0x027D, "Filter"),
132 | new ApplicationControlUsage(0x027E, "Set Clock"),
133 | new ApplicationControlUsage(0x027F, "View Clock"),
134 | new ApplicationControlUsage(0x0280, "Select Time Zone"),
135 | new ApplicationControlUsage(0x0281, "Edit Time Zones"),
136 | new ApplicationControlUsage(0x0282, "Set Alarm"),
137 | new ApplicationControlUsage(0x0283, "Clear Alarm"),
138 | new ApplicationControlUsage(0x0284, "Snooze Alarm"),
139 | new ApplicationControlUsage(0x0285, "Reset Alarm"),
140 | new ApplicationControlUsage(0x0286, "Synchronize"),
141 | new ApplicationControlUsage(0x0287, "Send/Receive"),
142 | new ApplicationControlUsage(0x0288, "Send To"),
143 | new ApplicationControlUsage(0x0289, "Reply"),
144 | new ApplicationControlUsage(0x028A, "Reply All"),
145 | new ApplicationControlUsage(0x028B, "Forward Msg"),
146 | new ApplicationControlUsage(0x028C, "Send"),
147 | new ApplicationControlUsage(0x028D, "Attach File"),
148 | new ApplicationControlUsage(0x028E, "Upload"),
149 | new ApplicationControlUsage(0x028F, "Download (Save Target As)"),
150 | new ApplicationControlUsage(0x0290, "Set Borders"),
151 | new ApplicationControlUsage(0x0291, "Insert Row"),
152 | new ApplicationControlUsage(0x0292, "Insert Column"),
153 | new ApplicationControlUsage(0x0293, "Insert File"),
154 | new ApplicationControlUsage(0x0294, "Insert Picture"),
155 | new ApplicationControlUsage(0x0295, "Insert Object"),
156 | new ApplicationControlUsage(0x0296, "Insert Symbol"),
157 | new ApplicationControlUsage(0x0297, "Save and Close"),
158 | new ApplicationControlUsage(0x0298, "Rename"),
159 | new ApplicationControlUsage(0x0299, "Merge"),
160 | new ApplicationControlUsage(0x029A, "Split"),
161 | new ApplicationControlUsage(0x029B, "Disribute Horizontally"),
162 | new ApplicationControlUsage(0x029C, "Distribute Vertically"),
163 | };
164 | public final short usage;
165 | private final String name;
166 |
167 | private ApplicationControlUsage(int u, String n) {
168 | usage = (short) u;
169 | name = n;
170 | }
171 |
172 | static public List getUsageNames() {
173 | List l = new ArrayList<>();
174 |
175 | for (ApplicationControlUsage AC_USAGE : AC_USAGES) {
176 | l.add(AC_USAGE.name);
177 | }
178 |
179 | return l;
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/consumer_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
24 |
25 |
33 |
34 |
40 |
41 |
45 |
46 |
53 |
54 |
61 |
62 |
69 |
70 |
77 |
78 |
79 |
85 |
86 |
90 |
91 |
98 |
99 |
106 |
107 |
114 |
115 |
116 |
122 |
123 |
127 |
128 |
135 |
136 |
143 |
144 |
145 |
151 |
152 |
156 |
157 |
164 |
165 |
172 |
173 |
174 |
175 |
182 |
183 |
188 |
189 |
196 |
197 |
204 |
205 |
212 |
213 |
220 |
221 |
222 |
229 |
230 |
235 |
236 |
243 |
244 |
250 |
251 |
252 |
253 |
262 |
263 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.bluetooth.BluetoothDevice;
19 | import android.content.ComponentName;
20 | import android.content.Context;
21 | import android.content.Intent;
22 | import android.content.ServiceConnection;
23 | import android.content.pm.ActivityInfo;
24 | import android.graphics.Color;
25 | import android.os.Bundle;
26 | import android.os.Handler;
27 | import android.os.IBinder;
28 | import android.support.v4.app.Fragment;
29 | import android.support.v4.app.FragmentActivity;
30 | import android.support.v4.app.FragmentManager;
31 | import android.support.v4.app.FragmentPagerAdapter;
32 | import android.util.Log;
33 | import android.view.KeyEvent;
34 | import android.widget.LinearLayout;
35 | import android.widget.TextView;
36 |
37 | import java.util.ArrayList;
38 |
39 | public class MainActivity extends FragmentActivity implements KeyEvent.Callback {
40 | private final Handler threadHandler = new Handler();
41 | public CustomViewPager pager = null;
42 | public PagerAdapter pagerAdapter = null;
43 | private volatile ArrayList devices = new ArrayList<>();
44 | private final Runnable deviceLayoutUpdate = new Runnable() {
45 | volatile ArrayList devices_copy = new ArrayList<>();
46 |
47 | public void run() {
48 | final long refreshLayoutPeriodMs = 300;
49 | final LinearLayout ll = (LinearLayout) findViewById(R.id.conf_linear_layout_devices);
50 |
51 | devices_copy = devices;
52 |
53 | if (ll == null) {
54 | threadHandler.postDelayed(this, refreshLayoutPeriodMs);
55 | return;
56 | }
57 |
58 | runOnUiThread(new Runnable() {
59 | @Override
60 | public void run() {
61 | ll.removeAllViews();
62 | }
63 | });
64 |
65 | if (devices_copy == null) {
66 | threadHandler.postDelayed(this, refreshLayoutPeriodMs);
67 | return;
68 | }
69 |
70 | for (int k = 0; k < devices_copy.size(); k++) {
71 | BluetoothDevice bd;
72 | final TextView textView = new TextView(getApplicationContext());
73 |
74 | try {
75 | bd = devices_copy.get(k);
76 | } catch (IndexOutOfBoundsException e) {
77 | break;
78 | }
79 |
80 | textView.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
81 | textView.setWidth(ll.getWidth());
82 | textView.setBackgroundColor(0xff2546e9);
83 | textView.setTextColor(Color.WHITE);
84 | textView.setText("" + bd.getName() + " (" + bd.getAddress() + ")");
85 |
86 | runOnUiThread(new Runnable() {
87 | @Override
88 | public void run() {
89 | ll.addView(textView);
90 | }
91 | });
92 | }
93 |
94 | threadHandler.postDelayed(this, refreshLayoutPeriodMs);
95 | }
96 | };
97 | private final Runnable deviceFieldUpdate = new Runnable() {
98 | volatile ArrayList devices_copy = new ArrayList<>();
99 | private int i = 0;
100 |
101 | public void run() {
102 | final long refreshTextViewPeriodMs = 1200;
103 | String text;
104 | int text_color;
105 | int bg_color;
106 |
107 | devices_copy = devices;
108 |
109 | if (devices_copy != null && devices_copy.size() > 0) {
110 | BluetoothDevice d;
111 |
112 | try {
113 | d = devices_copy.get(i);
114 | } catch (IndexOutOfBoundsException e) {
115 | i = 0;
116 | threadHandler.postDelayed(this, refreshTextViewPeriodMs);
117 | return;
118 | }
119 |
120 | text = "" + d.getName() + " (" + d.getAddress() + ")";
121 | text_color = Color.WHITE;
122 | bg_color = 0xff2546e9;
123 |
124 | if (devices_copy.size() > 1) {
125 | text += " [" + i + " / " + (devices_copy.size() - 1) + "]";
126 | }
127 | } else {
128 | text = "Device not connected ";
129 | text_color = Color.BLACK;
130 | bg_color = Color.GRAY;
131 | }
132 |
133 | updateDeviceInfoField(text, text_color, bg_color);
134 | i = (devices_copy == null || devices_copy.size() == 0) ? 0 : (i + 1) % devices_copy.size();
135 | threadHandler.postDelayed(this, refreshTextViewPeriodMs);
136 | }
137 | };
138 | private HidBleService mService = null;
139 | private final ServiceConnection mConnection = new ServiceConnection() {
140 | @Override
141 | public void onServiceConnected(ComponentName className,
142 | IBinder service) {
143 | HidBleService.LocalBinder binder = (HidBleService.LocalBinder) service;
144 | mService = binder.getService();
145 | mService.setActivity(MainActivity.this);
146 | devices = mService.getDevices();
147 | }
148 |
149 | @Override
150 | public void onServiceDisconnected(ComponentName arg0) {
151 |
152 | }
153 | };
154 |
155 | private void updateDeviceInfoField(final String text, final int text_color, final int bg_color) {
156 |
157 | runOnUiThread(new Runnable() {
158 | @Override
159 | public void run() {
160 | final int[] ids = {
161 | R.id.cons_text_device_info, R.id.mouse_text_device_info,
162 | R.id.keyboard_text_device_info, R.id.d_pad_text_device_info
163 | };
164 |
165 | for (int id : ids) {
166 | TextView textView = (TextView) findViewById(id);
167 |
168 | if (textView == null) {
169 | continue;
170 | }
171 |
172 | textView.setBackgroundColor(bg_color);
173 | textView.setTextColor(text_color);
174 | textView.setText(text);
175 | textView.refreshDrawableState();
176 | }
177 | }
178 | });
179 | }
180 |
181 | public void onConnectionStateChange(ArrayList dev_array) {
182 | devices = dev_array;
183 | }
184 |
185 | public void sendNotification(ReportField rf, int value) {
186 | if (mService == null) {
187 | // Service is not bound yet
188 | return;
189 | }
190 |
191 | mService.sendNotification(rf, value);
192 | }
193 |
194 | public void sendNotification(String s) {
195 | if (mService == null) {
196 | // Service is not bound yet
197 | return;
198 | }
199 |
200 | mService.sendNotification(s);
201 | }
202 |
203 | public void restartGattDatabase() {
204 | if (mService == null) {
205 | return;
206 | }
207 |
208 | mService.initializeLE();
209 | }
210 |
211 | @Override
212 | protected void onCreate(Bundle savedInstanceState) {
213 | super.onCreate(savedInstanceState);
214 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
215 | setContentView(R.layout.activity_main);
216 |
217 | pagerAdapter = new PagerAdapter(getSupportFragmentManager());
218 | pager = (CustomViewPager) findViewById(R.id.viewPager);
219 | pager.setAdapter(pagerAdapter);
220 | pager.setCurrentItem(1);
221 | pager.setHorizontalFadingEdgeEnabled(false);
222 | pager.swipePossible(true);
223 |
224 | Intent intent = new Intent(this, HidBleService.class);
225 | bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
226 |
227 | ApplicationConfiguration.initializeConfiguration(getApplicationContext());
228 | threadHandler.post(deviceFieldUpdate);
229 | threadHandler.post(deviceLayoutUpdate);
230 | }
231 |
232 | @Override
233 | protected void onDestroy() {
234 | super.onDestroy();
235 |
236 | unbindService(mConnection);
237 | threadHandler.removeCallbacks(deviceFieldUpdate);
238 | }
239 |
240 | @Override
241 | public boolean onKeyDown(int keyCode, KeyEvent event) {
242 | byte key = 0;
243 | byte meta_key = 0;
244 | short val;
245 |
246 | if (pager.getCurrentItem() == PagerAdapter.MOUSE) {
247 | if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
248 | sendNotification(ReportField.REPORT_FIELD_MOUSE_SCROLL, -1);
249 | return true;
250 | } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
251 | sendNotification(ReportField.REPORT_FIELD_MOUSE_SCROLL, 1);
252 | return true;
253 | }
254 | } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
255 | keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
256 | return false;
257 | }
258 |
259 | for (int i = 0; i < KeyboardUsage.KEYBOARD_USAGES.length; i++) {
260 | if (keyCode == KeyboardUsage.KEYBOARD_USAGES[i].key_code) {
261 | key = KeyboardUsage.KEYBOARD_USAGES[i].usage;
262 | meta_key = KeyboardUsage.KEYBOARD_USAGES[i].meta;
263 | break;
264 | }
265 | }
266 |
267 | if (key == 0) {
268 | Log.e("BLE", "Pressed unhandled keyboard button " + keyCode);
269 | return super.onKeyDown(keyCode, event);
270 |
271 | }
272 |
273 | if (event.isCtrlPressed()) {
274 | meta_key |= KeyboardUsage.META_LEFT_CONTROL;
275 | }
276 |
277 | if (event.isShiftPressed()) {
278 | meta_key |= KeyboardUsage.META_LEFT_SHIFT;
279 | }
280 |
281 | if (event.isAltPressed()) {
282 | meta_key |= KeyboardUsage.META_LEFT_ALT;
283 | }
284 |
285 | if (event.isMetaPressed()) {
286 | meta_key |= KeyboardUsage.META_LEFT_META;
287 | }
288 |
289 | val = (short) (meta_key + (key << 8));
290 | sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, (int) val);
291 |
292 | return true;
293 | }
294 |
295 | @Override
296 | public boolean onKeyUp(int keyCode, KeyEvent event) {
297 | int key = 0;
298 |
299 | if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
300 | if (pager.getCurrentItem() == PagerAdapter.MOUSE) {
301 | sendNotification(ReportField.REPORT_FIELD_MOUSE_SCROLL, 0);
302 | return true;
303 | } else {
304 | return false;
305 | }
306 | }
307 |
308 | sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, key);
309 |
310 | return true;
311 | }
312 |
313 | class PagerAdapter extends FragmentPagerAdapter {
314 | static final int CONFIGURATION = 0;
315 | static final int CONSUMER = 1;
316 | static final int MOUSE = 2;
317 | static final int KEYBOARD = 3;
318 | static final int D_PAD = 4;
319 |
320 | PagerAdapter(FragmentManager fm) {
321 | super(fm);
322 | }
323 |
324 | @Override
325 | public Fragment getItem(int pos) {
326 | Fragment[] fragments = new Fragment[5];
327 | int index = 2;
328 |
329 | fragments[0] = ConfigurationFragment.newInstance();
330 | fragments[1] = ConsumerFragment.newInstance();
331 | fragments[2] = ConfigurationFragment.newInstance();
332 | fragments[3] = ConfigurationFragment.newInstance();
333 | fragments[4] = ConfigurationFragment.newInstance();
334 |
335 | // Consumer fragment is always available
336 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
337 | ApplicationConfiguration.MOUSE_FEAT)) {
338 | fragments[index] = MouseFragment.newInstance();
339 | ++index;
340 | }
341 |
342 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
343 | ApplicationConfiguration.KEYBOARD_FEAT)) {
344 | fragments[index] = KeyboardFragment.newInstance();
345 | ++index;
346 | fragments[index] = DPadFragment.newInstance();
347 | ++index;
348 | }
349 |
350 | return fragments[pos];
351 | }
352 |
353 | @Override
354 | public int getCount() {
355 | int count = 2;
356 |
357 | // Consumer fragment is always available
358 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
359 | ApplicationConfiguration.MOUSE_FEAT)) {
360 | count += 1;
361 | }
362 |
363 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
364 | ApplicationConfiguration.KEYBOARD_FEAT)) {
365 | count += 2;
366 | }
367 |
368 | return count;
369 | }
370 | }
371 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/KeyboardUsage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.view.KeyEvent;
19 |
20 | import java.util.ArrayList;
21 | import java.util.List;
22 | import java.util.Objects;
23 |
24 | final class KeyboardUsage {
25 | static final byte META_LEFT_CONTROL = (byte) 0x01;
26 | static final byte META_LEFT_SHIFT = (byte) 0x02;
27 | static final byte META_LEFT_ALT = (byte) 0x04;
28 | static final byte META_LEFT_META = (byte) 0x08;
29 | static final byte META_RIGHT_CONTROL = (byte) 0x10;
30 | static final byte META_RIGHT_SHIFT = (byte) 0x20;
31 | static final byte META_RIGHT_ALT = (byte) 0x40;
32 | static final byte META_RIGHT_META = (byte) 0x80;
33 |
34 | static final KeyboardUsage[] KEYBOARD_USAGES = {
35 | new KeyboardUsage(KeyEvent.KEYCODE_UNKNOWN, (byte) 0x00, '\0', "Unknown", true),
36 | new KeyboardUsage(KeyEvent.KEYCODE_A, (byte) 0x04, 'a'),
37 | new KeyboardUsage(KeyEvent.KEYCODE_B, (byte) 0x05, 'b'),
38 | new KeyboardUsage(KeyEvent.KEYCODE_C, (byte) 0x06, 'c'),
39 | new KeyboardUsage(KeyEvent.KEYCODE_D, (byte) 0x07, 'd'),
40 | new KeyboardUsage(KeyEvent.KEYCODE_E, (byte) 0x08, 'e'),
41 | new KeyboardUsage(KeyEvent.KEYCODE_F, (byte) 0x09, 'f'),
42 | new KeyboardUsage(KeyEvent.KEYCODE_G, (byte) 0x0a, 'g'),
43 | new KeyboardUsage(KeyEvent.KEYCODE_H, (byte) 0x0b, 'h'),
44 | new KeyboardUsage(KeyEvent.KEYCODE_I, (byte) 0x0c, 'i'),
45 | new KeyboardUsage(KeyEvent.KEYCODE_J, (byte) 0x0d, 'j'),
46 | new KeyboardUsage(KeyEvent.KEYCODE_K, (byte) 0x0e, 'k'),
47 | new KeyboardUsage(KeyEvent.KEYCODE_L, (byte) 0x0f, 'l'),
48 | new KeyboardUsage(KeyEvent.KEYCODE_M, (byte) 0x10, 'm'),
49 | new KeyboardUsage(KeyEvent.KEYCODE_N, (byte) 0x11, 'n'),
50 | new KeyboardUsage(KeyEvent.KEYCODE_O, (byte) 0x12, 'o'),
51 | new KeyboardUsage(KeyEvent.KEYCODE_P, (byte) 0x13, 'p'),
52 | new KeyboardUsage(KeyEvent.KEYCODE_Q, (byte) 0x14, 'q'),
53 | new KeyboardUsage(KeyEvent.KEYCODE_R, (byte) 0x15, 'r'),
54 | new KeyboardUsage(KeyEvent.KEYCODE_S, (byte) 0x16, 's'),
55 | new KeyboardUsage(KeyEvent.KEYCODE_T, (byte) 0x17, 't'),
56 | new KeyboardUsage(KeyEvent.KEYCODE_U, (byte) 0x18, 'u'),
57 | new KeyboardUsage(KeyEvent.KEYCODE_V, (byte) 0x19, 'v'),
58 | new KeyboardUsage(KeyEvent.KEYCODE_W, (byte) 0x1a, 'w'),
59 | new KeyboardUsage(KeyEvent.KEYCODE_X, (byte) 0x1b, 'x'),
60 | new KeyboardUsage(KeyEvent.KEYCODE_Y, (byte) 0x1c, 'y'),
61 | new KeyboardUsage(KeyEvent.KEYCODE_Z, (byte) 0x1d, 'z'),
62 | new KeyboardUsage(KeyEvent.KEYCODE_1, (byte) 0x1e, '1'),
63 | new KeyboardUsage(KeyEvent.KEYCODE_2, (byte) 0x1f, '2'),
64 | new KeyboardUsage(KeyEvent.KEYCODE_3, (byte) 0x20, '3'),
65 | new KeyboardUsage(KeyEvent.KEYCODE_4, (byte) 0x21, '4'),
66 | new KeyboardUsage(KeyEvent.KEYCODE_5, (byte) 0x22, '5'),
67 | new KeyboardUsage(KeyEvent.KEYCODE_6, (byte) 0x23, '6'),
68 | new KeyboardUsage(KeyEvent.KEYCODE_7, (byte) 0x24, '7'),
69 | new KeyboardUsage(KeyEvent.KEYCODE_8, (byte) 0x25, '8'),
70 | new KeyboardUsage(KeyEvent.KEYCODE_9, (byte) 0x26, '9'),
71 | new KeyboardUsage(KeyEvent.KEYCODE_0, (byte) 0x27, '0'),
72 | new KeyboardUsage(KeyEvent.KEYCODE_ENTER, (byte) 0x28, '\n', "Enter", true),
73 | new KeyboardUsage(KeyEvent.KEYCODE_ESCAPE, (byte) 0x29, '\0', "Escape", true),
74 | new KeyboardUsage(KeyEvent.KEYCODE_DEL, (byte) 0x2a, '\0', "DEL", true),
75 | new KeyboardUsage(KeyEvent.KEYCODE_TAB, (byte) 0x2b, '\t', "TAB", true),
76 | new KeyboardUsage(KeyEvent.KEYCODE_SPACE, (byte) 0x2c, ' '),
77 | new KeyboardUsage(KeyEvent.KEYCODE_MINUS, (byte) 0x2d, '-'),
78 | new KeyboardUsage(KeyEvent.KEYCODE_EQUALS, (byte) 0x2e, '='),
79 | new KeyboardUsage(KeyEvent.KEYCODE_LEFT_BRACKET, (byte) 0x2f, '['),
80 | new KeyboardUsage(KeyEvent.KEYCODE_RIGHT_BRACKET, (byte) 0x30, ']'),
81 | new KeyboardUsage(KeyEvent.KEYCODE_BACKSLASH, (byte) 0x31, '\\'),
82 | new KeyboardUsage(KeyEvent.KEYCODE_BACKSLASH, (byte) 0x32, '\\'),
83 | new KeyboardUsage(KeyEvent.KEYCODE_SEMICOLON, (byte) 0x33, ';'),
84 | new KeyboardUsage(KeyEvent.KEYCODE_APOSTROPHE, (byte) 0x34, '\''),
85 | new KeyboardUsage(KeyEvent.KEYCODE_GRAVE, (byte) 0x35, '`'),
86 | new KeyboardUsage(KeyEvent.KEYCODE_COMMA, (byte) 0x36, ','),
87 | new KeyboardUsage(KeyEvent.KEYCODE_NUMPAD_DOT, (byte) 0x37, '.'),
88 | new KeyboardUsage(KeyEvent.KEYCODE_PERIOD, (byte) 0x37, '.'),
89 | new KeyboardUsage(KeyEvent.KEYCODE_SLASH, (byte) 0x38, '/'),
90 | new KeyboardUsage("CapsLock", (byte) 0x39, '/', true),
91 | new KeyboardUsage(KeyEvent.KEYCODE_F1, (byte) 0x3a, '\0', "F1", true),
92 | new KeyboardUsage(KeyEvent.KEYCODE_F2, (byte) 0x3b, '\0', "F2", true),
93 | new KeyboardUsage(KeyEvent.KEYCODE_F3, (byte) 0x3c, '\0', "F3", true),
94 | new KeyboardUsage(KeyEvent.KEYCODE_F4, (byte) 0x3d, '\0', "F4", true),
95 | new KeyboardUsage(KeyEvent.KEYCODE_F5, (byte) 0x3e, '\0', "F5", true),
96 | new KeyboardUsage(KeyEvent.KEYCODE_F6, (byte) 0x3f, '\0', "F6", true),
97 | new KeyboardUsage(KeyEvent.KEYCODE_F7, (byte) 0x40, '\0', "F7", true),
98 | new KeyboardUsage(KeyEvent.KEYCODE_F8, (byte) 0x41, '\0', "F8", true),
99 | new KeyboardUsage(KeyEvent.KEYCODE_F9, (byte) 0x42, '\0', "F9", true),
100 | new KeyboardUsage(KeyEvent.KEYCODE_F10, (byte) 0x43, '\0', "F10", true),
101 | new KeyboardUsage(KeyEvent.KEYCODE_F11, (byte) 0x44, '\0', "F11", true),
102 | new KeyboardUsage(KeyEvent.KEYCODE_F12, (byte) 0x45, '\0', "F12", true),
103 | new KeyboardUsage(KeyEvent.KEYCODE_SYSRQ, (byte) 0x46, '\0', "SysRq", true),
104 | new KeyboardUsage("ScrollLock", (byte) 0x47, '\0', true),
105 | new KeyboardUsage("Pause", (byte) 0x48, '\0', true),
106 | new KeyboardUsage(KeyEvent.KEYCODE_INSERT, (byte) 0x49, '\0', "Insert", true),
107 | new KeyboardUsage(KeyEvent.KEYCODE_MOVE_HOME, (byte) 0x4a, '\0', "Home", true),
108 | new KeyboardUsage(KeyEvent.KEYCODE_PAGE_UP, (byte) 0x4b, '\0', "Page Up", true),
109 | new KeyboardUsage(KeyEvent.KEYCODE_FORWARD_DEL, (byte) 0x4c, '\0', "Forward DEL", true),
110 | new KeyboardUsage(KeyEvent.KEYCODE_MOVE_END, (byte) 0x4d, '\0', "End", true),
111 | new KeyboardUsage(KeyEvent.KEYCODE_PAGE_DOWN, (byte) 0x4e, '\0', "Page Down", true),
112 | new KeyboardUsage(KeyEvent.KEYCODE_DPAD_RIGHT, (byte) 0x4f, '\0', "Right", true),
113 | new KeyboardUsage(KeyEvent.KEYCODE_DPAD_LEFT, (byte) 0x50, '\0', "Left", true),
114 | new KeyboardUsage(KeyEvent.KEYCODE_DPAD_DOWN, (byte) 0x51, '\0', "Down", true),
115 | new KeyboardUsage(KeyEvent.KEYCODE_DPAD_UP, (byte) 0x52, '\0', "Up", true),
116 | new KeyboardUsage("NumLock", (byte) 0x53, '\0', true),
117 | new KeyboardUsage("KPSlash", (byte) 0x54, '\0', true),
118 | new KeyboardUsage("KPAsterisk", (byte) 0x55, '\0', true),
119 | new KeyboardUsage("KPMinus", (byte) 0x56, '\0', true),
120 | new KeyboardUsage("KPPlus", (byte) 0x57, '\0', true),
121 | new KeyboardUsage("KPEnter", (byte) 0x58, '\0', true),
122 | new KeyboardUsage("KP1", (byte) 0x59, '\0', true),
123 | new KeyboardUsage("KP2", (byte) 0x5a, '\0', true),
124 | new KeyboardUsage("KP3", (byte) 0x5b, '\0', true),
125 | new KeyboardUsage("KP4", (byte) 0x5c, '\0', true),
126 | new KeyboardUsage("KP5", (byte) 0x5d, '\0', true),
127 | new KeyboardUsage("KP6", (byte) 0x5e, '\0', true),
128 | new KeyboardUsage("KP7", (byte) 0x5f, '\0', true),
129 | new KeyboardUsage("KP8", (byte) 0x60, '\0', true),
130 | new KeyboardUsage("KP9", (byte) 0x61, '\0', true),
131 | new KeyboardUsage("KP0", (byte) 0x62, '\0', true),
132 | new KeyboardUsage("KPDot", (byte) 0x63, '\0', true),
133 | new KeyboardUsage("102nd", (byte) 0x64, '\0', true),
134 | new KeyboardUsage("Compose", (byte) 0x65, '\0', true),
135 | new KeyboardUsage("Power", (byte) 0x66, '\0', true),
136 | new KeyboardUsage("KPEqual", (byte) 0x67, '\0', true),
137 | new KeyboardUsage("F13", (byte) 0x68, '\0', true),
138 | new KeyboardUsage("F14", (byte) 0x69, '\0', true),
139 | new KeyboardUsage("F15", (byte) 0x6a, '\0', true),
140 | new KeyboardUsage("F16", (byte) 0x6b, '\0', true),
141 | new KeyboardUsage("F17", (byte) 0x6c, '\0', true),
142 | new KeyboardUsage("F18", (byte) 0x6d, '\0', true),
143 | new KeyboardUsage("F19", (byte) 0x6e, '\0', true),
144 | new KeyboardUsage("F20", (byte) 0x6f, '\0', true),
145 | new KeyboardUsage("F21", (byte) 0x70, '\0', true),
146 | new KeyboardUsage("F22", (byte) 0x71, '\0', true),
147 | new KeyboardUsage("F23", (byte) 0x72, '\0', true),
148 | new KeyboardUsage("F24", (byte) 0x73, '\0', true),
149 | new KeyboardUsage("Open", (byte) 0x74, '\0', true),
150 | new KeyboardUsage(KeyEvent.KEYCODE_HELP, (byte) 0x75, '\0', "Help", true),
151 | new KeyboardUsage("Props", (byte) 0x76, '\0', true),
152 | new KeyboardUsage("Front", (byte) 0x77, '\0', true),
153 | new KeyboardUsage("Stop", (byte) 0x78, '\0', true),
154 | new KeyboardUsage("Again", (byte) 0x79, '\0', true),
155 | new KeyboardUsage("Undo", (byte) 0x7a, '\0', true),
156 | new KeyboardUsage(KeyEvent.KEYCODE_CUT, (byte) 0x7b, '\0', "Cut", true),
157 | new KeyboardUsage(KeyEvent.KEYCODE_COPY, (byte) 0x7c, '\0', "Copy", true),
158 | new KeyboardUsage(KeyEvent.KEYCODE_PASTE, (byte) 0x7d, '\0', "Paste", true),
159 | new KeyboardUsage("Find", (byte) 0x7e, '\0', true),
160 | new KeyboardUsage(KeyEvent.KEYCODE_VOLUME_MUTE, (byte) 0x7f, '\0', "Mute", true),
161 | new KeyboardUsage(KeyEvent.KEYCODE_VOLUME_UP, (byte) 0x80, '\0', "Volume Up", true),
162 | new KeyboardUsage(KeyEvent.KEYCODE_VOLUME_DOWN, (byte) 0x81, '\0', "Volume Down", true),
163 | /* ??? (0x82 - 0x84) */
164 | new KeyboardUsage("KPComma", (byte) 0x85, '\0', true),
165 | /* ??? (0x86) */
166 | new KeyboardUsage("RO", (byte) 0x87, '\0', true),
167 | new KeyboardUsage("Katakana/Hiragana", (byte) 0x88, '\0', true),
168 | new KeyboardUsage("Yen", (byte) 0x89, '\0', true),
169 | new KeyboardUsage("Henkan", (byte) 0x8a, '\0', true),
170 | new KeyboardUsage("Muhenkan", (byte) 0x8b, '\0', true),
171 | new KeyboardUsage("KPJpComma", (byte) 0x8c, '\0', true),
172 | /* ??? (0x8d - 0x8f) */
173 | new KeyboardUsage("Hangeul", (byte) 0x90, '\0', true),
174 | new KeyboardUsage("Hanja", (byte) 0x91, '\0', true),
175 | new KeyboardUsage("Katakana", (byte) 0x92, '\0', true),
176 | new KeyboardUsage("HIRAGANA", (byte) 0x93, '\0', true),
177 | new KeyboardUsage("Zenkaku/Hankaku", (byte) 0x94, '\0', true),
178 | /* ??? (0x95 - 0x9b) */
179 | new KeyboardUsage("Delete", (byte) 0x9c, '\0', true),
180 | /* ??? (0x9d - 0xb5) */
181 | new KeyboardUsage(KeyEvent.KEYCODE_NUMPAD_LEFT_PAREN, (byte) 0xb6, '('),
182 | new KeyboardUsage(KeyEvent.KEYCODE_NUMPAD_RIGHT_PAREN, (byte) 0xb7, ')'),
183 | /* ??? (0xb8 - 0xdf) */
184 |
185 | // Common + META keys
186 | new KeyboardUsage(KeyEvent.KEYCODE_AT, (byte) 0x1f, '@', META_LEFT_SHIFT),
187 | new KeyboardUsage(KeyEvent.KEYCODE_POUND, (byte) 0x20, '#', META_LEFT_SHIFT),
188 | new KeyboardUsage(KeyEvent.KEYCODE_STAR, (byte) 0x25, '*', META_LEFT_SHIFT),
189 | new KeyboardUsage(KeyEvent.KEYCODE_PLUS, (byte) 0x2e, '+', META_LEFT_SHIFT),
190 | // Polish letters
191 | new KeyboardUsage("ą", (byte) 0x04, 'a', META_RIGHT_ALT, true),
192 | new KeyboardUsage("ć", (byte) 0x06, 'c', META_RIGHT_ALT, true),
193 | new KeyboardUsage("ę", (byte) 0x08, 'e', META_RIGHT_ALT, true),
194 | new KeyboardUsage("ł", (byte) 0x0f, 'l', META_RIGHT_ALT, true),
195 | new KeyboardUsage("ń", (byte) 0x11, 'n', META_RIGHT_ALT, true),
196 | new KeyboardUsage("ó", (byte) 0x12, 'o', META_RIGHT_ALT, true),
197 | new KeyboardUsage("ś", (byte) 0x16, 's', META_RIGHT_ALT, true),
198 | new KeyboardUsage("ź", (byte) 0x1b, 'x', META_RIGHT_ALT, true),
199 | new KeyboardUsage("ż", (byte) 0x1d, 'z', META_RIGHT_ALT, true),
200 | };
201 | public final String description;
202 | final int key_code;
203 | final byte usage;
204 | final char character;
205 | final byte meta;
206 | final boolean non_keyboard;
207 |
208 | private KeyboardUsage(int kc, byte u, char c, byte m, boolean nk) {
209 | key_code = kc;
210 | usage = u;
211 | character = c;
212 | meta = m;
213 | non_keyboard = nk;
214 | description = "" + character;
215 | }
216 |
217 | private KeyboardUsage(String d, byte u, char c, byte m, boolean nk) {
218 | key_code = KeyEvent.KEYCODE_UNKNOWN;
219 | usage = u;
220 | character = c;
221 | meta = m;
222 | non_keyboard = nk;
223 | description = d;
224 | }
225 |
226 | private KeyboardUsage(int kc, byte u, char c, String d, boolean nk) {
227 | key_code = kc;
228 | usage = u;
229 | character = c;
230 | meta = (byte) 0;
231 | non_keyboard = nk;
232 | description = d;
233 | }
234 |
235 | private KeyboardUsage(String d, byte u, char c, boolean nk) {
236 | this(d, u, c, (byte) 0, nk);
237 | }
238 |
239 | private KeyboardUsage(int kc, byte u, char c, byte m) {
240 | this(kc, u, c, m, false);
241 | }
242 |
243 | private KeyboardUsage(int kc, byte u, char c) {
244 | this(kc, u, c, (byte) 0, false);
245 | }
246 |
247 | static public byte getUsage(String d) {
248 | for (KeyboardUsage KEYBOARD_USAGE : KEYBOARD_USAGES) {
249 | if (Objects.equals(KEYBOARD_USAGE.description, d)) {
250 | return KEYBOARD_USAGE.usage;
251 | }
252 | }
253 |
254 | return 0;
255 | }
256 |
257 | static public List getUsageNames() {
258 | List l = new ArrayList<>();
259 |
260 | for (KeyboardUsage KEYBOARD_USAGE : KEYBOARD_USAGES) {
261 | if (KEYBOARD_USAGE.non_keyboard) {
262 | l.add(KEYBOARD_USAGE.description);
263 | }
264 | }
265 |
266 | return l;
267 | }
268 | }
269 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/alek/ble_hid_example/HidBleService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018-2019 Aleksander Drewnicki
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 | package com.example.alek.ble_hid_example;
17 |
18 | import android.app.Service;
19 | import android.bluetooth.BluetoothAdapter;
20 | import android.bluetooth.BluetoothDevice;
21 | import android.bluetooth.BluetoothGatt;
22 | import android.bluetooth.BluetoothGattCharacteristic;
23 | import android.bluetooth.BluetoothGattDescriptor;
24 | import android.bluetooth.BluetoothGattServer;
25 | import android.bluetooth.BluetoothGattServerCallback;
26 | import android.bluetooth.BluetoothGattService;
27 | import android.bluetooth.BluetoothManager;
28 | import android.bluetooth.le.AdvertiseCallback;
29 | import android.bluetooth.le.AdvertiseData;
30 | import android.bluetooth.le.AdvertiseSettings;
31 | import android.bluetooth.le.BluetoothLeAdvertiser;
32 | import android.content.Context;
33 | import android.content.Intent;
34 | import android.os.BatteryManager;
35 | import android.os.Binder;
36 | import android.os.IBinder;
37 | import android.os.ParcelUuid;
38 | import android.util.Log;
39 |
40 | import java.util.ArrayList;
41 | import java.util.Arrays;
42 | import java.util.Objects;
43 | import java.util.UUID;
44 |
45 | import static android.bluetooth.BluetoothAdapter.STATE_CONNECTED;
46 | import static android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED;
47 | import static android.bluetooth.BluetoothGattCharacteristic.PERMISSION_READ;
48 | import static android.bluetooth.BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED;
49 | import static android.bluetooth.BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM;
50 | import static android.bluetooth.BluetoothGattCharacteristic.PERMISSION_WRITE;
51 | import static android.bluetooth.BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED;
52 | import static android.bluetooth.BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM;
53 | import static com.example.alek.ble_hid_example.UUIDs.CHAR_BATTERY_LEVEL;
54 | import static com.example.alek.ble_hid_example.UUIDs.CHAR_HID_CONTROL_POINT;
55 | import static com.example.alek.ble_hid_example.UUIDs.CHAR_HID_INFORMATION;
56 | import static com.example.alek.ble_hid_example.UUIDs.CHAR_PNP_ID;
57 | import static com.example.alek.ble_hid_example.UUIDs.CHAR_REPORT;
58 | import static com.example.alek.ble_hid_example.UUIDs.CHAR_REPORT_MAP;
59 | import static com.example.alek.ble_hid_example.UUIDs.DESC_CCC;
60 | import static com.example.alek.ble_hid_example.UUIDs.DESC_REPORT_REFERENCE;
61 | import static com.example.alek.ble_hid_example.UUIDs.SERVICE_BAS;
62 | import static com.example.alek.ble_hid_example.UUIDs.SERVICE_DIS;
63 | import static com.example.alek.ble_hid_example.UUIDs.SERVICE_HID;
64 |
65 | enum SendTo {
66 | SEND_TO_FIRST,
67 | SEND_TO_LAST,
68 | SEND_TO_ALL,
69 | }
70 |
71 | enum SecurityLevel {
72 | SECURITY_LEVEL_1, // None
73 | SECURITY_LEVEL_2, // Encryption
74 | SECURITY_LEVEL_3, // Authentication
75 | }
76 |
77 | enum ReportField {
78 | /* Consumer */
79 | REPORT_FIELD_CONSUMER_CONTROL(0, 2),
80 | REPORT_FIELD_LAUNCHER_BUTTON(2, 2),
81 | REPORT_FIELD_CONTROL_BUTTON(4, 2),
82 | /* Keyboard */
83 | REPORT_FIELD_KEYBOARD_META_KEYS(6, 1),
84 | REPORT_FIELD_KEYBOARD_KEYS(7, 1),
85 | REPORT_FIELD_KEYBOARD_ALL(6, 2), // REPORT_FIELD_KEYBOARD_META_KEYS + REPORT_FIELD_KEYBOARD_KEYS
86 | /* Mouse */
87 | REPORT_FIELD_MOUSE_BUTTONS(8, 1),
88 | REPORT_FIELD_MOUSE_X(9, 1),
89 | REPORT_FIELD_MOUSE_Y(10, 1),
90 | REPORT_FIELD_MOUSE_BUTTONS_XY(8, 3),
91 | REPORT_FIELD_MOUSE_XY(9, 2),
92 | REPORT_FIELD_MOUSE_SCROLL(11, 1);
93 |
94 | final static public int REP_CONSUMER = 0x01;
95 | final static public int REP_MOUSE = 0x02;
96 | final static public int REP_KEYBOARD = 0x04;
97 | final static public int REP_BASIC = 0x08;
98 | public final int byte_size;
99 | public int byte_offset;
100 |
101 | ReportField(int byte_offset, int byte_size) {
102 | this.byte_offset = byte_offset;
103 | this.byte_size = byte_size;
104 | }
105 |
106 | static void updateValues(int features) {
107 | /* Restore original value */
108 | REPORT_FIELD_CONSUMER_CONTROL.byte_offset = 0;
109 | REPORT_FIELD_LAUNCHER_BUTTON.byte_offset = 2;
110 | REPORT_FIELD_CONTROL_BUTTON.byte_offset = 4;
111 |
112 | REPORT_FIELD_KEYBOARD_META_KEYS.byte_offset = 6;
113 | REPORT_FIELD_KEYBOARD_KEYS.byte_offset = 7;
114 | REPORT_FIELD_KEYBOARD_ALL.byte_offset = 6;
115 |
116 | REPORT_FIELD_MOUSE_BUTTONS.byte_offset = 8;
117 | REPORT_FIELD_MOUSE_X.byte_offset = 9;
118 | REPORT_FIELD_MOUSE_Y.byte_offset = 10;
119 | REPORT_FIELD_MOUSE_BUTTONS_XY.byte_offset = 8;
120 | REPORT_FIELD_MOUSE_XY.byte_offset = 9;
121 | REPORT_FIELD_MOUSE_SCROLL.byte_offset = 11;
122 |
123 | if ((features & REP_CONSUMER) == 0) {
124 | REPORT_FIELD_CONSUMER_CONTROL.byte_offset = -1;
125 | REPORT_FIELD_LAUNCHER_BUTTON.byte_offset = -1;
126 | REPORT_FIELD_CONTROL_BUTTON.byte_offset = -1;
127 |
128 | REPORT_FIELD_KEYBOARD_META_KEYS.byte_offset -= 6;
129 | REPORT_FIELD_KEYBOARD_KEYS.byte_offset -= 6;
130 | REPORT_FIELD_KEYBOARD_ALL.byte_offset -= 6;
131 |
132 | REPORT_FIELD_MOUSE_BUTTONS.byte_offset -= 6;
133 | REPORT_FIELD_MOUSE_X.byte_offset -= 6;
134 | REPORT_FIELD_MOUSE_Y.byte_offset -= 6;
135 | REPORT_FIELD_MOUSE_BUTTONS_XY.byte_offset -= 6;
136 | REPORT_FIELD_MOUSE_XY.byte_offset -= 6;
137 | REPORT_FIELD_MOUSE_SCROLL.byte_offset -= 6;
138 | } else if ((features & REP_BASIC) == REP_BASIC) {
139 | REPORT_FIELD_LAUNCHER_BUTTON.byte_offset = -1;
140 | REPORT_FIELD_CONTROL_BUTTON.byte_offset = -1;
141 |
142 | REPORT_FIELD_KEYBOARD_META_KEYS.byte_offset -= 4;
143 | REPORT_FIELD_KEYBOARD_KEYS.byte_offset -= 4;
144 | REPORT_FIELD_KEYBOARD_ALL.byte_offset -= 4;
145 |
146 | REPORT_FIELD_MOUSE_BUTTONS.byte_offset -= 4;
147 | REPORT_FIELD_MOUSE_X.byte_offset -= 4;
148 | REPORT_FIELD_MOUSE_Y.byte_offset -= 4;
149 | REPORT_FIELD_MOUSE_BUTTONS_XY.byte_offset -= 4;
150 | REPORT_FIELD_MOUSE_XY.byte_offset -= 4;
151 | REPORT_FIELD_MOUSE_SCROLL.byte_offset -= 4;
152 | }
153 |
154 | if ((features & REP_KEYBOARD) == 0) {
155 | REPORT_FIELD_KEYBOARD_META_KEYS.byte_offset = -1;
156 | REPORT_FIELD_KEYBOARD_KEYS.byte_offset = -1;
157 | REPORT_FIELD_KEYBOARD_ALL.byte_offset = -1;
158 |
159 | REPORT_FIELD_MOUSE_BUTTONS.byte_offset -= 2;
160 | REPORT_FIELD_MOUSE_X.byte_offset -= 2;
161 | REPORT_FIELD_MOUSE_Y.byte_offset -= 2;
162 | REPORT_FIELD_MOUSE_BUTTONS_XY.byte_offset -= 2;
163 | REPORT_FIELD_MOUSE_XY.byte_offset -= 2;
164 | REPORT_FIELD_MOUSE_SCROLL.byte_offset -= 2;
165 | }
166 |
167 | if ((features & REP_MOUSE) == 0) {
168 | REPORT_FIELD_MOUSE_BUTTONS.byte_offset = -1;
169 | REPORT_FIELD_MOUSE_X.byte_offset = -1;
170 | REPORT_FIELD_MOUSE_Y.byte_offset = -1;
171 | REPORT_FIELD_MOUSE_BUTTONS_XY.byte_offset = -1;
172 | REPORT_FIELD_MOUSE_XY.byte_offset = -1;
173 | REPORT_FIELD_MOUSE_SCROLL.byte_offset = -1;
174 | }
175 | }
176 | }
177 |
178 | class NotificationData {
179 | public final byte[] value;
180 | public final BluetoothDevice device;
181 | public final BluetoothGattCharacteristic characteristic;
182 | public final boolean responseNeeded;
183 |
184 | NotificationData(BluetoothDevice device, BluetoothGattCharacteristic characteristic, byte[] value) {
185 | this.device = device;
186 | this.characteristic = characteristic;
187 | this.value = value;
188 | this.responseNeeded = false;
189 | }
190 | }
191 |
192 | public class HidBleService extends Service {
193 | private final IBinder mBinder = new LocalBinder();
194 | private final ArrayList devices = new ArrayList<>();
195 | private final ArrayList pendingNotifications = new ArrayList<>();
196 | /* Call proper methods on some BLE events */
197 | private MainActivity mainActivity;
198 | private BluetoothGattServerCallback mGattServerCallback;
199 | private boolean notificationPossible;
200 | private BluetoothGattServer gattServer;
201 | private Thread check_thread = null;
202 | private final AdvertiseCallback advertisingCallback = new AdvertiseCallback() {
203 | @Override
204 | public void onStartSuccess(AdvertiseSettings settingsInEffect) {
205 | Log.i("BLE", "Advertisement started successfully");
206 | }
207 |
208 | @Override
209 | public void onStartFailure(int errorCode) {
210 | Log.i("BLE", "Advertisement not started - error: " + errorCode);
211 | }
212 | };
213 |
214 | private byte readBatteryLevel() {
215 | BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
216 | int batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
217 |
218 | return (byte) batteryLevel;
219 | }
220 |
221 | public void sendNotification(ReportField rf, int value) {
222 | sendNotification(rf, value, SendTo.SEND_TO_ALL);
223 | }
224 |
225 | private void sendNotification(ReportField rf, int value, SendTo st) {
226 | // Assume one report characteristic or that the notification should be sent from the first
227 | BluetoothGattCharacteristic report;
228 | byte[] array = new byte[rf.byte_offset + rf.byte_size];
229 |
230 | if (devices.size() == 0) {
231 | return;
232 | }
233 |
234 | if (rf.byte_offset < 0) {
235 | return;
236 | }
237 |
238 | report = gattServer.getService(UUID.fromString(UUIDs.SERVICE_HID)).getCharacteristic(
239 | UUID.fromString(UUIDs.CHAR_REPORT));
240 |
241 | Arrays.fill(array, (byte) 0);
242 |
243 | for (int i = rf.byte_offset; i < rf.byte_offset + rf.byte_size; i++) {
244 | array[i] = (byte) (value & 0xff);
245 | value >>= 8;
246 | }
247 |
248 | switch (st) {
249 | case SEND_TO_FIRST:
250 | pendingNotifications.add(new NotificationData(devices.get(0), report, array));
251 | break;
252 | case SEND_TO_LAST:
253 | pendingNotifications.add(new NotificationData(devices.get(devices.size() - 1),
254 | report, array));
255 | break;
256 | case SEND_TO_ALL:
257 | for (int i = 0; i < devices.size(); i++) {
258 | pendingNotifications.add(new NotificationData(devices.get(i), report, array
259 | ));
260 | }
261 | break;
262 | }
263 |
264 | if (notificationPossible) {
265 | NotificationData toSend = pendingNotifications.remove(0);
266 | toSend.characteristic.setValue(toSend.value);
267 | gattServer.notifyCharacteristicChanged(toSend.device, toSend.characteristic,
268 | toSend.responseNeeded);
269 | notificationPossible = false;
270 | return;
271 | }
272 |
273 | if (check_thread != null) {
274 | return;
275 | }
276 |
277 | check_thread = new Thread() {
278 | public void run() {
279 | NotificationData toSend;
280 |
281 | while (!notificationPossible) {
282 | if (devices.size() == 0) {
283 | pendingNotifications.clear();
284 | return;
285 | }
286 | }
287 |
288 | if (pendingNotifications.size() < 1 || devices.size() == 0) {
289 | check_thread = null;
290 | return;
291 | }
292 |
293 | toSend = pendingNotifications.remove(0);
294 |
295 | if (devices.contains(toSend.device)) {
296 | /* Device could disconnect in the mean time */
297 | toSend.characteristic.setValue(toSend.value);
298 | gattServer.notifyCharacteristicChanged(toSend.device, toSend.characteristic,
299 | toSend.responseNeeded);
300 | }
301 |
302 | notificationPossible = false;
303 | }
304 | };
305 | check_thread.start();
306 | }
307 |
308 | public void sendNotification(String s) {
309 | sendNotification(s, SendTo.SEND_TO_ALL);
310 | }
311 |
312 | private void sendNotification(String s, SendTo st) {
313 | for (int i = 0; i < s.length(); i++) {
314 | char c = s.charAt(i);
315 |
316 | for (int j = 0; j < KeyboardUsage.KEYBOARD_USAGES.length; j++) {
317 | short val;
318 | byte m;
319 | byte k;
320 |
321 | if (Character.toLowerCase(c) == KeyboardUsage.KEYBOARD_USAGES[j].character) {
322 | m = KeyboardUsage.KEYBOARD_USAGES[j].meta;
323 | k = KeyboardUsage.KEYBOARD_USAGES[j].usage;
324 |
325 | if (Character.isLetter(c) && Character.isUpperCase(c)) {
326 | m |= KeyboardUsage.META_LEFT_SHIFT;
327 | }
328 |
329 | val = (short) (m + (k << 8));
330 | sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, (int) val, st);
331 | sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, 0, st);
332 | break;
333 | }
334 | }
335 | }
336 |
337 | sendNotification(ReportField.REPORT_FIELD_KEYBOARD_ALL, 0, st);
338 | }
339 |
340 | private void startAdvertising() {
341 | BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
342 | BluetoothLeAdvertiser advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
343 | AdvertiseSettings settings = new AdvertiseSettings.Builder()
344 | .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
345 | .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
346 | .setConnectable(true)
347 | .build();
348 | AdvertiseData advData = new AdvertiseData.Builder()
349 | .setIncludeDeviceName(true)
350 | // Human Interface Device Service's UUID
351 | .addServiceUuid(new ParcelUuid(UUID.fromString(SERVICE_HID)))
352 | // Device Information Service's UUID
353 | .addServiceUuid(new ParcelUuid(UUID.fromString(SERVICE_DIS)))
354 | // Battery Service's UUID
355 | .addServiceUuid(new ParcelUuid(UUID.fromString(SERVICE_BAS)))
356 | .build();
357 |
358 | //bluetoothAdapter.setName(deviceName);
359 | advertiser.startAdvertising(settings, advData, advertisingCallback);
360 | }
361 |
362 | private void createGattDatabase(BluetoothGattServer gattServer, int level, int features) {
363 | // Set characteristics' permissions
364 | final int PERM_READ = (level == SecurityLevel.SECURITY_LEVEL_3.ordinal()) ?
365 | PERMISSION_READ_ENCRYPTED_MITM : ((level == SecurityLevel.SECURITY_LEVEL_2.ordinal()) ?
366 | PERMISSION_READ_ENCRYPTED : PERMISSION_READ);
367 | final int PERM_WRITE = (level == SecurityLevel.SECURITY_LEVEL_3.ordinal()) ?
368 | PERMISSION_WRITE_ENCRYPTED_MITM : ((level == SecurityLevel.SECURITY_LEVEL_2.ordinal()) ?
369 | PERMISSION_WRITE_ENCRYPTED : PERMISSION_WRITE);
370 | final int PERM_READ_WRITE = PERM_READ | PERM_WRITE;
371 |
372 | // Clear current attributes database - avoid adding the same services to database
373 | gattServer.clearServices();
374 |
375 | ////////////////////////////////////////////////////////////////////////////////////////////
376 | // HID Service
377 | // -> Report Map
378 | // -> HID Information
379 | // -> HID Control Point
380 | // -> Report
381 | // -> Client Characteristic Configuration
382 | // -> Report Reference
383 | // ... (another Report characteristics and their descriptors)
384 | ////////////////////////////////////////////////////////////////////////////////////////////
385 | // Report Map - for basic mode
386 | final byte REPORT_MAP_BASIC[] = {
387 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
388 | (byte) 0x09, (byte) 0x01, /* Usage (Consumer Control) */
389 | (byte) 0xA1, (byte) 0x01, /* Collection (Application) */
390 | (byte) 0x85, (byte) 0x02, /* Report ID=2 */
391 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
392 | (byte) 0x15, (byte) 0x00, /* Logical Minimum (0) */
393 | (byte) 0x25, (byte) 0x01, /* Logical Maximum (1) */
394 | (byte) 0x75, (byte) 0x01, /* Report Size (1) */
395 | (byte) 0x95, (byte) 0x0B, /* Report Count (11) */
396 |
397 | (byte) 0x09, (byte) 0x6F, /* 1 Usage (Bright Up) */
398 | (byte) 0x09, (byte) 0x70, /* 2 Usage (Bright Down) */
399 |
400 | (byte) 0x09, (byte) 0xB5, /* 3 Usage (Scan Next Track) */
401 | (byte) 0x09, (byte) 0xB6, /* 4 Usage (Scan Previous Track) */
402 | (byte) 0x09, (byte) 0xB7, /* 5 Usage (Stop) */
403 | (byte) 0x09, (byte) 0xCD, /* 6 Usage (Play / Pause) */
404 |
405 | (byte) 0x09, (byte) 0xE2, /* 7 Usage (Mute) */
406 | (byte) 0x09, (byte) 0xE9, /* 8 Usage (Volume Up) */
407 | (byte) 0x09, (byte) 0xEA, /* 9 Usage (Volume Down) */
408 |
409 | (byte) 0x09, (byte) 0xB8, /* 10 Usage (Eject) */
410 | (byte) 0x09, (byte) 0xb8, /* 11 Usage (Snapshot) */
411 |
412 | (byte) 0x81, (byte) 0x02, /* Input (Data, Variable, Absolute) */
413 | (byte) 0x95, (byte) 0x05, /* Report Count (5) */
414 | (byte) 0x81, (byte) 0x01, /* Input (Constant) */
415 | (byte) 0xC0,
416 | };
417 |
418 | // Report Map - concatenation of few arrays
419 | final byte REPORT_MAP_START[] = {
420 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
421 | (byte) 0x09, (byte) 0x01, /* Usage (Consumer Control) */
422 | (byte) 0xA1, (byte) 0x01, /* Collection (Application) */
423 | (byte) 0x85, (byte) 0x02, /* Report ID=2 */
424 | };
425 | final byte REPORT_MAP_CONSUMER[] =
426 | ((features & ReportField.REP_CONSUMER) == ReportField.REP_CONSUMER) ? new byte[]{
427 | /*========================== Consumer control ==========================*/
428 | (byte) 0xA1, (byte) 0x02, /* Collection (Logical) */
429 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
430 | (byte) 0x15, (byte) 0x00, /* Logical Minimum (0) */
431 | (byte) 0x25, (byte) 0x01, /* Logical Maximum (1) */
432 | (byte) 0x75, (byte) 0x01, /* Report Size (1) */
433 | (byte) 0x95, (byte) 0x10, /* Report Count (16) */
434 |
435 | (byte) 0x09, (byte) 0x6F, /* 1 Usage (Bright Up) */
436 | (byte) 0x09, (byte) 0x70, /* 2 Usage (Bright Down) */
437 |
438 | (byte) 0x09, (byte) 0xB5, /* 3 Usage (Scan Next Track) */
439 | (byte) 0x09, (byte) 0xB6, /* 4 Usage (Scan Previous Track) */
440 | (byte) 0x09, (byte) 0xB7, /* 5 Usage (Stop) */
441 | (byte) 0x09, (byte) 0xCD, /* 6 Usage (Play / Pause) */
442 |
443 | (byte) 0x09, (byte) 0xE2, /* 7 Usage (Mute) */
444 | (byte) 0x09, (byte) 0xE9, /* 8 Usage (Volume Up) */
445 | (byte) 0x09, (byte) 0xEA, /* 9 Usage (Volume Down) */
446 |
447 | (byte) 0x09, (byte) 0xB8, /* 10 Usage (Eject) */
448 | (byte) 0x09, (byte) 0x65, /* 11 Usage (Snapshot) */
449 |
450 | (byte) 0x05, (byte) 0x01, /* Usage Page (Generic Desktop) */
451 | (byte) 0x09, (byte) 0x82, /* 12 Usage (System Sleep) */
452 | (byte) 0x09, (byte) 0xA8, /* 13 Usage (System Hibernate) */
453 | (byte) 0x09, (byte) 0x81, /* 14 Usage (System Power Down) */
454 | (byte) 0x09, (byte) 0x8E, /* 15 Usage (System Cold Restart) */
455 | (byte) 0x09, (byte) 0x8F, /* 16 Usage (System Warm Restart) */
456 |
457 | (byte) 0x81, (byte) 0x02, /* Input (Data, Variable, Absolute) */
458 | // (byte) 0x95, (byte) 0x00, /* Report Count (1) */
459 | // (byte) 0x81, (byte) 0x01, /* Input (Constant) */
460 |
461 | /*==================== Application Launcher Buttons ====================*/
462 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
463 | (byte) 0x95, (byte) 0x01, /* Report Count (1) */
464 | (byte) 0x75, (byte) 0x10, /* Report Size (16) */
465 | (byte) 0x16, (byte) 0x81, (byte) 0x01, /* Logical Minimum (385) */
466 | (byte) 0x26, (byte) 0xC7, (byte) 0x01, /* Logical Maximum (455) */
467 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
468 | (byte) 0x1a, (byte) 0x81, (byte) 0x01, /* Usage Minimum (385) */
469 | (byte) 0x2a, (byte) 0xC7, (byte) 0x01, /* Usage Maximum (455) */
470 | (byte) 0x81, (byte) 0x00, /* Input (Data, Array) */
471 |
472 | /*==================== Application Control Buttons =====================*/
473 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
474 | (byte) 0x95, (byte) 0x01, /* Report Count (1) */
475 | (byte) 0x75, (byte) 0x10, /* Report Size (16) */
476 | (byte) 0x16, (byte) 0x01, (byte) 0x02, /* Logical Minimum (385) */
477 | (byte) 0x26, (byte) 0x9C, (byte) 0x02, /* Logical Maximum (455) */
478 | (byte) 0x05, (byte) 0x0C, /* Usage Page (Consumer Devices) */
479 | (byte) 0x1a, (byte) 0x01, (byte) 0x02, /* Usage Minimum (385) */
480 | (byte) 0x2a, (byte) 0x9C, (byte) 0x02, /* Usage Maximum (455) */
481 | (byte) 0x81, (byte) 0x00, /* Input (Data, Array) */
482 | (byte) 0xC0, /* End Collection */
483 | } : new byte[]{};
484 | final byte REPORT_MAP_KEYBOARD[] =
485 | ((features & ReportField.REP_KEYBOARD) == ReportField.REP_KEYBOARD) ? new byte[]{
486 | /*============================== Keyboard ==============================*/
487 | (byte) 0x05, (byte) 0x07, /* Usage Page (Keyboard/Keypad) */
488 | (byte) 0x15, (byte) 0x00, /* Logical Minimum (0) */
489 | (byte) 0x25, (byte) 0x01, /* Logical Maximum (1) */
490 | (byte) 0x75, (byte) 0x01, /* Report Size (1) */
491 | (byte) 0x95, (byte) 0x08, /* Report Count (8) */
492 |
493 | (byte) 0x09, (byte) 0xE0, /* 1 Usage (LeftControl) */
494 | (byte) 0x09, (byte) 0xE1, /* 2 Usage (LeftShift) */
495 | (byte) 0x09, (byte) 0xE2, /* 3 Usage (LeftAlt) */
496 | (byte) 0x09, (byte) 0xE3, /* 4 Usage (LeftGUI) */
497 | (byte) 0x09, (byte) 0xE4, /* 5 Usage (RightControl) */
498 | (byte) 0x09, (byte) 0xE5, /* 6 Usage (RightShift) */
499 | (byte) 0x09, (byte) 0xE6, /* 7 Usage (RightAlt) */
500 | (byte) 0x09, (byte) 0xE7, /* 8 Usage (RightGUI) */
501 | (byte) 0x81, (byte) 0x02, /* Input (Data, Variable, Absolute) */
502 |
503 | (byte) 0x05, (byte) 0x07, /* Usage Page (Keyboard/Keypad) */
504 | (byte) 0x95, (byte) 0x01, /* Report Count (1) */
505 | (byte) 0x75, (byte) 0x08, /* Report Size (8) */
506 | (byte) 0x15, (byte) 0x04, /* Logical Minimum (4) */
507 | (byte) 0x25, (byte) 0xDF, /* Logical Maximum (223) */
508 | (byte) 0x05, (byte) 0x07, /* Usage Page (Key codes) */
509 | (byte) 0x19, (byte) 0x04, /* Usage Minimum (4) */
510 | (byte) 0x29, (byte) 0xDF, /* Usage Maximum (223) */
511 | (byte) 0x81, (byte) 0x00, /* Input (Data, Array) */
512 | } : new byte[]{};
513 | final byte REPORT_MAP_MOUSE[] =
514 | ((features & ReportField.REP_MOUSE) == ReportField.REP_MOUSE) ? new byte[]{
515 | /*================================ Mouse ===============================*/
516 | (byte) 0x05, (byte) 0x01, /* Usage Page (Generic Desktop) */
517 | (byte) 0x09, (byte) 0x02, /* Usage (Mouse) */
518 | (byte) 0xa1, (byte) 0x01, /* Collection (Application) */
519 | (byte) 0x85, (byte) 0x02,
520 | (byte) 0x09, (byte) 0x01, /* Usage (Consumer Control) */
521 | (byte) 0xa1, (byte) 0x00, /* Collection (Physical) */
522 | (byte) 0x05, (byte) 0x09, /* Usage Page (Button) */
523 | (byte) 0x19, (byte) 0x01, /* Usage Minimum (1) */
524 | (byte) 0x29, (byte) 0x05, /* Usage Maximum (5) */
525 | (byte) 0x15, (byte) 0x00, /* Logical Minimum (0) */
526 | (byte) 0x25, (byte) 0x01, /* Logical Maximum (1) */
527 | (byte) 0x95, (byte) 0x05, /* Report Count (5) */
528 | (byte) 0x75, (byte) 0x01, /* Report Size (1) */
529 | (byte) 0x81, (byte) 0x02, /* Input (Variable, Absolute) */
530 |
531 | (byte) 0x95, (byte) 0x01, /* Report Count (1) */
532 | (byte) 0x75, (byte) 0x03, /* Report Size (3) */
533 | (byte) 0x81, (byte) 0x01, /* Input (Constant) */
534 |
535 | (byte) 0x05, (byte) 0x01, /* Usage Page (Generic Desktop) */
536 | (byte) 0x09, (byte) 0x30, /* Usage (X) */
537 | (byte) 0x09, (byte) 0x31, /* Usage (Y) */
538 | (byte) 0x15, (byte) 0x81, /* Logical Minimum (-127) */
539 | (byte) 0x25, (byte) 0x7f, /* Logical Maximum (127) */
540 | (byte) 0x75, (byte) 0x08, /* Report Size (8) */
541 | (byte) 0x95, (byte) 0x02, /* Report Count (2) */
542 | (byte) 0x81, (byte) 0x06, /* Input (Variable, Relative) */
543 |
544 | (byte) 0x09, (byte) 0x38, /* Usage (Wheel) */
545 | (byte) 0x15, (byte) 0x81, /* Logical Minimum (-127) */
546 | (byte) 0x25, (byte) 0x7f, /* Logical Maximum (127) */
547 | (byte) 0x75, (byte) 0x08, /* Report Size (8) */
548 | (byte) 0x95, (byte) 0x01, /* Report Count (1) */
549 | (byte) 0x81, (byte) 0x06, /* Input (Variable, Relative) */
550 | (byte) 0xC0, /* End Collection */
551 | (byte) 0xC0, /* End Collection */
552 | } : new byte[]{};
553 | final byte REPORT_MAP_END[] = {
554 | (byte) 0xC0, /* End Collection */
555 | };
556 |
557 | int position = 0;
558 | byte REPORT_MAP[];
559 |
560 |
561 | if ((features & ReportField.REP_BASIC) == ReportField.REP_BASIC) {
562 | REPORT_MAP = REPORT_MAP_BASIC;
563 | } else {
564 | REPORT_MAP = new byte[REPORT_MAP_START.length + REPORT_MAP_CONSUMER.length +
565 | REPORT_MAP_KEYBOARD.length + REPORT_MAP_MOUSE.length + REPORT_MAP_END.length];
566 |
567 | System.arraycopy(REPORT_MAP_START, 0, REPORT_MAP, position, REPORT_MAP_START.length);
568 | position += REPORT_MAP_START.length;
569 | System.arraycopy(REPORT_MAP_CONSUMER, 0, REPORT_MAP, position, REPORT_MAP_CONSUMER.length);
570 | position += REPORT_MAP_CONSUMER.length;
571 | System.arraycopy(REPORT_MAP_KEYBOARD, 0, REPORT_MAP, position, REPORT_MAP_KEYBOARD.length);
572 | position += REPORT_MAP_KEYBOARD.length;
573 | System.arraycopy(REPORT_MAP_MOUSE, 0, REPORT_MAP, position, REPORT_MAP_MOUSE.length);
574 | position += REPORT_MAP_MOUSE.length;
575 | System.arraycopy(REPORT_MAP_END, 0, REPORT_MAP, position, REPORT_MAP_END.length);
576 | }
577 |
578 |
579 | // HID Service
580 | BluetoothGattService serviceHid = new BluetoothGattService(UUID.fromString(SERVICE_HID),
581 | BluetoothGattService.SERVICE_TYPE_PRIMARY);
582 |
583 | // Report Map characteristic
584 | BluetoothGattCharacteristic charReportMap = new BluetoothGattCharacteristic(
585 | UUID.fromString(CHAR_REPORT_MAP),
586 | BluetoothGattCharacteristic.PROPERTY_READ, PERM_READ);
587 |
588 | charReportMap.setValue(REPORT_MAP);
589 |
590 | // HID Information characteristic
591 | BluetoothGattCharacteristic charHidInformation = new BluetoothGattCharacteristic(
592 | UUID.fromString(CHAR_HID_INFORMATION),
593 | BluetoothGattCharacteristic.PROPERTY_READ, PERM_READ);
594 |
595 | charHidInformation.setValue(new byte[]{0x01, 0x11, 0x00, 0x03});
596 |
597 | // HID Control Point characteristic
598 | BluetoothGattCharacteristic charHidControlPoint = new BluetoothGattCharacteristic(
599 | UUID.fromString(CHAR_HID_CONTROL_POINT),
600 | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, PERM_WRITE);
601 |
602 | charHidControlPoint.setValue("\0".getBytes());
603 |
604 | // Report characteristic
605 | BluetoothGattCharacteristic charReport1 = new BluetoothGattCharacteristic(
606 | UUID.fromString(CHAR_REPORT),
607 | BluetoothGattCharacteristic.PROPERTY_READ |
608 | BluetoothGattCharacteristic.PROPERTY_NOTIFY, PERM_READ_WRITE);
609 |
610 | charReport1.setValue("\0\0".getBytes());
611 |
612 | /// Report Reference descriptor
613 | BluetoothGattDescriptor descReportReference1 = new BluetoothGattDescriptor(
614 | UUID.fromString(DESC_REPORT_REFERENCE), PERM_READ);
615 |
616 | descReportReference1.setValue("\2\1".getBytes());
617 |
618 | /// Client Characteristic Configuration descriptor
619 | BluetoothGattDescriptor descCCC1 = new BluetoothGattDescriptor(
620 | UUID.fromString(DESC_CCC), PERM_READ_WRITE);
621 |
622 | descCCC1.setValue("\0\0".getBytes());
623 |
624 | charReport1.addDescriptor(descReportReference1);
625 | charReport1.addDescriptor(descCCC1);
626 |
627 | serviceHid.addCharacteristic(charReportMap);
628 | serviceHid.addCharacteristic(charHidInformation);
629 | serviceHid.addCharacteristic(charHidControlPoint);
630 | serviceHid.addCharacteristic(charReport1);
631 | gattServer.addService(serviceHid);
632 | ////////////////////////////////////////////////////////////////////////////////////////////
633 | // Device Information Service
634 | // -> PnP ID
635 | ////////////////////////////////////////////////////////////////////////////////////////////
636 | BluetoothGattService serviceDIS = new BluetoothGattService(UUID.fromString(SERVICE_DIS),
637 | BluetoothGattService.SERVICE_TYPE_PRIMARY);
638 |
639 | // PnP ID characteristic
640 | BluetoothGattCharacteristic charPnpId = new BluetoothGattCharacteristic(
641 | UUID.fromString(CHAR_PNP_ID),
642 | BluetoothGattCharacteristic.PROPERTY_READ, PERM_READ);
643 |
644 | charPnpId.setValue("\2\0\0\0\0\0\0".getBytes());
645 | serviceDIS.addCharacteristic(charPnpId);
646 | gattServer.addService(serviceDIS);
647 | ////////////////////////////////////////////////////////////////////////////////////////////
648 | // Battery Service
649 | // -> Battery Level
650 | ////////////////////////////////////////////////////////////////////////////////////////////
651 | BluetoothGattService serviceBAS = new BluetoothGattService(UUID.fromString(SERVICE_BAS),
652 | BluetoothGattService.SERVICE_TYPE_PRIMARY);
653 |
654 | // PBattery Level characteristic
655 | BluetoothGattCharacteristic charBatteryLevel = new BluetoothGattCharacteristic(
656 | UUID.fromString(CHAR_BATTERY_LEVEL),
657 | BluetoothGattCharacteristic.PROPERTY_READ, PERM_READ);
658 |
659 | charBatteryLevel.setValue(new byte[]{readBatteryLevel()});
660 | serviceBAS.addCharacteristic(charBatteryLevel);
661 | gattServer.addService(serviceBAS);
662 | }
663 |
664 | private void gattServerCbInit() {
665 | mGattServerCallback = new BluetoothGattServerCallback() {
666 | private final int DEFAULT_MTU = 23;
667 | private int currentMtu = DEFAULT_MTU;
668 |
669 | @Override
670 | public void onConnectionStateChange(final BluetoothDevice device, int status, int newState) {
671 | Log.e("BLE", "onConnectionStateChange " + device.toString() + " " + status + " " + newState);
672 |
673 | if (newState == STATE_CONNECTED) {
674 | currentMtu = DEFAULT_MTU;
675 |
676 | if (!devices.contains(device)) {
677 | devices.add(device);
678 | }
679 |
680 | if (devices.size() == 1) {
681 | notificationPossible = true;
682 | }
683 |
684 | BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
685 | BluetoothLeAdvertiser advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
686 |
687 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
688 | ApplicationConfiguration.FORCE_BOND_FEAT)) {
689 | if (device.getBondState() != BluetoothDevice.BOND_BONDING &&
690 | device.getBondState() != BluetoothDevice.BOND_BONDED) {
691 | device.createBond();
692 | } else if (device.getBondState() == BluetoothDevice.BOND_BONDING) {
693 | device.setPairingConfirmation(true);
694 | }
695 | }
696 | } else if (newState == STATE_DISCONNECTED) {
697 | if (devices.contains(device)) {
698 | // If some notification waiting for this device then they will be removed in
699 | // proper task
700 | devices.remove(device);
701 | }
702 |
703 | if (devices.size() == 0) {
704 | notificationPossible = false;
705 | }
706 | }
707 |
708 | if (mainActivity != null) {
709 | mainActivity.onConnectionStateChange(devices);
710 | }
711 | }
712 |
713 | @Override
714 | public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
715 | BluetoothGattCharacteristic characteristic) {
716 | super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
717 | int charLength = characteristic.getValue().length;
718 | int partLength = (currentMtu > charLength - offset) ? charLength - offset : currentMtu;
719 | byte bytes[] = new byte[partLength];
720 |
721 | if (Objects.equals(characteristic.getUuid().toString(), CHAR_BATTERY_LEVEL)) {
722 | characteristic.setValue(new byte[]{readBatteryLevel()});
723 | }
724 |
725 | for (int i = 0; i < partLength; i++) {
726 | bytes[i] = characteristic.getValue()[i + offset];
727 | }
728 |
729 | gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, bytes);
730 |
731 | Log.e("BLE", "onCharacteristicReadRequest " + characteristic.getUuid().toString() +
732 | " offset " + offset + " " + new String(bytes));
733 | }
734 |
735 | @Override
736 | public void onMtuChanged(BluetoothDevice device, int mtu) {
737 | currentMtu = mtu;
738 | }
739 |
740 | @Override
741 | public void onDescriptorWriteRequest(final BluetoothDevice device, int requestId,
742 | BluetoothGattDescriptor descriptor,
743 | boolean preparedWrite, boolean responseNeeded,
744 | int offset, byte[] value) {
745 | Log.e("BLE", "onDescriptorWriteRequest " + descriptor.getUuid().toString() + "value"
746 | + value[0] + value[1]);
747 | descriptor.setValue(value);
748 | gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, value);
749 | }
750 |
751 | @Override
752 | public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
753 | BluetoothGattCharacteristic characteristic,
754 | boolean preparedWrite, boolean responseNeeded,
755 | int offset, byte[] value) {
756 | Log.e("BLE", "onCharacteristicWriteRequest " + characteristic.getUuid().toString() +
757 | " offset " + offset);
758 | characteristic.setValue(value);
759 | gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, value);
760 | }
761 |
762 | @Override
763 | public void onDescriptorReadRequest(BluetoothDevice device, int requestId,
764 | int offset, BluetoothGattDescriptor descriptor) {
765 | Log.e("BLE", "onDescriptorReadRequest " + descriptor.getUuid().toString());
766 | gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, descriptor.getValue());
767 | }
768 |
769 | @Override
770 | public void onNotificationSent(BluetoothDevice device, int status) {
771 | Log.e("BLE", "onNotificationSent - left: " + pendingNotifications.size());
772 | if (pendingNotifications.size() > 0) {
773 | NotificationData toSend = pendingNotifications.remove(0);
774 | toSend.characteristic.setValue(toSend.value);
775 | gattServer.notifyCharacteristicChanged(toSend.device, toSend.characteristic,
776 | toSend.responseNeeded);
777 | notificationPossible = false;
778 | } else {
779 | notificationPossible = true;
780 | }
781 | }
782 | };
783 | }
784 |
785 | public ArrayList getDevices() {
786 | return devices;
787 | }
788 |
789 | public void setActivity(MainActivity ma) {
790 | mainActivity = ma;
791 | }
792 |
793 | /* Service handling-related methods */
794 | public void initializeLE() {
795 | BluetoothManager mManager;
796 | int features = 0;
797 |
798 | if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
799 | BluetoothAdapter.getDefaultAdapter().enable();
800 | while (true) {
801 | if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
802 | break;
803 | }
804 | }
805 | //TODO: Add timeout
806 | }
807 |
808 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
809 | ApplicationConfiguration.CONSUMER_FEAT)) {
810 | features |= ReportField.REP_CONSUMER;
811 | }
812 |
813 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
814 | ApplicationConfiguration.MOUSE_FEAT)) {
815 | features |= ReportField.REP_MOUSE;
816 | }
817 |
818 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
819 | ApplicationConfiguration.KEYBOARD_FEAT)) {
820 | features |= ReportField.REP_KEYBOARD;
821 | }
822 |
823 | if (ApplicationConfiguration.getConfigurationField(getApplicationContext(),
824 | ApplicationConfiguration.BASIC_FEAT)) {
825 | features |= ReportField.REP_BASIC;
826 | }
827 |
828 | ReportField.updateValues(features);
829 | gattServerCbInit();
830 | mManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
831 | gattServer = mManager.openGattServer(getBaseContext(), mGattServerCallback);
832 | createGattDatabase(gattServer, SecurityLevel.SECURITY_LEVEL_2.ordinal(), features);
833 | pendingNotifications.clear();
834 | startAdvertising();
835 | }
836 |
837 | @Override
838 | public void onCreate() {
839 | super.onCreate();
840 |
841 | initializeLE();
842 | }
843 |
844 | @Override
845 | public IBinder onBind(Intent intent) {
846 | return mBinder;
847 | }
848 |
849 | @Override
850 | public boolean onUnbind(Intent intent) {
851 | mainActivity = null;
852 | return false;
853 | }
854 |
855 | public class LocalBinder extends Binder {
856 | HidBleService getService() {
857 | return HidBleService.this;
858 | }
859 | }
860 | }
--------------------------------------------------------------------------------