├── bluetooth-spp-terminal
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_action_device_bluetooth.png
│ │ │ └── ic_action_device_bluetooth_connected.png
│ │ ├── drawable-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_action_device_bluetooth.png
│ │ │ └── ic_action_device_bluetooth_connected.png
│ │ ├── drawable-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── ic_action_device_bluetooth.png
│ │ │ └── ic_action_device_bluetooth_connected.png
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── styles.xml
│ │ │ ├── arrays.xml
│ │ │ ├── preferences.xml
│ │ │ └── strings.xml
│ │ ├── drawable-xxhdpi
│ │ │ ├── ic_action_device_bluetooth.png
│ │ │ └── ic_action_device_bluetooth_connected.png
│ │ ├── drawable-xxxhdpi
│ │ │ ├── ic_action_device_bluetooth.png
│ │ │ └── ic_action_device_bluetooth_connected.png
│ │ ├── layout
│ │ │ ├── device_list.xml
│ │ │ ├── device_name.xml
│ │ │ └── activity_terminal.xml
│ │ ├── menu
│ │ │ └── device_control_activity.xml
│ │ ├── values-ru
│ │ │ └── strings.xml
│ │ └── xml
│ │ │ └── settings_activity.xml
│ │ ├── java
│ │ └── ru
│ │ │ └── sash0k
│ │ │ └── bluetooth_terminal
│ │ │ ├── Const.java
│ │ │ ├── DeviceData.java
│ │ │ ├── activity
│ │ │ ├── SettingsActivity.java
│ │ │ ├── BaseActivity.java
│ │ │ └── DeviceControlActivity.java
│ │ │ ├── bluetooth
│ │ │ ├── DeviceListActivity.java
│ │ │ ├── BluetoothUtils.java
│ │ │ └── DeviceConnector.java
│ │ │ └── Utils.java
│ │ └── AndroidManifest.xml
├── build.gradle
└── proguard-rules.txt
├── settings.gradle
├── fastlane
└── metadata
│ └── android
│ ├── en-US
│ ├── full_description.txt
│ ├── changelogs
│ │ └── 4.txt
│ ├── short_description.txt
│ └── images
│ │ ├── icon.png
│ │ └── phoneScreenshots
│ │ ├── 1.png
│ │ └── 2.png
│ └── ru
│ ├── short_description.txt
│ ├── changelogs
│ └── 4.txt
│ └── full_description.txt
├── icon.xcf
├── .idea
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── vcs.xml
├── compiler.xml
├── gradle.xml
├── jarRepositories.xml
├── modules.xml
└── misc.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── Bluetooth-spp-terminal.iml
├── bluetooth-spp-terminal.iml
├── gradle.properties
├── README.md
├── gradlew
└── LICENSE
/bluetooth-spp-terminal/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':bluetooth-spp-terminal'
2 |
--------------------------------------------------------------------------------
/fastlane/metadata/android/en-US/full_description.txt:
--------------------------------------------------------------------------------
1 | ./short_description.txt
--------------------------------------------------------------------------------
/icon.xcf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/icon.xcf
--------------------------------------------------------------------------------
/fastlane/metadata/android/en-US/changelogs/4.txt:
--------------------------------------------------------------------------------
1 | * fix: permissions for Android 12+
2 | * feat: material theme
--------------------------------------------------------------------------------
/fastlane/metadata/android/en-US/short_description.txt:
--------------------------------------------------------------------------------
1 | Terminal for Bluetooth SPP devices (HC-05, HC-06 and others)
--------------------------------------------------------------------------------
/fastlane/metadata/android/ru/short_description.txt:
--------------------------------------------------------------------------------
1 | Терминал для устройств Bluetooth SPP (HC-05, HC-06 и подобные)
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/fastlane/metadata/android/ru/changelogs/4.txt:
--------------------------------------------------------------------------------
1 | * fix: проблема с отзывом разрешения на Android 12+
2 | * feat: material theme
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/fastlane/metadata/android/en-US/images/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/fastlane/metadata/android/en-US/images/icon.png
--------------------------------------------------------------------------------
/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png
--------------------------------------------------------------------------------
/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png
--------------------------------------------------------------------------------
/fastlane/metadata/android/ru/full_description.txt:
--------------------------------------------------------------------------------
1 | Приложение подходит для разработки и отладки устройств, реализующих обмен через профиль SPP Bluetooth (модули HC-05, HC-06 и подобные).
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 5dp
4 |
5 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-hdpi/ic_action_device_bluetooth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-hdpi/ic_action_device_bluetooth.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-mdpi/ic_action_device_bluetooth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-mdpi/ic_action_device_bluetooth.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xhdpi/ic_action_device_bluetooth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xhdpi/ic_action_device_bluetooth.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xxhdpi/ic_action_device_bluetooth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xxhdpi/ic_action_device_bluetooth.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xxxhdpi/ic_action_device_bluetooth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xxxhdpi/ic_action_device_bluetooth.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-hdpi/ic_action_device_bluetooth_connected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-hdpi/ic_action_device_bluetooth_connected.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-mdpi/ic_action_device_bluetooth_connected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-mdpi/ic_action_device_bluetooth_connected.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xhdpi/ic_action_device_bluetooth_connected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xhdpi/ic_action_device_bluetooth_connected.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xxhdpi/ic_action_device_bluetooth_connected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xxhdpi/ic_action_device_bluetooth_connected.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/drawable-xxxhdpi/ic_action_device_bluetooth_connected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sash0k/bluetooth-spp-terminal/HEAD/bluetooth-spp-terminal/src/main/res/drawable-xxxhdpi/ic_action_device_bluetooth_connected.png
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/Const.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal;
2 |
3 | /**
4 | * Created by sash0k on 12.12.13.
5 | * Общие константы
6 | */
7 | public class Const {
8 | static final String TAG = "SPP_TERMINAL";
9 | }
10 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Dec 02 00:53:05 GMT+03:00 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/values/arrays.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - ASCII
5 | - HEX
6 |
7 |
8 |
9 | - none
10 | - Modulo 256
11 |
12 |
13 |
14 | - none
15 | - \\n
16 | - \\r
17 | - \\r\\n
18 |
19 |
20 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 33
5 | buildToolsVersion "33.0.0"
6 |
7 | defaultConfig {
8 | minSdkVersion 23
9 | targetSdkVersion 33
10 |
11 | versionCode 4
12 | versionName "1.3"
13 | }
14 |
15 | lintOptions {
16 | checkReleaseBuilds false
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled true
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
23 | zipAlignEnabled true
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Bluetooth-spp-terminal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/proguard-rules.txt:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/sash0k/develop/android-studio/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the ProGuard
5 | # include property in project.properties.
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 | #}
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/layout/device_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
20 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
19 |
20 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/values/preferences.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | pref_commands_mode
5 | pref_checksum_mode
6 | pref_commands_ending
7 | pref_log_timing
8 | pref_log_direction
9 | pref_need_clean
10 | pref_log_limit
11 | pref_log_limit_size
12 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Settings specified in this file will override any Gradle settings
5 | # configured through the IDE.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/menu/device_control_activity.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/layout/device_name.xml:
--------------------------------------------------------------------------------
1 |
15 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.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 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/layout/activity_terminal.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
13 |
14 |
21 |
22 |
29 |
30 |
31 |
39 |
40 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
15 |
16 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
34 |
35 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/DeviceData.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal;
2 |
3 | import java.util.ArrayList;
4 |
5 | import android.bluetooth.BluetoothDevice;
6 | import android.os.ParcelUuid;
7 |
8 | import ru.sash0k.bluetooth_terminal.bluetooth.BluetoothUtils;
9 |
10 |
11 | public class DeviceData {
12 | private String name = "";
13 | private String address = "";
14 | private int bondState = BluetoothDevice.BOND_NONE;
15 | private ArrayList uuids = null;
16 | private final int deviceClass;
17 | private final int majorDeviceClass;
18 |
19 | public DeviceData(BluetoothDevice device, String emptyName) {
20 | name = device.getName();
21 | address = device.getAddress();
22 | bondState = device.getBondState();
23 |
24 | if (name == null || name.isEmpty()) name = emptyName;
25 | deviceClass = device.getBluetoothClass().getDeviceClass();
26 | majorDeviceClass = device.getBluetoothClass().getMajorDeviceClass();
27 | uuids = BluetoothUtils.getDeviceUuids(device);
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 |
34 | public void setName(String deviceName) {
35 | name = deviceName;
36 | }
37 |
38 | public String getAddress() {
39 | return address;
40 | }
41 |
42 | public int getDeviceClass() {
43 | return deviceClass;
44 | }
45 |
46 | public int getMajorDeviceClass() {
47 | return majorDeviceClass;
48 | }
49 |
50 | public void setBondState(int state) {
51 | bondState = state;
52 | }
53 |
54 | public ArrayList getUuids() {
55 | return uuids;
56 | }
57 |
58 | public int getBondState() {
59 | return bondState;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### Archived here. Project development has been continued in [GitFlic](https://gitflic.ru/project/sash0k/bluetooth-spp-terminal)
2 |
3 | ## Bluetooth-spp-terminal
4 | (based on Android Bluetooth chat sample)
5 |
6 | ### Features
7 | #### v-1.3 (01.05.2023)
8 | * Исправлена проблема с автоматическим отзывом разрешения (Android 12+);
9 | * Material theme;
10 |
11 | #### v-1.2 (02.12.2022)
12 | * Адаптация к современной модели разрешений (Android 12+);
13 | * Сопряжение с устройствами через системный UI;
14 | * Возможность ограничить размер лога сообщений (see: #5);
15 | * Возможность передать входящую команду в приложение через intent/adb (see: #8);
16 | * Исправлен баг с затиранием входящей команды;
17 |
18 | #### v-1.1 (03.11.2016)
19 | * Calc and check Modulo256 checksum;
20 | * Drop deprecated Android 2.x support;
21 | * Minor fixes/improvements;
22 |
23 | #### v-1.0 (17.04.2014)
24 | * Search and connect to bluetooth devices in slave mode via RFCOMM;
25 | * Send commands to devices both ASCII and hex modes;
26 | * Share and clean log;
27 | * English/Russian i18n;
28 |
29 |
30 | ### Download
31 | * в [ruStore](https://apps.rustore.ru/app/ru.sash0k.bluetooth_terminal).
32 | * on [F-Droid](https://f-droid.org/repository/browse/?fdid=ru.sash0k.bluetooth_terminal).
33 | * on the [Play Store](https://play.google.com/store/apps/details?id=ru.sash0k.bluetooth_terminal).
34 | * directly on [GitHub](https://github.com/Sash0k/bluetooth-spp-terminal/releases).
35 |
36 | ### License
37 |
38 |
39 | Licensed under the Apache License, Version 2.0 (the "License");
40 | you may not use this file except in compliance with the License.
41 | You may obtain a copy of the License at
42 |
43 | http://www.apache.org/licenses/LICENSE-2.0
44 |
45 | Unless required by applicable law or agreed to in writing, software
46 | distributed under the License is distributed on an "AS IS" BASIS,
47 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
48 | See the License for the specific language governing permissions and
49 | limitations under the License.
50 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Bluetooth terminal
4 |
5 | not connected
6 | connecting…
7 | connected
8 |
9 | on/off
10 | Your device doesn\'t support bluetooth.
11 | This application won\'t work without Bluetooth permission grant.
12 | <New device>
13 |
14 | Send log…
15 | Settings
16 | Clear history
17 |
18 | Pair new device…
19 | No paired devices
20 | Enter command here
21 | Send
22 |
23 |
24 | Command history:
25 |
26 | Time
27 | Show time in log
28 | Direction
29 | Show I/O direction in log
30 | Log limit
31 | Clear log on max size exceeded
32 | Log buffer size (lines)
33 |
34 | Input mode:
35 | Checksum
36 | Add checksum to command
37 | Select input mode
38 | Select ending
39 |
40 | Clear previous command
41 | Cleanup command view after sending
42 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/values-ru/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | не подключено
4 | подключение…
5 | подключено
6 |
7 | on/off
8 | Ваше устройство не поддерживает Bluetooth.
9 | Приложение не будет работать без разрешения доступа к Bluetooth.
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 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/res/xml/settings_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
13 |
14 |
21 |
22 |
29 |
30 |
35 |
36 |
37 |
38 |
39 |
44 |
45 |
50 |
51 |
56 |
57 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/.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 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/activity/SettingsActivity.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal.activity;
2 |
3 | import android.app.ActionBar;
4 | import android.content.SharedPreferences;
5 | import android.os.Bundle;
6 | import android.preference.CheckBoxPreference;
7 | import android.preference.EditTextPreference;
8 | import android.preference.ListPreference;
9 | import android.preference.Preference;
10 | import android.preference.PreferenceActivity;
11 | import android.preference.PreferenceManager;
12 | import android.view.MenuItem;
13 |
14 | import ru.sash0k.bluetooth_terminal.R;
15 | import ru.sash0k.bluetooth_terminal.Utils;
16 |
17 | /**
18 | * Created by sash0k on 29.11.13.
19 | * Настройки приложения
20 | */
21 | @SuppressWarnings("deprecation")
22 | public final class SettingsActivity extends PreferenceActivity
23 | implements SharedPreferences.OnSharedPreferenceChangeListener {
24 |
25 |
26 | @Override
27 | public void onCreate(Bundle savedInstanceState) {
28 | super.onCreate(savedInstanceState);
29 | addPreferencesFromResource(R.xml.settings_activity);
30 |
31 | final ActionBar bar = getActionBar();
32 | bar.setHomeButtonEnabled(true);
33 | bar.setDisplayHomeAsUpEnabled(true);
34 |
35 | SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
36 | prefs.registerOnSharedPreferenceChangeListener(this);
37 | setPreferenceTitle(getString(R.string.pref_commands_mode));
38 | setPreferenceTitle(getString(R.string.pref_checksum_mode));
39 | setPreferenceTitle(getString(R.string.pref_commands_ending));
40 | setPreferenceTitle(getString(R.string.pref_log_limit));
41 | setPreferenceTitle(getString(R.string.pref_log_limit_size));
42 | }
43 | // ============================================================================
44 |
45 |
46 | @Override
47 | public boolean onOptionsItemSelected(MenuItem item) {
48 | int id = item.getItemId();
49 | switch (id) {
50 | case android.R.id.home:
51 | finish();
52 | return true;
53 | default:
54 | return super.onOptionsItemSelected(item);
55 | }
56 | }
57 | // ============================================================================
58 |
59 |
60 | @Override
61 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String value) {
62 | setPreferenceTitle(value);
63 | }
64 | // ============================================================================
65 |
66 |
67 | /**
68 | * Установка заголовка списка
69 | */
70 | private void setPreferenceTitle(String TAG) {
71 | final Preference preference = findPreference(TAG);
72 | if (preference == null) return;
73 |
74 | if (getString(R.string.pref_log_limit).equals(preference.getKey())) {
75 | boolean isEnabled = ((CheckBoxPreference)preference).isChecked();
76 | Preference limitSize = findPreference(getString(R.string.pref_log_limit_size));
77 | if (limitSize != null) limitSize.setEnabled(isEnabled);
78 | }
79 |
80 | if (preference instanceof ListPreference) {
81 | if (((ListPreference) preference).getEntry() == null) return;
82 | final String title = ((ListPreference) preference).getEntry().toString();
83 | preference.setTitle(title);
84 | } else if (preference instanceof EditTextPreference) {
85 | final String text = ((EditTextPreference) preference).getText();
86 | preference.setSummary(Integer.toString(Utils.formatNumber(text)));
87 | }
88 | }
89 | // ============================================================================
90 | }
91 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/bluetooth/DeviceListActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package ru.sash0k.bluetooth_terminal.bluetooth;
18 |
19 | import android.app.Activity;
20 | import android.bluetooth.BluetoothAdapter;
21 | import android.bluetooth.BluetoothDevice;
22 | import android.content.Intent;
23 | import android.os.Bundle;
24 | import android.view.View;
25 | import android.view.View.OnClickListener;
26 | import android.widget.AdapterView;
27 | import android.widget.AdapterView.OnItemClickListener;
28 | import android.widget.ArrayAdapter;
29 | import android.widget.Button;
30 | import android.widget.ListView;
31 | import android.widget.TextView;
32 |
33 | import java.util.Set;
34 |
35 | import ru.sash0k.bluetooth_terminal.R;
36 |
37 |
38 | /**
39 | * This Activity appears as a dialog. It lists already paired devices,
40 | * and it can scan for devices nearby. When the user selects a device,
41 | * its MAC address is returned to the caller as the result of this activity.
42 | */
43 | public class DeviceListActivity extends Activity {
44 |
45 | public static final String EXTRA_DEVICE_ADDRESS = "device_address";
46 |
47 | private BluetoothAdapter mBtAdapter;
48 | private Button scanButton;
49 |
50 | @Override
51 | protected void onCreate(Bundle savedInstanceState) {
52 | super.onCreate(savedInstanceState);
53 | setContentView(R.layout.device_list);
54 | }
55 |
56 | @Override
57 | protected void onResume() {
58 | super.onResume();
59 |
60 | // Initialize the button to perform device discovery
61 | scanButton = (Button) findViewById(R.id.button_scan);
62 | scanButton.setOnClickListener(new OnClickListener() {
63 | public void onClick(View v) {
64 | pairNewDevice();
65 | }
66 | });
67 |
68 | ArrayAdapter pairedDevicesAdapter = new ArrayAdapter(this, R.layout.device_name);
69 | ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
70 | pairedListView.setAdapter(pairedDevicesAdapter);
71 | pairedListView.setOnItemClickListener(mDeviceClickListener);
72 |
73 | mBtAdapter = BluetoothAdapter.getDefaultAdapter();
74 |
75 | Set pairedDevices = mBtAdapter.getBondedDevices();
76 |
77 | if (pairedDevices != null && !pairedDevices.isEmpty()) {
78 | pairedListView.setEnabled(true);
79 | for (BluetoothDevice device : pairedDevices) {
80 | final String address = device.getAddress();
81 | pairedDevicesAdapter.add(device.getName() + '\n' + address);
82 | }
83 | } else {
84 | pairedListView.setEnabled(false);
85 | String noDevices = getResources().getText(R.string.none_paired).toString();
86 | pairedDevicesAdapter.add(noDevices);
87 | }
88 | }
89 |
90 | /**
91 | * Start device discover with the system settings UI
92 | */
93 | private void pairNewDevice() {
94 | startActivity(new Intent().setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS));
95 | }
96 |
97 | private final OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
98 | public void onItemClick(AdapterView> av, View v, int arg2, long arg3) {
99 | // Get the device MAC address, which is the last 17 chars in the View
100 | CharSequence info = ((TextView) v).getText();
101 | if (info != null) {
102 | // TODO this is not so cool...
103 | CharSequence address = info.toString().substring(info.length() - 17);
104 | Intent intent = new Intent();
105 | intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
106 |
107 | setResult(Activity.RESULT_OK, intent);
108 | finish();
109 | }
110 | }
111 | };
112 | }
113 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/Utils.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 | import android.preference.PreferenceManager;
6 | import android.text.InputFilter;
7 | import android.text.Spanned;
8 | import android.util.Log;
9 |
10 | /**
11 | * Вспомогательные методы
12 | * Created by sash0k on 29.01.14.
13 | */
14 | public class Utils {
15 |
16 | /**
17 | * Общий метод вывода отладочных сообщений в лог
18 | */
19 | public static void log(String message) {
20 | if (BuildConfig.DEBUG) {
21 | if (message != null) Log.i(Const.TAG, message);
22 | }
23 | }
24 | // ============================================================================
25 |
26 |
27 | /**
28 | * Конвертация hex-команд в строку для отображения
29 | */
30 | public static String printHex(String hex) {
31 | StringBuilder sb = new StringBuilder();
32 | int len = hex.length();
33 | try {
34 | for (int i = 0; i < len; i += 2) {
35 | sb.append("0x").append(hex.substring(i, i + 2)).append(" ");
36 | }
37 | } catch (NumberFormatException e) {
38 | log("printHex NumberFormatException: " + e.getMessage());
39 |
40 | } catch (StringIndexOutOfBoundsException e) {
41 | log("printHex StringIndexOutOfBoundsException: " + e.getMessage());
42 | }
43 | return sb.toString();
44 | }
45 | // ============================================================================
46 |
47 |
48 | /**
49 | * Перевод введенных ASCII-команд в hex побайтно.
50 | * @param hex - команда
51 | * @return - массив байт команды
52 | */
53 | public static byte[] toHex(String hex) {
54 | int len = hex.length();
55 | byte[] result = new byte[len];
56 | try {
57 | int index = 0;
58 | for (int i = 0; i < len; i += 2) {
59 | result[index] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
60 | index++;
61 | }
62 | } catch (NumberFormatException e) {
63 | log("toHex NumberFormatException: " + e.getMessage());
64 |
65 | } catch (StringIndexOutOfBoundsException e) {
66 | log("toHex StringIndexOutOfBoundsException: " + e.getMessage());
67 | }
68 | return result;
69 | }
70 | // ============================================================================
71 |
72 |
73 | /**
74 | * Метод сливает два массива в один
75 | */
76 | public static byte[] concat(byte[] A, byte[] B) {
77 | byte[] C = new byte[A.length + B.length];
78 | System.arraycopy(A, 0, C, 0, A.length);
79 | System.arraycopy(B, 0, C, A.length, B.length);
80 | return C;
81 | }
82 | // ============================================================================
83 |
84 |
85 | /**
86 | * Modulo
87 | */
88 | public static int mod(int x, int y) {
89 | int result = x % y;
90 | return result < 0 ? result + y : result;
91 | }
92 | // ============================================================================
93 |
94 | /**
95 | * Расчёт контрольной суммы
96 | */
97 | public static String calcModulo256(String command)
98 | {
99 | int crc = 0;
100 | for (int i = 0; i< command.length(); i++) {
101 | crc += (int)command.charAt(i);
102 | }
103 | return Integer.toHexString(Utils.mod(crc, 256));
104 | }
105 | // ============================================================================
106 |
107 | /**
108 | * Раскрасить текст нужным цветом
109 | */
110 | public static String mark(String text, String color) {
111 | return "" + text + "";
112 | }
113 | // ============================================================================
114 |
115 | /**
116 | * Получение id сохранённого в игрушке звукового набора
117 | */
118 | public static String getPrefence(Context context, String item) {
119 | final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
120 | return settings.getString(item, Const.TAG);
121 | }
122 | // ============================================================================
123 |
124 |
125 | /**
126 | * Получение флага из настроек
127 | */
128 | public static boolean getBooleanPrefence(Context context, String tag) {
129 | final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
130 | return settings.getBoolean(tag, true);
131 | }
132 | // ============================================================================
133 |
134 |
135 | /**
136 | * Класс-фильтр полей ввода
137 | */
138 | // ============================================================================
139 | public static class InputFilterHex implements InputFilter {
140 |
141 | @Override
142 | public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
143 | for (int i = start; i < end; i++) {
144 | if (!Character.isDigit(source.charAt(i))
145 | && source.charAt(i) != 'A' && source.charAt(i) != 'D'
146 | && source.charAt(i) != 'B' && source.charAt(i) != 'E'
147 | && source.charAt(i) != 'C' && source.charAt(i) != 'F'
148 | ) {
149 | return "";
150 | }
151 | }
152 | return null;
153 | }
154 | }
155 | // ============================================================================
156 |
157 | public static int formatNumber(String input) {
158 | int value;
159 | try {
160 | value = Integer.parseInt(input);
161 | } catch (NumberFormatException e) {
162 | value = 0;
163 | }
164 | return value;
165 | }
166 | }
167 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/activity/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal.activity;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.app.AlertDialog;
6 | import android.bluetooth.BluetoothAdapter;
7 | import android.content.DialogInterface;
8 | import android.content.Intent;
9 | import android.content.pm.PackageManager;
10 | import android.os.Build;
11 | import android.os.Bundle;
12 |
13 | import ru.sash0k.bluetooth_terminal.R;
14 | import ru.sash0k.bluetooth_terminal.Utils;
15 |
16 | /**
17 | * Общий базовый класс. Инициализация BT-адаптера
18 | * Created by sash0k on 09.12.13.
19 | */
20 | public abstract class BaseActivity extends Activity {
21 |
22 | // Intent request codes
23 | static final int REQUEST_CONNECT_DEVICE = 1;
24 | static final int REQUEST_ENABLE_BT = 2;
25 |
26 | // Message types sent from the DeviceConnector Handler
27 | public static final int MESSAGE_STATE_CHANGE = 1;
28 | public static final int MESSAGE_READ = 2;
29 | public static final int MESSAGE_WRITE = 3;
30 | public static final int MESSAGE_DEVICE_NAME = 4;
31 | public static final int MESSAGE_TOAST = 5;
32 |
33 | BluetoothAdapter btAdapter;
34 |
35 | private static final String SAVED_PENDING_REQUEST_ENABLE_BT = "PENDING_REQUEST_ENABLE_BT";
36 | // do not resend request to enable Bluetooth
37 | // if there is a request already in progress
38 | // See: https://code.google.com/p/android/issues/detail?id=24931#c1
39 | boolean pendingRequestEnableBt = false;
40 | // ==========================================================================
41 |
42 | @Override
43 | protected void onCreate(Bundle state) {
44 | super.onCreate(state);
45 | getActionBar().setHomeButtonEnabled(false);
46 |
47 | checkBluetoothPermission(REQUEST_ENABLE_BT);
48 |
49 | if (state != null) {
50 | pendingRequestEnableBt = state.getBoolean(SAVED_PENDING_REQUEST_ENABLE_BT);
51 | }
52 | btAdapter = BluetoothAdapter.getDefaultAdapter();
53 | if (btAdapter == null) {
54 | final String no_bluetooth = getString(R.string.no_bt_support);
55 | showAlertDialog(no_bluetooth);
56 | Utils.log(no_bluetooth);
57 | }
58 | }
59 | // ==========================================================================
60 |
61 | protected boolean checkBluetoothPermission(int requestCode) {
62 | final String permission;
63 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
64 | permission = Manifest.permission.BLUETOOTH_CONNECT;
65 | else
66 | permission = Manifest.permission.BLUETOOTH;
67 |
68 | if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
69 | requestPermissions(new String[]{permission}, requestCode);
70 | return false;
71 | }
72 |
73 | return true;
74 | }
75 |
76 | @Override
77 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
78 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
79 |
80 | int grantResult;
81 | if (grantResults.length > 0)
82 | grantResult = grantResults[0];
83 | else grantResult = PackageManager.PERMISSION_DENIED;
84 |
85 | if (requestCode == REQUEST_ENABLE_BT && grantResult != PackageManager.PERMISSION_GRANTED) {
86 | final String message = getString(R.string.no_permission);
87 | showAlertDialog(message);
88 | Utils.log(message);
89 | }
90 | }
91 |
92 | @Override
93 | public void onStart() {
94 | super.onStart();
95 | if (btAdapter == null) return;
96 |
97 | if (!btAdapter.isEnabled() && !pendingRequestEnableBt) {
98 | pendingRequestEnableBt = true;
99 | Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
100 | if (checkBluetoothPermission(REQUEST_ENABLE_BT)) startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
101 | }
102 | }
103 | // ==========================================================================
104 |
105 |
106 | @Override
107 | public synchronized void onResume() {
108 | super.onResume();
109 | }
110 | // ==========================================================================
111 |
112 |
113 | @Override
114 | public synchronized void onPause() {
115 | super.onPause();
116 | }
117 | // ==========================================================================
118 |
119 |
120 | @Override
121 | protected void onSaveInstanceState(Bundle outState) {
122 | super.onSaveInstanceState(outState);
123 | outState.putBoolean(SAVED_PENDING_REQUEST_ENABLE_BT, pendingRequestEnableBt);
124 | }
125 | // ==========================================================================
126 |
127 |
128 | /**
129 | * Проверка адаптера
130 | *
131 | * @return - true, если готов к работе
132 | */
133 | boolean isAdapterReady() {
134 | return (btAdapter != null) && (btAdapter.isEnabled());
135 | }
136 | // ==========================================================================
137 |
138 |
139 | /**
140 | * Показывает диалоговое окно с предупреждением.
141 | * TODO: При переконфигурациях будет теряться
142 | *
143 | * @param message - сообщение
144 | */
145 | void showAlertDialog(String message) {
146 | AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this)
147 | .setTitle(getString(R.string.app_name))
148 | .setMessage(message);
149 |
150 | AlertDialog alertDialog = alertDialogBuilder.create();
151 | alertDialog.setCancelable(false);
152 | alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getString(android.R.string.ok), new DialogInterface.OnClickListener() {
153 | @Override
154 | public void onClick(DialogInterface dialogInterface, int i) {
155 | finish();
156 | }
157 | });
158 |
159 | alertDialog.show();
160 | }
161 | // ==========================================================================
162 | }
163 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/bluetooth/BluetoothUtils.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal.bluetooth;
2 |
3 | import java.lang.reflect.InvocationTargetException;
4 | import java.lang.reflect.Method;
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | import android.bluetooth.BluetoothDevice;
10 | import android.bluetooth.BluetoothSocket;
11 | import android.os.ParcelUuid;
12 | import android.util.Log;
13 |
14 | public class BluetoothUtils {
15 | private static final String TAG = "BluetoothUtils";
16 | private static final boolean D = true;
17 |
18 | private static final Map uuidsDescriptions = new HashMap();
19 |
20 | static {
21 | uuidsDescriptions.put("0001", "SDP");
22 | uuidsDescriptions.put("0002", "UDP");
23 | uuidsDescriptions.put("0003", "RFCOMM");
24 | uuidsDescriptions.put("0004", "TCP");
25 | uuidsDescriptions.put("0005", "TCS-BIN");
26 | uuidsDescriptions.put("0006", "TCS-AT");
27 | uuidsDescriptions.put("0007", "ATT");
28 | uuidsDescriptions.put("0008", "OBEX");
29 | uuidsDescriptions.put("0009", "IP");
30 | uuidsDescriptions.put("000A", "FTP");
31 | uuidsDescriptions.put("000C", "HTTP");
32 | uuidsDescriptions.put("000E", "WSP");
33 | uuidsDescriptions.put("000F", "BNEP");
34 |
35 | uuidsDescriptions.put("0010", "UPNP");
36 | uuidsDescriptions.put("0011", "HIDP");
37 | uuidsDescriptions.put("0012", "HardcopyControlChannel");
38 | uuidsDescriptions.put("0014", "HardcopyDataChannel");
39 | uuidsDescriptions.put("0016", "HardcopyNotification");
40 | uuidsDescriptions.put("0017", "AVCTP");
41 | uuidsDescriptions.put("0019", "AVDTP");
42 | uuidsDescriptions.put("001B", "CMTP");
43 | uuidsDescriptions.put("001E", "MCAPControlChannel");
44 | uuidsDescriptions.put("001F", "MCAPDataChannel");
45 | uuidsDescriptions.put("0100", "L2CAP");
46 |
47 | uuidsDescriptions.put("1000", "ServiceDiscoveryServerService");
48 | uuidsDescriptions.put("1001", "BrowseGroupDescriptorService");
49 | uuidsDescriptions.put("1002", "PublicBrowseGroupService");
50 | uuidsDescriptions.put("1101", "SerialPortService");
51 | uuidsDescriptions.put("1102", "LANAccessUsingPPPService");
52 | uuidsDescriptions.put("1103", "DialupNetworkingService");
53 | uuidsDescriptions.put("1104", "IrMCSyncService");
54 | uuidsDescriptions.put("1105", "OBEXObjectPushService");
55 | uuidsDescriptions.put("1106", "OBEXFileTransferService");
56 | uuidsDescriptions.put("1107", "IrMCSyncCommandService");
57 | uuidsDescriptions.put("1108", "HeadsetService");
58 | uuidsDescriptions.put("1109", "CordlessTelephonyService");
59 | uuidsDescriptions.put("110A", "AudioSourceService");
60 | uuidsDescriptions.put("110B", "AudioSinkService");
61 | uuidsDescriptions.put("110C", "AVRemoteControlTargetService");
62 | uuidsDescriptions.put("110D", "AdvancedAudioDistributionService");
63 | uuidsDescriptions.put("110E", "AVRemoteControlService");
64 | uuidsDescriptions.put("110F", "VideoConferencingService");
65 |
66 | uuidsDescriptions.put("1110", "IntercomService");
67 | uuidsDescriptions.put("1111", "FaxService");
68 | uuidsDescriptions.put("1112", "HeadsetAudioGatewayService");
69 | uuidsDescriptions.put("1113", "WAPService");
70 | uuidsDescriptions.put("1114", "WAPClientService");
71 | uuidsDescriptions.put("1115", "PANUService");
72 | uuidsDescriptions.put("1116", "NAPService");
73 | uuidsDescriptions.put("1117", "GNService");
74 | uuidsDescriptions.put("1118", "DirectPrintingService");
75 | uuidsDescriptions.put("1119", "ReferencePrintingService");
76 | uuidsDescriptions.put("111A", "ImagingService");
77 | uuidsDescriptions.put("111B", "ImagingResponderService");
78 | uuidsDescriptions.put("111C", "ImagingAutomaticArchiveService");
79 | uuidsDescriptions.put("111D", "ImagingReferenceObjectsService");
80 | uuidsDescriptions.put("111E", "HandsfreeService");
81 | uuidsDescriptions.put("111F", "HandsfreeAudioGatewayService");
82 |
83 | uuidsDescriptions.put("1120", "DirectPrintingReferenceObjectsService");
84 | uuidsDescriptions.put("1121", "ReflectedUIService");
85 | uuidsDescriptions.put("1122", "BasicPringingService");
86 | uuidsDescriptions.put("1123", "PrintingStatusService");
87 | uuidsDescriptions.put("1124", "HumanInterfaceDeviceService");
88 | uuidsDescriptions.put("1125", "HardcopyCableReplacementService");
89 | uuidsDescriptions.put("1126", "HCRPrintService");
90 | uuidsDescriptions.put("1127", "HCRScanService");
91 | uuidsDescriptions.put("1128", "CommonISDNAccessService");
92 | uuidsDescriptions.put("1129", "VideoConferencingGWService");
93 | uuidsDescriptions.put("112A", "UDIMTService");
94 | uuidsDescriptions.put("112B", "UDITAService");
95 | uuidsDescriptions.put("112C", "AudioVideoService");
96 | uuidsDescriptions.put("112D", "SIMAccessService");
97 | uuidsDescriptions.put("112E", "Phonebook Access - PCE");
98 | uuidsDescriptions.put("112F", "Phonebook Access - PSE");
99 |
100 | uuidsDescriptions.put("1130", "Phonebook Access");
101 | uuidsDescriptions.put("1131", "Headset - HS");
102 | uuidsDescriptions.put("1132", "Message Access Server");
103 | uuidsDescriptions.put("1133", "Message Notification Server");
104 | uuidsDescriptions.put("1134", "Message Access Profile");
105 | uuidsDescriptions.put("1135", "GNSS");
106 | uuidsDescriptions.put("1136", "GNSS_Server");
107 |
108 | uuidsDescriptions.put("1200", "PnPInformationService");
109 | uuidsDescriptions.put("1201", "GenericNetworkingService");
110 | uuidsDescriptions.put("1202", "GenericFileTransferService");
111 | uuidsDescriptions.put("1203", "GenericAudioService");
112 | uuidsDescriptions.put("1204", "GenericTelephonyService");
113 | }
114 |
115 | public static ArrayList getDeviceUuids(BluetoothDevice device) {
116 | ArrayList result = new ArrayList();
117 |
118 | try {
119 | Method method = device.getClass().getMethod("getUuids", null);
120 | ParcelUuid[] phoneUuids = (ParcelUuid[]) method.invoke(device, null);
121 | if (phoneUuids != null) {
122 | for (ParcelUuid uuid : phoneUuids) {
123 | if (D) Log.d(TAG, device.getName() + ": " + uuid.toString());
124 | result.add(uuid);
125 | }
126 | }
127 | } catch (NoSuchMethodException e) {
128 | e.printStackTrace();
129 | if (D) Log.e(TAG, "getDeviceUuids() failed", e);
130 | } catch (InvocationTargetException e) {
131 | e.printStackTrace();
132 | if (D) Log.e(TAG, "getDeviceUuids() failed", e);
133 | } catch (IllegalAccessException e) {
134 | e.printStackTrace();
135 | if (D) Log.e(TAG, "getDeviceUuids() failed", e);
136 | }
137 |
138 | return result;
139 | }
140 |
141 |
142 | private static ArrayList getDeviceServices(ArrayList uuids) {
143 | ArrayList result = new ArrayList();
144 | for (ParcelUuid uuid : uuids) {
145 | String s = uuid.toString().toUpperCase();
146 | boolean found = false;
147 | for (Map.Entry entry : uuidsDescriptions.entrySet()) {
148 | String key = entry.getKey().toUpperCase();
149 | String value = entry.getValue();
150 |
151 | if (s.startsWith("0000" + key)) {
152 | found = true;
153 | result.add(value);
154 | break;
155 | }
156 | }
157 | if (!found) {
158 | String desc = "Unknown service UUID 0x" + s.substring(4, 8);
159 | result.add(desc);
160 | }
161 | }
162 | return result;
163 | }
164 |
165 |
166 | public static ArrayList getDeviceServices(BluetoothDevice device) {
167 | ArrayList uuids = getDeviceUuids(device);
168 | return getDeviceServices(uuids);
169 | }
170 |
171 | /**
172 | * see http://habrahabr.ru/post/144547/
173 | */
174 | public static BluetoothSocket createRfcommSocket(BluetoothDevice device) {
175 | BluetoothSocket tmp = null;
176 | try {
177 | Class class1 = device.getClass();
178 | Class aclass[] = new Class[1];
179 | aclass[0] = Integer.TYPE;
180 | Method method = class1.getMethod("createRfcommSocket", aclass);
181 | Object aobj[] = new Object[1];
182 | aobj[0] = Integer.valueOf(1);
183 |
184 | tmp = (BluetoothSocket) method.invoke(device, aobj);
185 | } catch (NoSuchMethodException e) {
186 | e.printStackTrace();
187 | if (D) Log.e(TAG, "createRfcommSocket() failed", e);
188 | } catch (InvocationTargetException e) {
189 | e.printStackTrace();
190 | if (D) Log.e(TAG, "createRfcommSocket() failed", e);
191 | } catch (IllegalAccessException e) {
192 | e.printStackTrace();
193 | if (D) Log.e(TAG, "createRfcommSocket() failed", e);
194 | }
195 | return tmp;
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/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.
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/bluetooth/DeviceConnector.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package ru.sash0k.bluetooth_terminal.bluetooth;
18 |
19 | import java.io.IOException;
20 | import java.io.InputStream;
21 | import java.io.OutputStream;
22 |
23 | import android.bluetooth.BluetoothAdapter;
24 | import android.bluetooth.BluetoothDevice;
25 | import android.bluetooth.BluetoothSocket;
26 | import android.os.Bundle;
27 | import android.os.Handler;
28 | import android.os.Message;
29 | import android.util.Log;
30 |
31 | import ru.sash0k.bluetooth_terminal.DeviceData;
32 | import ru.sash0k.bluetooth_terminal.activity.DeviceControlActivity;
33 |
34 |
35 | public class DeviceConnector {
36 | private static final String TAG = "DeviceConnector";
37 | private static final boolean D = false;
38 |
39 | // Constants that indicate the current connection state
40 | public static final int STATE_NONE = 0; // we're doing nothing
41 | public static final int STATE_CONNECTING = 1; // now initiating an outgoing connection
42 | public static final int STATE_CONNECTED = 2; // now connected to a remote device
43 |
44 | private int mState;
45 |
46 | private final BluetoothAdapter btAdapter;
47 | private final BluetoothDevice connectedDevice;
48 | private ConnectThread mConnectThread;
49 | private ConnectedThread mConnectedThread;
50 | private final Handler mHandler;
51 | private final String deviceName;
52 | // ==========================================================================
53 |
54 |
55 | public DeviceConnector(DeviceData deviceData, Handler handler) {
56 | mHandler = handler;
57 | btAdapter = BluetoothAdapter.getDefaultAdapter();
58 | connectedDevice = btAdapter.getRemoteDevice(deviceData.getAddress());
59 | deviceName = (deviceData.getName() == null) ? deviceData.getAddress() : deviceData.getName();
60 | mState = STATE_NONE;
61 | }
62 | // ==========================================================================
63 |
64 |
65 | /**
66 | * Запрос на соединение с устойством
67 | */
68 | public synchronized void connect() {
69 | if (D) Log.d(TAG, "connect to: " + connectedDevice);
70 |
71 | if (mState == STATE_CONNECTING) {
72 | if (mConnectThread != null) {
73 | if (D) Log.d(TAG, "cancel mConnectThread");
74 | mConnectThread.cancel();
75 | mConnectThread = null;
76 | }
77 | }
78 |
79 | if (mConnectedThread != null) {
80 | if (D) Log.d(TAG, "cancel mConnectedThread");
81 | mConnectedThread.cancel();
82 | mConnectedThread = null;
83 | }
84 |
85 | // Start the thread to connect with the given device
86 | mConnectThread = new ConnectThread(connectedDevice);
87 | mConnectThread.start();
88 | setState(STATE_CONNECTING);
89 | }
90 | // ==========================================================================
91 |
92 | /**
93 | * Завершение соединения
94 | */
95 | public synchronized void stop() {
96 | if (D) Log.d(TAG, "stop");
97 |
98 | if (mConnectThread != null) {
99 | if (D) Log.d(TAG, "cancel mConnectThread");
100 | mConnectThread.cancel();
101 | mConnectThread = null;
102 | }
103 |
104 | if (mConnectedThread != null) {
105 | if (D) Log.d(TAG, "cancel mConnectedThread");
106 | mConnectedThread.cancel();
107 | mConnectedThread = null;
108 | }
109 |
110 | setState(STATE_NONE);
111 | }
112 | // ==========================================================================
113 |
114 |
115 | /**
116 | * Установка внутреннего состояния устройства
117 | *
118 | * @param state - состояние
119 | */
120 | private synchronized void setState(int state) {
121 | if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
122 | mState = state;
123 | mHandler.obtainMessage(DeviceControlActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
124 | }
125 | // ==========================================================================
126 |
127 |
128 | /**
129 | * Получение состояния устройства
130 | */
131 | public synchronized int getState() {
132 | return mState;
133 | }
134 | // ==========================================================================
135 |
136 |
137 | public synchronized void connected(BluetoothSocket socket) {
138 | if (D) Log.d(TAG, "connected");
139 |
140 | // Cancel the thread that completed the connection
141 | if (mConnectThread != null) {
142 | if (D) Log.d(TAG, "cancel mConnectThread");
143 | mConnectThread.cancel();
144 | mConnectThread = null;
145 | }
146 |
147 | if (mConnectedThread != null) {
148 | if (D) Log.d(TAG, "cancel mConnectedThread");
149 | mConnectedThread.cancel();
150 | mConnectedThread = null;
151 | }
152 |
153 | setState(STATE_CONNECTED);
154 |
155 | // Send the name of the connected device back to the UI Activity
156 | Message msg = mHandler.obtainMessage(DeviceControlActivity.MESSAGE_DEVICE_NAME, deviceName);
157 | mHandler.sendMessage(msg);
158 |
159 | // Start the thread to manage the connection and perform transmissions
160 | mConnectedThread = new ConnectedThread(socket);
161 | mConnectedThread.start();
162 | }
163 | // ==========================================================================
164 |
165 |
166 | public void write(byte[] data) {
167 | ConnectedThread r;
168 | // Synchronize a copy of the ConnectedThread
169 | synchronized (this) {
170 | if (mState != STATE_CONNECTED) return;
171 | r = mConnectedThread;
172 | }
173 |
174 | // Perform the write unsynchronized
175 | if (data.length == 1) r.write(data[0]);
176 | else r.writeData(data);
177 | }
178 | // ==========================================================================
179 |
180 |
181 | private void connectionFailed() {
182 | if (D) Log.d(TAG, "connectionFailed");
183 |
184 | // Send a failure message back to the Activity
185 | Message msg = mHandler.obtainMessage(DeviceControlActivity.MESSAGE_TOAST);
186 | Bundle bundle = new Bundle();
187 | msg.setData(bundle);
188 | mHandler.sendMessage(msg);
189 | setState(STATE_NONE);
190 | }
191 | // ==========================================================================
192 |
193 |
194 | private void connectionLost() {
195 | // Send a failure message back to the Activity
196 | Message msg = mHandler.obtainMessage(DeviceControlActivity.MESSAGE_TOAST);
197 | Bundle bundle = new Bundle();
198 | msg.setData(bundle);
199 | mHandler.sendMessage(msg);
200 | setState(STATE_NONE);
201 | }
202 | // ==========================================================================
203 |
204 |
205 | /**
206 | * Класс потока для соединения с BT-устройством
207 | */
208 | // ==========================================================================
209 | private class ConnectThread extends Thread {
210 | private static final String TAG = "ConnectThread";
211 | private static final boolean D = false;
212 |
213 | private final BluetoothSocket mmSocket;
214 | private final BluetoothDevice mmDevice;
215 |
216 | public ConnectThread(BluetoothDevice device) {
217 | if (D) Log.d(TAG, "create ConnectThread");
218 | mmDevice = device;
219 | mmSocket = BluetoothUtils.createRfcommSocket(mmDevice);
220 | }
221 | // ==========================================================================
222 |
223 | /**
224 | * Основной рабочий метод для соединения с устройством.
225 | * При успешном соединении передаёт управление другому потоку
226 | */
227 | public void run() {
228 | if (D) Log.d(TAG, "ConnectThread run");
229 | if (mmSocket == null) {
230 | if (D) Log.d(TAG, "unable to connect to device, socket isn't created");
231 | connectionFailed();
232 | return;
233 | }
234 |
235 | // Make a connection to the BluetoothSocket
236 | try {
237 | // This is a blocking call and will only return on a
238 | // successful connection or an exception
239 | mmSocket.connect();
240 | } catch (IOException e) {
241 | // Close the socket
242 | try {
243 | mmSocket.close();
244 | } catch (IOException e2) {
245 | if (D) Log.e(TAG, "unable to close() socket during connection failure", e2);
246 | }
247 | connectionFailed();
248 | return;
249 | }
250 |
251 | // Reset the ConnectThread because we're done
252 | synchronized (DeviceConnector.this) {
253 | mConnectThread = null;
254 | }
255 |
256 | // Start the connected thread
257 | connected(mmSocket);
258 | }
259 | // ==========================================================================
260 |
261 |
262 | /**
263 | * Отмена соединения
264 | */
265 | public void cancel() {
266 | if (D) Log.d(TAG, "ConnectThread cancel");
267 |
268 | if (mmSocket == null) {
269 | if (D) Log.d(TAG, "unable to close null socket");
270 | return;
271 | }
272 | try {
273 | mmSocket.close();
274 | } catch (IOException e) {
275 | if (D) Log.e(TAG, "close() of connect socket failed", e);
276 | }
277 | }
278 | // ==========================================================================
279 | }
280 | // ==========================================================================
281 |
282 |
283 | /**
284 | * Класс потока для обмена данными с BT-устройством
285 | */
286 | // ==========================================================================
287 | private class ConnectedThread extends Thread {
288 | private static final String TAG = "ConnectedThread";
289 | private static final boolean D = false;
290 |
291 | private final BluetoothSocket mmSocket;
292 | private final InputStream mmInStream;
293 | private final OutputStream mmOutStream;
294 |
295 | public ConnectedThread(BluetoothSocket socket) {
296 | if (D) Log.d(TAG, "create ConnectedThread");
297 |
298 | mmSocket = socket;
299 | InputStream tmpIn = null;
300 | OutputStream tmpOut = null;
301 |
302 | // Get the BluetoothSocket input and output streams
303 | try {
304 | tmpIn = socket.getInputStream();
305 | tmpOut = socket.getOutputStream();
306 | } catch (IOException e) {
307 | if (D) Log.e(TAG, "temp sockets not created", e);
308 | }
309 |
310 | mmInStream = tmpIn;
311 | mmOutStream = tmpOut;
312 | }
313 | // ==========================================================================
314 |
315 | /**
316 | * Основной рабочий метод - ждёт входящих команд от потока
317 | */
318 | public void run() {
319 | if (D) Log.i(TAG, "ConnectedThread run");
320 | byte[] buffer = new byte[512];
321 | int bytes;
322 | StringBuilder readMessage = new StringBuilder();
323 | while (true) {
324 | try {
325 | // считываю входящие данные из потока и собираю в строку ответа
326 | bytes = mmInStream.read(buffer);
327 | String readed = new String(buffer, 0, bytes);
328 | readMessage.append(readed);
329 |
330 | // маркер конца команды - вернуть ответ в главный поток
331 | if (readed.contains("\n")) {
332 | mHandler.obtainMessage(DeviceControlActivity.MESSAGE_READ, bytes, -1, readMessage.toString()).sendToTarget();
333 | readMessage.setLength(0);
334 | }
335 |
336 | } catch (IOException e) {
337 | if (D) Log.e(TAG, "disconnected", e);
338 | connectionLost();
339 | break;
340 | }
341 | }
342 | }
343 | // ==========================================================================
344 |
345 |
346 | /**
347 | * Записать кусок данных в устройство
348 | */
349 | public void writeData(byte[] chunk) {
350 |
351 | try {
352 | mmOutStream.write(chunk);
353 | mmOutStream.flush();
354 | // Share the sent message back to the UI Activity
355 | mHandler.obtainMessage(DeviceControlActivity.MESSAGE_WRITE, -1, -1, chunk).sendToTarget();
356 | } catch (IOException e) {
357 | if (D) Log.e(TAG, "Exception during write", e);
358 | }
359 | }
360 | // ==========================================================================
361 |
362 |
363 | /**
364 | * Записать байт
365 | */
366 | public void write(byte command) {
367 | byte[] buffer = new byte[1];
368 | buffer[0] = command;
369 |
370 | try {
371 | mmOutStream.write(buffer);
372 |
373 | // Share the sent message back to the UI Activity
374 | mHandler.obtainMessage(DeviceControlActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
375 | } catch (IOException e) {
376 | if (D) Log.e(TAG, "Exception during write", e);
377 | }
378 | }
379 | // ==========================================================================
380 |
381 |
382 | /**
383 | * Отмена - закрытие сокета
384 | */
385 | public void cancel() {
386 | try {
387 | mmSocket.close();
388 | } catch (IOException e) {
389 | if (D) Log.e(TAG, "close() of connect socket failed", e);
390 | }
391 | }
392 | // ==========================================================================
393 | }
394 | // ==========================================================================
395 | }
396 |
--------------------------------------------------------------------------------
/bluetooth-spp-terminal/src/main/java/ru/sash0k/bluetooth_terminal/activity/DeviceControlActivity.java:
--------------------------------------------------------------------------------
1 | package ru.sash0k.bluetooth_terminal.activity;
2 |
3 | import android.app.ActionBar;
4 | import android.app.Activity;
5 | import android.bluetooth.BluetoothAdapter;
6 | import android.bluetooth.BluetoothDevice;
7 | import android.content.Intent;
8 | import android.os.Bundle;
9 | import android.os.Handler;
10 | import android.os.Message;
11 | import android.preference.PreferenceManager;
12 | import android.text.Html;
13 | import android.text.InputFilter;
14 | import android.text.InputType;
15 | import android.text.method.ScrollingMovementMethod;
16 | import android.view.KeyEvent;
17 | import android.view.Menu;
18 | import android.view.MenuItem;
19 | import android.view.View;
20 | import android.view.inputmethod.EditorInfo;
21 | import android.widget.EditText;
22 | import android.widget.TextView;
23 |
24 | import java.lang.ref.WeakReference;
25 | import java.text.SimpleDateFormat;
26 | import java.util.Date;
27 |
28 | import ru.sash0k.bluetooth_terminal.DeviceData;
29 | import ru.sash0k.bluetooth_terminal.R;
30 | import ru.sash0k.bluetooth_terminal.Utils;
31 | import ru.sash0k.bluetooth_terminal.bluetooth.DeviceConnector;
32 | import ru.sash0k.bluetooth_terminal.bluetooth.DeviceListActivity;
33 |
34 | public final class DeviceControlActivity extends BaseActivity {
35 | private static final String DEVICE_NAME = "DEVICE_NAME";
36 | private static final String LOG = "LOG";
37 |
38 | // Подсветка crc
39 | private static final String CRC_OK = "#FFFF00";
40 | private static final String CRC_BAD = "#FF0000";
41 |
42 | private static final SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss.SSS");
43 |
44 | private static String MSG_NOT_CONNECTED;
45 | private static String MSG_CONNECTING;
46 | private static String MSG_CONNECTED;
47 |
48 | private static DeviceConnector connector;
49 | private static BluetoothResponseHandler mHandler;
50 |
51 | private StringBuilder logHtml;
52 | private TextView logTextView;
53 | private EditText commandEditText;
54 |
55 | // Настройки приложения
56 | private int logLimitSize;
57 | private boolean hexMode, checkSum, needClean, logLimit;
58 | private boolean show_timings, show_direction;
59 | private String command_ending;
60 | private String deviceName;
61 |
62 | @Override
63 | protected void onCreate(Bundle savedInstanceState) {
64 | super.onCreate(savedInstanceState);
65 | PreferenceManager.setDefaultValues(this, R.xml.settings_activity, false);
66 |
67 | if (mHandler == null) mHandler = new BluetoothResponseHandler(this);
68 | else mHandler.setTarget(this);
69 |
70 | MSG_NOT_CONNECTED = getString(R.string.msg_not_connected);
71 | MSG_CONNECTING = getString(R.string.msg_connecting);
72 | MSG_CONNECTED = getString(R.string.msg_connected);
73 |
74 | setContentView(R.layout.activity_terminal);
75 | if (isConnected() && (savedInstanceState != null)) {
76 | setDeviceName(savedInstanceState.getString(DEVICE_NAME));
77 | } else getActionBar().setSubtitle(MSG_NOT_CONNECTED);
78 |
79 | this.logHtml = new StringBuilder();
80 | if (savedInstanceState != null) this.logHtml.append(savedInstanceState.getString(LOG));
81 |
82 | this.logTextView = (TextView) findViewById(R.id.log_textview);
83 | this.logTextView.setMovementMethod(new ScrollingMovementMethod());
84 | this.logTextView.setText(Html.fromHtml(logHtml.toString()));
85 |
86 | this.commandEditText = (EditText) findViewById(R.id.command_edittext);
87 | // soft-keyboard send button
88 | this.commandEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
89 | @Override
90 | public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
91 | if (actionId == EditorInfo.IME_ACTION_SEND) {
92 | sendCommand(null);
93 | return true;
94 | }
95 | return false;
96 | }
97 | });
98 | // hardware Enter button
99 | this.commandEditText.setOnKeyListener(new View.OnKeyListener() {
100 | public boolean onKey(View v, int keyCode, KeyEvent event) {
101 | if (event.getAction() == KeyEvent.ACTION_DOWN) {
102 | switch (keyCode) {
103 | case KeyEvent.KEYCODE_ENTER:
104 | sendCommand(null);
105 | return true;
106 | default:
107 | break;
108 | }
109 | }
110 | return false;
111 | }
112 | });
113 |
114 | Intent intent = getIntent();
115 | String action = intent.getAction();
116 | String type = intent.getType();
117 |
118 | if (Intent.ACTION_SEND.equals(action) && type != null) {
119 | if ("text/plain".equals(type)) {
120 | String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
121 | if (sharedText != null) {
122 | EditText commandEditText = (EditText)findViewById(R.id.command_edittext);
123 | commandEditText.setText(sharedText);
124 | }
125 | }
126 | }
127 | }
128 | // ==========================================================================
129 |
130 | @Override
131 | protected void onSaveInstanceState(Bundle outState) {
132 | super.onSaveInstanceState(outState);
133 | outState.putString(DEVICE_NAME, deviceName);
134 | if (logTextView != null) {
135 | outState.putString(LOG, logHtml.toString());
136 | }
137 | }
138 | // ============================================================================
139 |
140 |
141 | /**
142 | * Проверка готовности соединения
143 | */
144 | private boolean isConnected() {
145 | return (connector != null) && (connector.getState() == DeviceConnector.STATE_CONNECTED);
146 | }
147 | // ==========================================================================
148 |
149 |
150 | /**
151 | * Разорвать соединение
152 | */
153 | private void stopConnection() {
154 | if (connector != null) {
155 | connector.stop();
156 | connector = null;
157 | deviceName = null;
158 | }
159 | }
160 | // ==========================================================================
161 |
162 |
163 | /**
164 | * Список устройств для подключения
165 | */
166 | private void startDeviceListActivity() {
167 | stopConnection();
168 | Intent serverIntent = new Intent(this, DeviceListActivity.class);
169 | startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
170 | }
171 | // ============================================================================
172 |
173 |
174 | /**
175 | * Обработка аппаратной кнопки "Поиск"
176 | *
177 | * @return
178 | */
179 | @Override
180 | public boolean onSearchRequested() {
181 | if (super.isAdapterReady()) startDeviceListActivity();
182 | return false;
183 | }
184 | // ==========================================================================
185 |
186 |
187 | @Override
188 | public boolean onCreateOptionsMenu(Menu menu) {
189 | getMenuInflater().inflate(R.menu.device_control_activity, menu);
190 | final MenuItem bluetooth = menu.findItem(R.id.menu_search);
191 | if (bluetooth != null) bluetooth.setIcon(this.isConnected() ?
192 | R.drawable.ic_action_device_bluetooth_connected :
193 | R.drawable.ic_action_device_bluetooth);
194 | return true;
195 | }
196 | // ============================================================================
197 |
198 |
199 | @Override
200 | public boolean onOptionsItemSelected(MenuItem item) {
201 | switch (item.getItemId()) {
202 |
203 | case R.id.menu_search:
204 | if (super.isAdapterReady()) {
205 | if (isConnected()) stopConnection();
206 | else startDeviceListActivity();
207 | } else {
208 | Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
209 | if (checkBluetoothPermission(REQUEST_ENABLE_BT)) startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
210 | }
211 | return true;
212 |
213 | case R.id.menu_clear:
214 | if (logTextView != null) logTextView.setText("");
215 | return true;
216 |
217 | case R.id.menu_send:
218 | if (logTextView != null) {
219 | final String msg = logTextView.getText().toString();
220 | final Intent intent = new Intent(Intent.ACTION_SEND);
221 | intent.setType("text/plain");
222 | intent.putExtra(Intent.EXTRA_TEXT, msg);
223 | startActivity(Intent.createChooser(intent, getString(R.string.menu_send)));
224 | }
225 | return true;
226 |
227 | case R.id.menu_settings:
228 | final Intent intent = new Intent(this, SettingsActivity.class);
229 | startActivity(intent);
230 | return true;
231 |
232 | default:
233 | return super.onOptionsItemSelected(item);
234 | }
235 | }
236 | // ============================================================================
237 |
238 |
239 | @Override
240 | public void onStart() {
241 | super.onStart();
242 |
243 | // hex mode
244 | final String mode = Utils.getPrefence(this, getString(R.string.pref_commands_mode));
245 | this.hexMode = "HEX".equals(mode);
246 | if (hexMode) {
247 | commandEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
248 | commandEditText.setFilters(new InputFilter[]{new Utils.InputFilterHex()});
249 | } else {
250 | commandEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
251 | commandEditText.setFilters(new InputFilter[]{});
252 | }
253 |
254 | // checksum
255 | final String checkSum = Utils.getPrefence(this, getString(R.string.pref_checksum_mode));
256 | this.checkSum = "Modulo 256".equals(checkSum);
257 |
258 | // Окончание строки
259 | this.command_ending = getCommandEnding();
260 |
261 | // Формат отображения лога команд
262 | this.show_timings = Utils.getBooleanPrefence(this, getString(R.string.pref_log_timing));
263 | this.show_direction = Utils.getBooleanPrefence(this, getString(R.string.pref_log_direction));
264 | this.needClean = Utils.getBooleanPrefence(this, getString(R.string.pref_need_clean));
265 | this.logLimit = Utils.getBooleanPrefence(this, getString(R.string.pref_log_limit));
266 | this.logLimitSize = Utils.formatNumber(Utils.getPrefence(this, getString(R.string.pref_log_limit_size)));
267 | }
268 | // ============================================================================
269 |
270 |
271 | /**
272 | * Получить из настроек признак окончания команды
273 | */
274 | private String getCommandEnding() {
275 | String result = Utils.getPrefence(this, getString(R.string.pref_commands_ending));
276 | if (result.equals("\\r\\n")) result = "\r\n";
277 | else if (result.equals("\\n")) result = "\n";
278 | else if (result.equals("\\r")) result = "\r";
279 | else result = "";
280 | return result;
281 | }
282 | // ============================================================================
283 |
284 |
285 | @Override
286 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
287 | super.onActivityResult(requestCode, resultCode, data);
288 | switch (requestCode) {
289 | case REQUEST_CONNECT_DEVICE:
290 | // When DeviceListActivity returns with a device to connect
291 | if (resultCode == Activity.RESULT_OK) {
292 | String address = data.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
293 | BluetoothDevice device = btAdapter.getRemoteDevice(address);
294 | if (super.isAdapterReady() && (connector == null)) setupConnector(device);
295 | }
296 | break;
297 | case REQUEST_ENABLE_BT:
298 | // When the request to enable Bluetooth returns
299 | super.pendingRequestEnableBt = false;
300 | if (resultCode != Activity.RESULT_OK) {
301 | Utils.log("BT not enabled");
302 | }
303 | break;
304 | }
305 | }
306 | // ==========================================================================
307 |
308 |
309 | /**
310 | * Установка соединения с устройством
311 | */
312 | private void setupConnector(BluetoothDevice connectedDevice) {
313 | stopConnection();
314 | try {
315 | String emptyName = getString(R.string.empty_device_name);
316 | DeviceData data = new DeviceData(connectedDevice, emptyName);
317 | connector = new DeviceConnector(data, mHandler);
318 | connector.connect();
319 | } catch (IllegalArgumentException e) {
320 | Utils.log("setupConnector failed: " + e.getMessage());
321 | }
322 | }
323 | // ==========================================================================
324 |
325 |
326 | /**
327 | * Отправка команды устройству
328 | */
329 | public void sendCommand(View view) {
330 | if (commandEditText != null) {
331 | String commandString = commandEditText.getText().toString();
332 | if (commandString.isEmpty()) return;
333 |
334 | // Дополнение команд в hex
335 | if (hexMode && (commandString.length() % 2 == 1)) {
336 | commandString = "0" + commandString;
337 | commandEditText.setText(commandString);
338 | }
339 |
340 | // checksum
341 | if (checkSum) {
342 | commandString += Utils.calcModulo256(commandString);
343 | }
344 |
345 | byte[] command = (hexMode ? Utils.toHex(commandString) : commandString.getBytes());
346 | if (command_ending != null) command = Utils.concat(command, command_ending.getBytes());
347 | if (isConnected()) {
348 | connector.write(command);
349 | appendLog(commandString, hexMode, true, needClean);
350 | }
351 | }
352 | }
353 | // ==========================================================================
354 |
355 |
356 | /**
357 | * Добавление ответа в лог
358 | *
359 | * @param message - текст для отображения
360 | * @param outgoing - направление передачи
361 | * @param clean - удалять команду из поля ввода после отправки
362 | */
363 | void appendLog(String message, boolean hexMode, boolean outgoing, boolean clean) {
364 |
365 | // если установлено ограничение на логи, проверить и почистить
366 | if (this.logLimit && this.logLimitSize > 0 && logTextView.getLineCount() > this.logLimitSize) {
367 | logTextView.setText("");
368 | }
369 |
370 | StringBuilder msg = new StringBuilder();
371 | if (show_timings) msg.append("[").append(timeformat.format(new Date())).append("]");
372 | if (show_direction) {
373 | final String arrow = (outgoing ? " << " : " >> ");
374 | msg.append(arrow);
375 | } else msg.append(" ");
376 |
377 | // Убрать символы переноса строки \r\n
378 | message = message.replace("\r", "").replace("\n", "");
379 |
380 | // Проверка контрольной суммы ответа
381 | String crc = "";
382 | boolean crcOk = false;
383 | if (checkSum) {
384 | int crcPos = message.length() - 2;
385 | crc = message.substring(crcPos);
386 | message = message.substring(0, crcPos);
387 | crcOk = outgoing || crc.equals(Utils.calcModulo256(message).toUpperCase());
388 | if (hexMode) crc = Utils.printHex(crc.toUpperCase());
389 | }
390 |
391 | // Лог в html
392 | msg.append("")
393 | .append(hexMode ? Utils.printHex(message) : message)
394 | .append(checkSum ? Utils.mark(crc, crcOk ? CRC_OK : CRC_BAD) : "")
395 | .append("")
396 | .append("
");
397 |
398 | logHtml.append(msg);
399 | logTextView.append(Html.fromHtml(msg.toString()));
400 |
401 | final int scrollAmount = logTextView.getLayout().getLineTop(logTextView.getLineCount()) - logTextView.getHeight();
402 | if (scrollAmount > 0)
403 | logTextView.scrollTo(0, scrollAmount);
404 | else logTextView.scrollTo(0, 0);
405 |
406 | if (clean) commandEditText.setText("");
407 | }
408 | // =========================================================================
409 |
410 |
411 | void setDeviceName(String deviceName) {
412 | this.deviceName = deviceName;
413 | getActionBar().setSubtitle(deviceName);
414 | }
415 | // ==========================================================================
416 |
417 | /**
418 | * Обработчик приёма данных от bluetooth-потока
419 | */
420 | private static class BluetoothResponseHandler extends Handler {
421 | private WeakReference mActivity;
422 |
423 | public BluetoothResponseHandler(DeviceControlActivity activity) {
424 | mActivity = new WeakReference(activity);
425 | }
426 |
427 | public void setTarget(DeviceControlActivity target) {
428 | mActivity.clear();
429 | mActivity = new WeakReference(target);
430 | }
431 |
432 | @Override
433 | public void handleMessage(Message msg) {
434 | DeviceControlActivity activity = mActivity.get();
435 | if (activity != null) {
436 | switch (msg.what) {
437 | case MESSAGE_STATE_CHANGE:
438 |
439 | Utils.log("MESSAGE_STATE_CHANGE: " + msg.arg1);
440 | final ActionBar bar = activity.getActionBar();
441 | switch (msg.arg1) {
442 | case DeviceConnector.STATE_CONNECTED:
443 | bar.setSubtitle(MSG_CONNECTED);
444 | break;
445 | case DeviceConnector.STATE_CONNECTING:
446 | bar.setSubtitle(MSG_CONNECTING);
447 | break;
448 | case DeviceConnector.STATE_NONE:
449 | bar.setSubtitle(MSG_NOT_CONNECTED);
450 | break;
451 | }
452 | activity.invalidateOptionsMenu();
453 | break;
454 |
455 | case MESSAGE_READ:
456 | final String readMessage = (String) msg.obj;
457 | if (readMessage != null) {
458 | activity.appendLog(readMessage, false, false, false);
459 | }
460 | break;
461 |
462 | case MESSAGE_DEVICE_NAME:
463 | activity.setDeviceName((String) msg.obj);
464 | break;
465 |
466 | case MESSAGE_WRITE:
467 | // stub
468 | break;
469 |
470 | case MESSAGE_TOAST:
471 | // stub
472 | break;
473 | }
474 | }
475 | }
476 | }
477 | // ==========================================================================
478 | }
--------------------------------------------------------------------------------