├── .gitignore
├── LICENSE.txt
├── README.md
├── app
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── de
│ │ └── kai_morich
│ │ └── simple_usb_terminal
│ │ ├── Constants.java
│ │ ├── CustomProber.java
│ │ ├── DevicesFragment.java
│ │ ├── MainActivity.java
│ │ ├── SerialListener.java
│ │ ├── SerialService.java
│ │ ├── SerialSocket.java
│ │ ├── TerminalFragment.java
│ │ └── TextUtil.java
│ └── res
│ ├── drawable-hdpi
│ ├── ic_clear_white_24dp.png
│ └── ic_notification.png
│ ├── drawable-mdpi
│ ├── ic_clear_white_24dp.png
│ └── ic_notification.png
│ ├── drawable-xhdpi
│ ├── ic_clear_white_24dp.png
│ └── ic_notification.png
│ ├── drawable-xxhdpi
│ ├── ic_clear_white_24dp.png
│ └── ic_notification.png
│ ├── drawable-xxxhdpi
│ ├── ic_clear_white_24dp.png
│ └── ic_notification.png
│ ├── drawable
│ ├── ic_block_white_24dp.xml
│ ├── ic_delete_white_24dp.xml
│ └── ic_send_white_24dp.xml
│ ├── layout
│ ├── activity_main.xml
│ ├── device_list_header.xml
│ ├── device_list_item.xml
│ └── fragment_terminal.xml
│ ├── menu
│ ├── menu_devices.xml
│ └── menu_terminal.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ ├── values
│ ├── arrays.xml
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
│ └── xml
│ └── usb_device_filter.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | /.gradle/
3 | /.idea/
4 | /local.properties
5 | /app/build/
6 | /build/
7 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Kai Morich
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://www.codacy.com/manual/kai-morich/SimpleUsbTerminal?utm_source=github.com&utm_medium=referral&utm_content=kai-morich/SimpleUsbTerminal&utm_campaign=Badge_Grade)
2 |
3 | # SimpleUsbTerminal
4 |
5 | This Android app provides a line-oriented terminal / console for devices with a serial / UART interface connected with a USB-to-serial-converter.
6 |
7 | It supports USB to serial converters based on
8 | - FTDI FT232, FT2232, ...
9 | - Prolific PL2303
10 | - Silabs CP2102, CP2105, ...
11 | - Qinheng CH340, CH341
12 |
13 | and devices implementing the USB CDC protocol like
14 | - Arduino using ATmega32U4
15 | - Digispark using V-USB software USB
16 | - BBC micro:bit using ARM mbed DAPLink firmware
17 | - Pi Pico
18 | - ...
19 |
20 | ## Features
21 |
22 | - permission handling on device connection
23 | - foreground service to buffer receive data while the app is rotating, in background, ...
24 | - send BREAK
25 | - show control lines
26 | - RTS/CTS, DTR/DSR, XON/XOFF flow control
27 |
28 | ## Credits
29 |
30 | The app uses the [usb-serial-for-android](https://github.com/mik3y/usb-serial-for-android) library.
31 |
32 | ## Motivation
33 |
34 | I got various requests asking for help with Android development or source code for my
35 | [Serial USB Terminal](https://play.google.com/store/apps/details?id=de.kai_morich.serial_usb_terminal) app.
36 | Here you find a simplified version of my app.
37 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | }
4 |
5 | android {
6 | compileSdkVersion 34
7 | defaultConfig {
8 | targetSdkVersion 34
9 | minSdkVersion 19
10 | vectorDrawables.useSupportLibrary true
11 |
12 | applicationId "de.kai_morich.simple_usb_terminal"
13 | versionCode 1
14 | versionName "1.0"
15 | }
16 | compileOptions {
17 | sourceCompatibility JavaVersion.VERSION_1_8
18 | targetCompatibility JavaVersion.VERSION_1_8
19 | }
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | namespace 'de.kai_morich.simple_usb_terminal'
27 | }
28 |
29 | dependencies {
30 | implementation 'com.github.mik3y:usb-serial-for-android:3.8.0' // maven jitpack
31 | //implementation('com.github.mik3y:usb-serial-for-android:3.8.0beta') { changing = true } // maven local
32 |
33 | implementation 'androidx.appcompat:appcompat:1.6.1'
34 | implementation 'com.google.android.material:material:1.12.0'
35 | }
36 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
16 |
20 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
35 |
36 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/Constants.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | class Constants {
4 |
5 | // values have to be globally unique
6 | static final String INTENT_ACTION_GRANT_USB = BuildConfig.APPLICATION_ID + ".GRANT_USB";
7 | static final String INTENT_ACTION_DISCONNECT = BuildConfig.APPLICATION_ID + ".Disconnect";
8 | static final String NOTIFICATION_CHANNEL = BuildConfig.APPLICATION_ID + ".Channel";
9 | static final String INTENT_CLASS_MAIN_ACTIVITY = BuildConfig.APPLICATION_ID + ".MainActivity";
10 |
11 | // values have to be unique within each app
12 | static final int NOTIFY_MANAGER_START_FOREGROUND_SERVICE = 1001;
13 |
14 | private Constants() {}
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/CustomProber.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import com.hoho.android.usbserial.driver.FtdiSerialDriver;
4 | import com.hoho.android.usbserial.driver.ProbeTable;
5 | import com.hoho.android.usbserial.driver.UsbSerialProber;
6 |
7 | /**
8 | * add devices here, that are not known to DefaultProber
9 | *
10 | * if the App should auto start for these devices, also
11 | * add IDs to app/src/main/res/xml/usb_device_filter.xml
12 | */
13 | class CustomProber {
14 |
15 | static UsbSerialProber getCustomProber() {
16 | ProbeTable customTable = new ProbeTable();
17 | customTable.addProduct(0x1234, 0xabcd, FtdiSerialDriver.class); // e.g. device with custom VID+PID
18 | return new UsbSerialProber(customTable);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/DevicesFragment.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import android.app.AlertDialog;
4 | import android.content.Context;
5 | import android.content.DialogInterface;
6 | import android.hardware.usb.UsbDevice;
7 | import android.hardware.usb.UsbManager;
8 | import android.os.Bundle;
9 |
10 | import androidx.annotation.NonNull;
11 | import androidx.fragment.app.Fragment;
12 | import androidx.fragment.app.ListFragment;
13 | import android.view.Menu;
14 | import android.view.MenuInflater;
15 | import android.view.MenuItem;
16 | import android.view.View;
17 | import android.view.ViewGroup;
18 | import android.widget.ArrayAdapter;
19 | import android.widget.ListView;
20 | import android.widget.TextView;
21 | import android.widget.Toast;
22 |
23 | import com.hoho.android.usbserial.driver.UsbSerialDriver;
24 | import com.hoho.android.usbserial.driver.UsbSerialProber;
25 |
26 | import java.util.ArrayList;
27 | import java.util.Locale;
28 |
29 | public class DevicesFragment extends ListFragment {
30 |
31 | static class ListItem {
32 | UsbDevice device;
33 | int port;
34 | UsbSerialDriver driver;
35 |
36 | ListItem(UsbDevice device, int port, UsbSerialDriver driver) {
37 | this.device = device;
38 | this.port = port;
39 | this.driver = driver;
40 | }
41 | }
42 |
43 | private final ArrayList listItems = new ArrayList<>();
44 | private ArrayAdapter listAdapter;
45 | private int baudRate = 19200;
46 |
47 | @Override
48 | public void onCreate(Bundle savedInstanceState) {
49 | super.onCreate(savedInstanceState);
50 | setHasOptionsMenu(true);
51 | listAdapter = new ArrayAdapter(getActivity(), 0, listItems) {
52 | @NonNull
53 | @Override
54 | public View getView(int position, View view, @NonNull ViewGroup parent) {
55 | ListItem item = listItems.get(position);
56 | if (view == null)
57 | view = getActivity().getLayoutInflater().inflate(R.layout.device_list_item, parent, false);
58 | TextView text1 = view.findViewById(R.id.text1);
59 | TextView text2 = view.findViewById(R.id.text2);
60 | if(item.driver == null)
61 | text1.setText("");
62 | else if(item.driver.getPorts().size() == 1)
63 | text1.setText(item.driver.getClass().getSimpleName().replace("SerialDriver",""));
64 | else
65 | text1.setText(item.driver.getClass().getSimpleName().replace("SerialDriver","")+", Port "+item.port);
66 | text2.setText(String.format(Locale.US, "Vendor %04X, Product %04X", item.device.getVendorId(), item.device.getProductId()));
67 | return view;
68 | }
69 | };
70 | }
71 |
72 | @Override
73 | public void onActivityCreated(Bundle savedInstanceState) {
74 | super.onActivityCreated(savedInstanceState);
75 | setListAdapter(null);
76 | View header = getActivity().getLayoutInflater().inflate(R.layout.device_list_header, null, false);
77 | getListView().addHeaderView(header, null, false);
78 | setEmptyText("");
79 | ((TextView) getListView().getEmptyView()).setTextSize(18);
80 | setListAdapter(listAdapter);
81 | }
82 |
83 | @Override
84 | public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
85 | inflater.inflate(R.menu.menu_devices, menu);
86 | }
87 |
88 | @Override
89 | public void onResume() {
90 | super.onResume();
91 | refresh();
92 | }
93 |
94 | @Override
95 | public boolean onOptionsItemSelected(MenuItem item) {
96 | int id = item.getItemId();
97 | if(id == R.id.refresh) {
98 | refresh();
99 | return true;
100 | } else if (id ==R.id.baud_rate) {
101 | final String[] baudRates = getResources().getStringArray(R.array.baud_rates);
102 | int pos = java.util.Arrays.asList(baudRates).indexOf(String.valueOf(baudRate));
103 | AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
104 | builder.setTitle("Baud rate");
105 | builder.setSingleChoiceItems(baudRates, pos, new DialogInterface.OnClickListener() {
106 | public void onClick(DialogInterface dialog, int item) {
107 | baudRate = Integer.parseInt(baudRates[item]);
108 | dialog.dismiss();
109 | }
110 | });
111 | builder.create().show();
112 | return true;
113 | } else {
114 | return super.onOptionsItemSelected(item);
115 | }
116 | }
117 |
118 | void refresh() {
119 | UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
120 | UsbSerialProber usbDefaultProber = UsbSerialProber.getDefaultProber();
121 | UsbSerialProber usbCustomProber = CustomProber.getCustomProber();
122 | listItems.clear();
123 | for(UsbDevice device : usbManager.getDeviceList().values()) {
124 | UsbSerialDriver driver = usbDefaultProber.probeDevice(device);
125 | if(driver == null) {
126 | driver = usbCustomProber.probeDevice(device);
127 | }
128 | if(driver != null) {
129 | for(int port = 0; port < driver.getPorts().size(); port++)
130 | listItems.add(new ListItem(device, port, driver));
131 | } else {
132 | listItems.add(new ListItem(device, 0, null));
133 | }
134 | }
135 | listAdapter.notifyDataSetChanged();
136 | }
137 |
138 | @Override
139 | public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
140 | ListItem item = listItems.get(position-1);
141 | if(item.driver == null) {
142 | Toast.makeText(getActivity(), "no driver", Toast.LENGTH_SHORT).show();
143 | } else {
144 | Bundle args = new Bundle();
145 | args.putInt("device", item.device.getDeviceId());
146 | args.putInt("port", item.port);
147 | args.putInt("baud", baudRate);
148 | Fragment fragment = new TerminalFragment();
149 | fragment.setArguments(args);
150 | getParentFragmentManager().beginTransaction().replace(R.id.fragment, fragment, "terminal").addToBackStack(null).commit();
151 | }
152 | }
153 |
154 | }
155 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/MainActivity.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import androidx.fragment.app.FragmentManager;
6 | import androidx.appcompat.app.AppCompatActivity;
7 | import androidx.appcompat.widget.Toolbar;
8 |
9 | public class MainActivity extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener {
10 |
11 | @Override
12 | protected void onCreate(Bundle savedInstanceState) {
13 | super.onCreate(savedInstanceState);
14 | setContentView(R.layout.activity_main);
15 | Toolbar toolbar = findViewById(R.id.toolbar);
16 | setSupportActionBar(toolbar);
17 | getSupportFragmentManager().addOnBackStackChangedListener(this);
18 | if (savedInstanceState == null)
19 | getSupportFragmentManager().beginTransaction().add(R.id.fragment, new DevicesFragment(), "devices").commit();
20 | else
21 | onBackStackChanged();
22 | }
23 |
24 | @Override
25 | public void onBackStackChanged() {
26 | getSupportActionBar().setDisplayHomeAsUpEnabled(getSupportFragmentManager().getBackStackEntryCount()>0);
27 | }
28 |
29 | @Override
30 | public boolean onSupportNavigateUp() {
31 | onBackPressed();
32 | return true;
33 | }
34 |
35 | @Override
36 | protected void onNewIntent(Intent intent) {
37 | if ("android.hardware.usb.action.USB_DEVICE_ATTACHED".equals(intent.getAction())) {
38 | TerminalFragment terminal = (TerminalFragment)getSupportFragmentManager().findFragmentByTag("terminal");
39 | if (terminal != null)
40 | terminal.status("USB device detected");
41 | }
42 | super.onNewIntent(intent);
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/SerialListener.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import java.util.ArrayDeque;
4 |
5 | interface SerialListener {
6 | void onSerialConnect ();
7 | void onSerialConnectError (Exception e);
8 | void onSerialRead (byte[] data); // socket -> service
9 | void onSerialRead (ArrayDeque datas); // service -> UI thread
10 | void onSerialIoError (Exception e);
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/SerialService.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import android.app.Notification;
4 | import android.app.NotificationChannel;
5 | import android.app.NotificationManager;
6 | import android.app.PendingIntent;
7 | import android.app.Service;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.os.Binder;
11 | import android.os.Build;
12 | import android.os.Handler;
13 | import android.os.IBinder;
14 | import android.os.Looper;
15 |
16 | import androidx.annotation.Nullable;
17 | import androidx.annotation.RequiresApi;
18 | import androidx.core.app.NotificationCompat;
19 |
20 | import java.io.IOException;
21 | import java.util.ArrayDeque;
22 |
23 | /**
24 | * create notification and queue serial data while activity is not in the foreground
25 | * use listener chain: SerialSocket -> SerialService -> UI fragment
26 | */
27 | public class SerialService extends Service implements SerialListener {
28 |
29 | class SerialBinder extends Binder {
30 | SerialService getService() { return SerialService.this; }
31 | }
32 |
33 | private enum QueueType {Connect, ConnectError, Read, IoError}
34 |
35 | private static class QueueItem {
36 | QueueType type;
37 | ArrayDeque datas;
38 | Exception e;
39 |
40 | QueueItem(QueueType type) { this.type=type; if(type==QueueType.Read) init(); }
41 | QueueItem(QueueType type, Exception e) { this.type=type; this.e=e; }
42 | QueueItem(QueueType type, ArrayDeque datas) { this.type=type; this.datas=datas; }
43 |
44 | void init() { datas = new ArrayDeque<>(); }
45 | void add(byte[] data) { datas.add(data); }
46 | }
47 |
48 | private final Handler mainLooper;
49 | private final IBinder binder;
50 | private final ArrayDeque queue1, queue2;
51 | private final QueueItem lastRead;
52 |
53 | private SerialSocket socket;
54 | private SerialListener listener;
55 | private boolean connected;
56 |
57 | /**
58 | * Lifecylce
59 | */
60 | public SerialService() {
61 | mainLooper = new Handler(Looper.getMainLooper());
62 | binder = new SerialBinder();
63 | queue1 = new ArrayDeque<>();
64 | queue2 = new ArrayDeque<>();
65 | lastRead = new QueueItem(QueueType.Read);
66 | }
67 |
68 | @Override
69 | public void onDestroy() {
70 | cancelNotification();
71 | disconnect();
72 | super.onDestroy();
73 | }
74 |
75 | @Nullable
76 | @Override
77 | public IBinder onBind(Intent intent) {
78 | return binder;
79 | }
80 |
81 | /**
82 | * Api
83 | */
84 | public void connect(SerialSocket socket) throws IOException {
85 | socket.connect(this);
86 | this.socket = socket;
87 | connected = true;
88 | }
89 |
90 | public void disconnect() {
91 | connected = false; // ignore data,errors while disconnecting
92 | cancelNotification();
93 | if(socket != null) {
94 | socket.disconnect();
95 | socket = null;
96 | }
97 | }
98 |
99 | public void write(byte[] data) throws IOException {
100 | if(!connected)
101 | throw new IOException("not connected");
102 | socket.write(data);
103 | }
104 |
105 | public void attach(SerialListener listener) {
106 | if(Looper.getMainLooper().getThread() != Thread.currentThread())
107 | throw new IllegalArgumentException("not in main thread");
108 | initNotification();
109 | cancelNotification();
110 | // use synchronized() to prevent new items in queue2
111 | // new items will not be added to queue1 because mainLooper.post and attach() run in main thread
112 | synchronized (this) {
113 | this.listener = listener;
114 | }
115 | for(QueueItem item : queue1) {
116 | switch(item.type) {
117 | case Connect: listener.onSerialConnect (); break;
118 | case ConnectError: listener.onSerialConnectError (item.e); break;
119 | case Read: listener.onSerialRead (item.datas); break;
120 | case IoError: listener.onSerialIoError (item.e); break;
121 | }
122 | }
123 | for(QueueItem item : queue2) {
124 | switch(item.type) {
125 | case Connect: listener.onSerialConnect (); break;
126 | case ConnectError: listener.onSerialConnectError (item.e); break;
127 | case Read: listener.onSerialRead (item.datas); break;
128 | case IoError: listener.onSerialIoError (item.e); break;
129 | }
130 | }
131 | queue1.clear();
132 | queue2.clear();
133 | }
134 |
135 | public void detach() {
136 | if(connected)
137 | createNotification();
138 | // items already in event queue (posted before detach() to mainLooper) will end up in queue1
139 | // items occurring later, will be moved directly to queue2
140 | // detach() and mainLooper.post run in the main thread, so all items are caught
141 | listener = null;
142 | }
143 |
144 | private void initNotification() {
145 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
146 | NotificationChannel nc = new NotificationChannel(Constants.NOTIFICATION_CHANNEL, "Background service", NotificationManager.IMPORTANCE_LOW);
147 | nc.setShowBadge(false);
148 | NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
149 | nm.createNotificationChannel(nc);
150 | }
151 | }
152 |
153 | @RequiresApi(Build.VERSION_CODES.O)
154 | public boolean areNotificationsEnabled() {
155 | NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
156 | NotificationChannel nc = nm.getNotificationChannel(Constants.NOTIFICATION_CHANNEL);
157 | return nm.areNotificationsEnabled() && nc != null && nc.getImportance() > NotificationManager.IMPORTANCE_NONE;
158 | }
159 |
160 | private void createNotification() {
161 | Intent disconnectIntent = new Intent()
162 | .setPackage(getPackageName())
163 | .setAction(Constants.INTENT_ACTION_DISCONNECT);
164 | Intent restartIntent = new Intent()
165 | .setClassName(this, Constants.INTENT_CLASS_MAIN_ACTIVITY)
166 | .setAction(Intent.ACTION_MAIN)
167 | .addCategory(Intent.CATEGORY_LAUNCHER);
168 | int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0;
169 | PendingIntent disconnectPendingIntent = PendingIntent.getBroadcast(this, 1, disconnectIntent, flags);
170 | PendingIntent restartPendingIntent = PendingIntent.getActivity(this, 1, restartIntent, flags);
171 | NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL)
172 | .setSmallIcon(R.drawable.ic_notification)
173 | .setColor(getResources().getColor(R.color.colorPrimary))
174 | .setContentTitle(getResources().getString(R.string.app_name))
175 | .setContentText(socket != null ? "Connected to "+socket.getName() : "Background Service")
176 | .setContentIntent(restartPendingIntent)
177 | .setOngoing(true)
178 | .addAction(new NotificationCompat.Action(R.drawable.ic_clear_white_24dp, "Disconnect", disconnectPendingIntent));
179 | // @drawable/ic_notification created with Android Studio -> New -> Image Asset using @color/colorPrimaryDark as background color
180 | // Android < API 21 does not support vectorDrawables in notifications, so both drawables used here, are created as .png instead of .xml
181 | Notification notification = builder.build();
182 | startForeground(Constants.NOTIFY_MANAGER_START_FOREGROUND_SERVICE, notification);
183 | }
184 |
185 | private void cancelNotification() {
186 | stopForeground(true);
187 | }
188 |
189 | /**
190 | * SerialListener
191 | */
192 | public void onSerialConnect() {
193 | if(connected) {
194 | synchronized (this) {
195 | if (listener != null) {
196 | mainLooper.post(() -> {
197 | if (listener != null) {
198 | listener.onSerialConnect();
199 | } else {
200 | queue1.add(new QueueItem(QueueType.Connect));
201 | }
202 | });
203 | } else {
204 | queue2.add(new QueueItem(QueueType.Connect));
205 | }
206 | }
207 | }
208 | }
209 |
210 | public void onSerialConnectError(Exception e) {
211 | if(connected) {
212 | synchronized (this) {
213 | if (listener != null) {
214 | mainLooper.post(() -> {
215 | if (listener != null) {
216 | listener.onSerialConnectError(e);
217 | } else {
218 | queue1.add(new QueueItem(QueueType.ConnectError, e));
219 | disconnect();
220 | }
221 | });
222 | } else {
223 | queue2.add(new QueueItem(QueueType.ConnectError, e));
224 | disconnect();
225 | }
226 | }
227 | }
228 | }
229 |
230 | public void onSerialRead(ArrayDeque datas) { throw new UnsupportedOperationException(); }
231 |
232 | /**
233 | * reduce number of UI updates by merging data chunks.
234 | * Data can arrive at hundred chunks per second, but the UI can only
235 | * perform a dozen updates if receiveText already contains much text.
236 | *
237 | * On new data inform UI thread once (1).
238 | * While not consumed (2), add more data (3).
239 | */
240 | public void onSerialRead(byte[] data) {
241 | if(connected) {
242 | synchronized (this) {
243 | if (listener != null) {
244 | boolean first;
245 | synchronized (lastRead) {
246 | first = lastRead.datas.isEmpty(); // (1)
247 | lastRead.add(data); // (3)
248 | }
249 | if(first) {
250 | mainLooper.post(() -> {
251 | ArrayDeque datas;
252 | synchronized (lastRead) {
253 | datas = lastRead.datas;
254 | lastRead.init(); // (2)
255 | }
256 | if (listener != null) {
257 | listener.onSerialRead(datas);
258 | } else {
259 | queue1.add(new QueueItem(QueueType.Read, datas));
260 | }
261 | });
262 | }
263 | } else {
264 | if(queue2.isEmpty() || queue2.getLast().type != QueueType.Read)
265 | queue2.add(new QueueItem(QueueType.Read));
266 | queue2.getLast().add(data);
267 | }
268 | }
269 | }
270 | }
271 |
272 | public void onSerialIoError(Exception e) {
273 | if(connected) {
274 | synchronized (this) {
275 | if (listener != null) {
276 | mainLooper.post(() -> {
277 | if (listener != null) {
278 | listener.onSerialIoError(e);
279 | } else {
280 | queue1.add(new QueueItem(QueueType.IoError, e));
281 | disconnect();
282 | }
283 | });
284 | } else {
285 | queue2.add(new QueueItem(QueueType.IoError, e));
286 | disconnect();
287 | }
288 | }
289 | }
290 | }
291 |
292 | }
293 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/SerialSocket.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import android.app.Activity;
4 | import android.content.BroadcastReceiver;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.content.IntentFilter;
8 | import android.hardware.usb.UsbDeviceConnection;
9 | import android.util.Log;
10 |
11 | import androidx.core.content.ContextCompat;
12 |
13 | import com.hoho.android.usbserial.driver.UsbSerialPort;
14 | import com.hoho.android.usbserial.util.SerialInputOutputManager;
15 |
16 | import java.io.IOException;
17 | import java.security.InvalidParameterException;
18 |
19 | public class SerialSocket implements SerialInputOutputManager.Listener {
20 |
21 | private static final int WRITE_WAIT_MILLIS = 200; // 0 blocked infinitely on unprogrammed arduino
22 | private final static String TAG = SerialSocket.class.getSimpleName();
23 |
24 | private final BroadcastReceiver disconnectBroadcastReceiver;
25 |
26 | private final Context context;
27 | private SerialListener listener;
28 | private UsbDeviceConnection connection;
29 | private UsbSerialPort serialPort;
30 | private SerialInputOutputManager ioManager;
31 |
32 | SerialSocket(Context context, UsbDeviceConnection connection, UsbSerialPort serialPort) {
33 | if(context instanceof Activity)
34 | throw new InvalidParameterException("expected non UI context");
35 | this.context = context;
36 | this.connection = connection;
37 | this.serialPort = serialPort;
38 | disconnectBroadcastReceiver = new BroadcastReceiver() {
39 | @Override
40 | public void onReceive(Context context, Intent intent) {
41 | if (listener != null)
42 | listener.onSerialIoError(new IOException("background disconnect"));
43 | disconnect(); // disconnect now, else would be queued until UI re-attached
44 | }
45 | };
46 | }
47 |
48 | String getName() { return serialPort.getDriver().getClass().getSimpleName().replace("SerialDriver",""); }
49 |
50 | void connect(SerialListener listener) throws IOException {
51 | this.listener = listener;
52 | ContextCompat.registerReceiver(context, disconnectBroadcastReceiver, new IntentFilter(Constants.INTENT_ACTION_DISCONNECT), ContextCompat.RECEIVER_NOT_EXPORTED);
53 | try {
54 | serialPort.setDTR(true); // for arduino, ...
55 | serialPort.setRTS(true);
56 | } catch (UnsupportedOperationException e) {
57 | Log.d(TAG, "Failed to set initial DTR/RTS", e);
58 | }
59 | ioManager = new SerialInputOutputManager(serialPort, this);
60 | ioManager.start();
61 | }
62 |
63 | void disconnect() {
64 | listener = null; // ignore remaining data and errors
65 | if (ioManager != null) {
66 | ioManager.setListener(null);
67 | ioManager.stop();
68 | ioManager = null;
69 | }
70 | if (serialPort != null) {
71 | try {
72 | serialPort.setDTR(false);
73 | serialPort.setRTS(false);
74 | } catch (Exception ignored) {
75 | }
76 | try {
77 | serialPort.close();
78 | } catch (Exception ignored) {
79 | }
80 | serialPort = null;
81 | }
82 | if(connection != null) {
83 | connection.close();
84 | connection = null;
85 | }
86 | try {
87 | context.unregisterReceiver(disconnectBroadcastReceiver);
88 | } catch (Exception ignored) {
89 | }
90 | }
91 |
92 | void write(byte[] data) throws IOException {
93 | if(serialPort == null)
94 | throw new IOException("not connected");
95 | serialPort.write(data, WRITE_WAIT_MILLIS);
96 | }
97 |
98 | @Override
99 | public void onNewData(byte[] data) {
100 | if(listener != null)
101 | listener.onSerialRead(data);
102 | }
103 |
104 | @Override
105 | public void onRunError(Exception e) {
106 | if (listener != null)
107 | listener.onSerialIoError(e);
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/TerminalFragment.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.app.AlertDialog;
6 | import android.app.PendingIntent;
7 | import android.content.BroadcastReceiver;
8 | import android.content.ComponentName;
9 | import android.content.Context;
10 | import android.content.Intent;
11 | import android.content.IntentFilter;
12 | import android.content.ServiceConnection;
13 | import android.hardware.usb.UsbDevice;
14 | import android.hardware.usb.UsbDeviceConnection;
15 | import android.hardware.usb.UsbManager;
16 | import android.os.Build;
17 | import android.os.Bundle;
18 | import android.os.Handler;
19 | import android.os.IBinder;
20 | import android.os.Looper;
21 | import android.text.Editable;
22 | import android.text.Spannable;
23 | import android.text.SpannableStringBuilder;
24 | import android.text.method.ScrollingMovementMethod;
25 | import android.text.style.ForegroundColorSpan;
26 | import android.view.LayoutInflater;
27 | import android.view.Menu;
28 | import android.view.MenuInflater;
29 | import android.view.MenuItem;
30 | import android.view.View;
31 | import android.view.ViewGroup;
32 | import android.widget.ImageButton;
33 | import android.widget.TextView;
34 | import android.widget.Toast;
35 | import android.widget.ToggleButton;
36 |
37 | import androidx.annotation.NonNull;
38 | import androidx.annotation.Nullable;
39 | import androidx.core.content.ContextCompat;
40 | import androidx.fragment.app.Fragment;
41 |
42 | import com.hoho.android.usbserial.driver.SerialTimeoutException;
43 | import com.hoho.android.usbserial.driver.UsbSerialDriver;
44 | import com.hoho.android.usbserial.driver.UsbSerialPort;
45 | import com.hoho.android.usbserial.driver.UsbSerialProber;
46 | import com.hoho.android.usbserial.util.XonXoffFilter;
47 |
48 | import java.io.IOException;
49 | import java.util.ArrayDeque;
50 | import java.util.ArrayList;
51 | import java.util.Arrays;
52 | import java.util.EnumSet;
53 |
54 | public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
55 |
56 | private enum Connected { False, Pending, True }
57 |
58 | private final Handler mainLooper;
59 | private final BroadcastReceiver broadcastReceiver;
60 | private int deviceId, portNum, baudRate;
61 | private UsbSerialPort usbSerialPort;
62 | private SerialService service;
63 |
64 | private TextView receiveText;
65 | private TextView sendText;
66 | private ImageButton sendBtn;
67 | private TextUtil.HexWatcher hexWatcher;
68 |
69 | private Connected connected = Connected.False;
70 | private boolean initialStart = true;
71 | private boolean hexEnabled = false;
72 | private enum SendButtonState {Idle, Busy, Disabled};
73 |
74 | private ControlLines controlLines = new ControlLines();
75 | private XonXoffFilter flowControlFilter;
76 |
77 | private boolean pendingNewline = false;
78 | private String newline = TextUtil.newline_crlf;
79 |
80 | public TerminalFragment() {
81 | mainLooper = new Handler(Looper.getMainLooper());
82 | broadcastReceiver = new BroadcastReceiver() {
83 | @Override
84 | public void onReceive(Context context, Intent intent) {
85 | if(Constants.INTENT_ACTION_GRANT_USB.equals(intent.getAction())) {
86 | Boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
87 | connect(granted);
88 | }
89 | }
90 | };
91 | }
92 |
93 | /*
94 | * Lifecycle
95 | */
96 | @Override
97 | public void onCreate(@Nullable Bundle savedInstanceState) {
98 | super.onCreate(savedInstanceState);
99 | setHasOptionsMenu(true);
100 | setRetainInstance(true);
101 | deviceId = getArguments().getInt("device");
102 | portNum = getArguments().getInt("port");
103 | baudRate = getArguments().getInt("baud");
104 | }
105 |
106 | @Override
107 | public void onDestroy() {
108 | if (connected != Connected.False)
109 | disconnect();
110 | getActivity().stopService(new Intent(getActivity(), SerialService.class));
111 | super.onDestroy();
112 | }
113 |
114 | @Override
115 | public void onStart() {
116 | super.onStart();
117 | if(service != null)
118 | service.attach(this);
119 | else
120 | getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
121 | ContextCompat.registerReceiver(getActivity(), broadcastReceiver, new IntentFilter(Constants.INTENT_ACTION_GRANT_USB), ContextCompat.RECEIVER_NOT_EXPORTED);
122 | }
123 |
124 | @Override
125 | public void onStop() {
126 | getActivity().unregisterReceiver(broadcastReceiver);
127 | if(service != null && !getActivity().isChangingConfigurations())
128 | service.detach();
129 | super.onStop();
130 | }
131 |
132 | @SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
133 | @Override
134 | public void onAttach(@NonNull Activity activity) {
135 | super.onAttach(activity);
136 | getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
137 | }
138 |
139 | @Override
140 | public void onDetach() {
141 | try { getActivity().unbindService(this); } catch(Exception ignored) {}
142 | super.onDetach();
143 | }
144 |
145 | @Override
146 | public void onResume() {
147 | super.onResume();
148 | if(initialStart && service != null) {
149 | initialStart = false;
150 | getActivity().runOnUiThread(this::connect);
151 | }
152 | if(connected == Connected.True)
153 | controlLines.start();
154 | }
155 |
156 | @Override
157 | public void onPause() {
158 | controlLines.stop();
159 | super.onPause();
160 | }
161 |
162 | @Override
163 | public void onServiceConnected(ComponentName name, IBinder binder) {
164 | service = ((SerialService.SerialBinder) binder).getService();
165 | service.attach(this);
166 | if(initialStart && isResumed()) {
167 | initialStart = false;
168 | getActivity().runOnUiThread(this::connect);
169 | }
170 | }
171 |
172 | @Override
173 | public void onServiceDisconnected(ComponentName name) {
174 | service = null;
175 | }
176 |
177 | /*
178 | * UI
179 | */
180 | @Override
181 | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
182 | View view = inflater.inflate(R.layout.fragment_terminal, container, false);
183 | receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
184 | receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
185 | receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
186 |
187 | sendText = view.findViewById(R.id.send_text);
188 | sendBtn = view.findViewById(R.id.send_btn);
189 | hexWatcher = new TextUtil.HexWatcher(sendText);
190 | hexWatcher.enable(hexEnabled);
191 | sendText.addTextChangedListener(hexWatcher);
192 | sendText.setHint(hexEnabled ? "HEX mode" : "");
193 |
194 | View sendBtn = view.findViewById(R.id.send_btn);
195 | sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
196 | controlLines.onCreateView(view);
197 | return view;
198 | }
199 |
200 | @Override
201 | public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
202 | inflater.inflate(R.menu.menu_terminal, menu);
203 | }
204 |
205 | public void onPrepareOptionsMenu(@NonNull Menu menu) {
206 | menu.findItem(R.id.hex).setChecked(hexEnabled);
207 | controlLines.onPrepareOptionsMenu(menu);
208 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
209 | menu.findItem(R.id.backgroundNotification).setChecked(service != null && service.areNotificationsEnabled());
210 | } else {
211 | menu.findItem(R.id.backgroundNotification).setChecked(true);
212 | menu.findItem(R.id.backgroundNotification).setEnabled(false);
213 | }
214 | }
215 |
216 | @Override
217 | public boolean onOptionsItemSelected(MenuItem item) {
218 | int id = item.getItemId();
219 | if (id == R.id.clear) {
220 | receiveText.setText("");
221 | return true;
222 | } else if (id == R.id.newline) {
223 | String[] newlineNames = getResources().getStringArray(R.array.newline_names);
224 | String[] newlineValues = getResources().getStringArray(R.array.newline_values);
225 | int pos = Arrays.asList(newlineValues).indexOf(newline);
226 | AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
227 | builder.setTitle("Newline");
228 | builder.setSingleChoiceItems(newlineNames, pos, (dialog, which) -> {
229 | newline = newlineValues[which];
230 | dialog.dismiss();
231 | });
232 | builder.create().show();
233 | return true;
234 | } else if (id == R.id.hex) {
235 | hexEnabled = !hexEnabled;
236 | sendText.setText("");
237 | hexWatcher.enable(hexEnabled);
238 | sendText.setHint(hexEnabled ? "HEX mode" : "");
239 | item.setChecked(hexEnabled);
240 | return true;
241 | } else if (id == R.id.controlLines) {
242 | item.setChecked(controlLines.showControlLines(!item.isChecked()));
243 | return true;
244 | } else if (id == R.id.flowControl) {
245 | controlLines.selectFlowControl();
246 | return true;
247 | } else if (id == R.id.backgroundNotification) {
248 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
249 | if (!service.areNotificationsEnabled() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
250 | requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, 0);
251 | } else {
252 | showNotificationSettings();
253 | }
254 | }
255 | return true;
256 | } else if (id == R.id.sendBreak) {
257 | try {
258 | usbSerialPort.setBreak(true);
259 | Thread.sleep(100);
260 | status("send BREAK");
261 | usbSerialPort.setBreak(false);
262 | } catch (Exception e) {
263 | status("send BREAK failed: " + e.getMessage());
264 | }
265 | return true;
266 | }
267 | return super.onOptionsItemSelected(item);
268 | }
269 |
270 | /*
271 | * Serial + UI
272 | */
273 | private void connect() {
274 | connect(null);
275 | }
276 |
277 | private void connect(Boolean permissionGranted) {
278 | UsbDevice device = null;
279 | UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
280 | for(UsbDevice v : usbManager.getDeviceList().values())
281 | if(v.getDeviceId() == deviceId)
282 | device = v;
283 | if(device == null) {
284 | status("connection failed: device not found");
285 | return;
286 | }
287 | UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
288 | if(driver == null) {
289 | driver = CustomProber.getCustomProber().probeDevice(device);
290 | }
291 | if(driver == null) {
292 | status("connection failed: no driver for device");
293 | return;
294 | }
295 | if(driver.getPorts().size() < portNum) {
296 | status("connection failed: not enough ports at device");
297 | return;
298 | }
299 | usbSerialPort = driver.getPorts().get(portNum);
300 | UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
301 | if(usbConnection == null && permissionGranted == null && !usbManager.hasPermission(driver.getDevice())) {
302 | int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_MUTABLE : 0;
303 | Intent intent = new Intent(Constants.INTENT_ACTION_GRANT_USB);
304 | intent.setPackage(getActivity().getPackageName());
305 | PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, flags);
306 | usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
307 | return;
308 | }
309 | if(usbConnection == null) {
310 | if (!usbManager.hasPermission(driver.getDevice()))
311 | status("connection failed: permission denied");
312 | else
313 | status("connection failed: open failed");
314 | return;
315 | }
316 |
317 | connected = Connected.Pending;
318 | try {
319 | usbSerialPort.open(usbConnection);
320 | try {
321 | usbSerialPort.setParameters(baudRate, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
322 | } catch (UnsupportedOperationException e) {
323 | status("Setting serial parameters failed: " + e.getMessage());
324 | }
325 | SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), usbConnection, usbSerialPort);
326 | service.connect(socket);
327 | // usb connect is not asynchronous. connect-success and connect-error are returned immediately from socket.connect
328 | // for consistency to bluetooth/bluetooth-LE app use same SerialListener and SerialService classes
329 | onSerialConnect();
330 | } catch (Exception e) {
331 | onSerialConnectError(e);
332 | }
333 | }
334 |
335 | private void disconnect() {
336 | connected = Connected.False;
337 | controlLines.stop();
338 | service.disconnect();
339 | updateSendBtn(SendButtonState.Idle);
340 | usbSerialPort = null;
341 | }
342 |
343 | private void send(String str) {
344 | if(connected != Connected.True) {
345 | Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
346 | return;
347 | }
348 | String msg;
349 | byte[] data;
350 | if(hexEnabled) {
351 | StringBuilder sb = new StringBuilder();
352 | TextUtil.toHexString(sb, TextUtil.fromHexString(str));
353 | TextUtil.toHexString(sb, newline.getBytes());
354 | msg = sb.toString();
355 | data = TextUtil.fromHexString(msg);
356 | } else {
357 | msg = str;
358 | data = (str + newline).getBytes();
359 | }
360 | try {
361 | SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
362 | spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
363 | receiveText.append(spn);
364 | service.write(data);
365 | } catch (SerialTimeoutException e) { // e.g. writing large data at low baud rate or suspended by flow control
366 | mainLooper.post(() -> sendAgain(data, e.bytesTransferred));
367 | } catch (Exception e) {
368 | onSerialIoError(e);
369 | }
370 | }
371 |
372 | private void sendAgain(byte[] data0, int offset) {
373 | updateSendBtn(controlLines.sendAllowed ? SendButtonState.Busy : SendButtonState.Disabled);
374 | if (connected != Connected.True) {
375 | return;
376 | }
377 | byte[] data;
378 | if (offset == 0) {
379 | data = data0;
380 | } else {
381 | data = new byte[data0.length - offset];
382 | System.arraycopy(data0, offset, data, 0, data.length);
383 | }
384 | try {
385 | service.write(data);
386 | } catch (SerialTimeoutException e) {
387 | mainLooper.post(() -> sendAgain(data, e.bytesTransferred));
388 | return;
389 | } catch (Exception e) {
390 | onSerialIoError(e);
391 | }
392 | updateSendBtn(controlLines.sendAllowed ? SendButtonState.Idle : SendButtonState.Disabled);
393 | }
394 |
395 | private void receive(ArrayDeque datas) {
396 | SpannableStringBuilder spn = new SpannableStringBuilder();
397 | for (byte[] data : datas) {
398 | if (flowControlFilter != null)
399 | data = flowControlFilter.filter(data);
400 | if (hexEnabled) {
401 | spn.append(TextUtil.toHexString(data)).append('\n');
402 | } else {
403 | String msg = new String(data);
404 | if (newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
405 | // don't show CR as ^M if directly before LF
406 | msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
407 | // special handling if CR and LF come in separate fragments
408 | if (pendingNewline && msg.charAt(0) == '\n') {
409 | if(spn.length() >= 2) {
410 | spn.delete(spn.length() - 2, spn.length());
411 | } else {
412 | Editable edt = receiveText.getEditableText();
413 | if (edt != null && edt.length() >= 2)
414 | edt.delete(edt.length() - 2, edt.length());
415 | }
416 | }
417 | pendingNewline = msg.charAt(msg.length() - 1) == '\r';
418 | }
419 | spn.append(TextUtil.toCaretString(msg, newline.length() != 0));
420 | }
421 | }
422 | receiveText.append(spn);
423 | }
424 |
425 | void status(String str) {
426 | SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
427 | spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
428 | receiveText.append(spn);
429 | }
430 |
431 | void updateSendBtn(SendButtonState state) {
432 | sendBtn.setEnabled(state == SendButtonState.Idle);
433 | sendBtn.setImageAlpha(state == SendButtonState.Idle ? 255 : 64);
434 | sendBtn.setImageResource(state == SendButtonState.Disabled ? R.drawable.ic_block_white_24dp : R.drawable.ic_send_white_24dp);
435 | }
436 |
437 | /*
438 | * starting with Android 14, notifications are not shown in notification bar by default when App is in background
439 | */
440 |
441 | private void showNotificationSettings() {
442 | Intent intent = new Intent();
443 | intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
444 | intent.putExtra("android.provider.extra.APP_PACKAGE", getActivity().getPackageName());
445 | startActivity(intent);
446 | }
447 |
448 |
449 | @Override
450 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
451 | if(Arrays.equals(permissions, new String[]{Manifest.permission.POST_NOTIFICATIONS}) &&
452 | Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !service.areNotificationsEnabled())
453 | showNotificationSettings();
454 | }
455 |
456 | /*
457 | * SerialListener
458 | */
459 | @Override
460 | public void onSerialConnect() {
461 | status("connected");
462 | connected = Connected.True;
463 | controlLines.start();
464 | }
465 |
466 | @Override
467 | public void onSerialConnectError(Exception e) {
468 | status("connection failed: " + e.getMessage());
469 | disconnect();
470 | }
471 |
472 | @Override
473 | public void onSerialRead(byte[] data) {
474 | ArrayDeque datas = new ArrayDeque<>();
475 | datas.add(data);
476 | receive(datas);
477 | }
478 |
479 | public void onSerialRead(ArrayDeque datas) {
480 | receive(datas);
481 | }
482 |
483 | @Override
484 | public void onSerialIoError(Exception e) {
485 | status("connection lost: " + e.getMessage());
486 | disconnect();
487 | }
488 |
489 | class ControlLines {
490 | private static final int refreshInterval = 200; // msec
491 |
492 | private final Runnable runnable;
493 |
494 | private View frame;
495 | private ToggleButton rtsBtn, ctsBtn, dtrBtn, dsrBtn, cdBtn, riBtn;
496 |
497 | private boolean showControlLines; // show & update control line buttons
498 | private UsbSerialPort.FlowControl flowControl = UsbSerialPort.FlowControl.NONE; // !NONE: update send button state
499 |
500 | boolean sendAllowed = true;
501 |
502 | ControlLines() {
503 | runnable = this::run; // w/o explicit Runnable, a new lambda would be created on each postDelayed, which would not be found again by removeCallbacks
504 | }
505 |
506 | void onCreateView(View view) {
507 | frame = view.findViewById(R.id.controlLines);
508 | rtsBtn = view.findViewById(R.id.controlLineRts);
509 | ctsBtn = view.findViewById(R.id.controlLineCts);
510 | dtrBtn = view.findViewById(R.id.controlLineDtr);
511 | dsrBtn = view.findViewById(R.id.controlLineDsr);
512 | cdBtn = view.findViewById(R.id.controlLineCd);
513 | riBtn = view.findViewById(R.id.controlLineRi);
514 | rtsBtn.setOnClickListener(this::toggle);
515 | dtrBtn.setOnClickListener(this::toggle);
516 | }
517 |
518 | void onPrepareOptionsMenu(Menu menu) {
519 | try {
520 | EnumSet scl = usbSerialPort.getSupportedControlLines();
521 | EnumSet sfc = usbSerialPort.getSupportedFlowControl();
522 | menu.findItem(R.id.controlLines).setEnabled(!scl.isEmpty());
523 | menu.findItem(R.id.controlLines).setChecked(showControlLines);
524 | menu.findItem(R.id.flowControl).setEnabled(sfc.size() > 1);
525 | } catch (Exception ignored) {
526 | }
527 | }
528 |
529 | void selectFlowControl() {
530 | EnumSet sfc = usbSerialPort.getSupportedFlowControl();
531 | UsbSerialPort.FlowControl fc = usbSerialPort.getFlowControl();
532 | ArrayList names = new ArrayList<>();
533 | ArrayList values = new ArrayList<>();
534 | int pos = 0;
535 | names.add("");
536 | values.add(UsbSerialPort.FlowControl.NONE);
537 | if (sfc.contains(UsbSerialPort.FlowControl.RTS_CTS)) {
538 | names.add("RTS/CTS control lines");
539 | values.add(UsbSerialPort.FlowControl.RTS_CTS);
540 | if (fc == UsbSerialPort.FlowControl.RTS_CTS) pos = names.size() -1;
541 | }
542 | if (sfc.contains(UsbSerialPort.FlowControl.DTR_DSR)) {
543 | names.add("DTR/DSR control lines");
544 | values.add(UsbSerialPort.FlowControl.DTR_DSR);
545 | if (fc == UsbSerialPort.FlowControl.DTR_DSR) pos = names.size() - 1;
546 | }
547 | if (sfc.contains(UsbSerialPort.FlowControl.XON_XOFF)) {
548 | names.add("XON/XOFF characters");
549 | values.add(UsbSerialPort.FlowControl.XON_XOFF);
550 | if (fc == UsbSerialPort.FlowControl.XON_XOFF) pos = names.size() - 1;
551 | }
552 | if (sfc.contains(UsbSerialPort.FlowControl.XON_XOFF_INLINE)) {
553 | names.add("XON/XOFF characters");
554 | values.add(UsbSerialPort.FlowControl.XON_XOFF_INLINE);
555 | if (fc == UsbSerialPort.FlowControl.XON_XOFF_INLINE) pos = names.size() - 1;
556 | }
557 | AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
558 | builder.setTitle("Flow Control");
559 | builder.setSingleChoiceItems(names.toArray(new CharSequence[0]), pos, (dialog, which) -> {
560 | dialog.dismiss();
561 | try {
562 | flowControl = values.get(which);
563 | usbSerialPort.setFlowControl(flowControl);
564 | flowControlFilter = usbSerialPort.getFlowControl() == UsbSerialPort.FlowControl.XON_XOFF_INLINE ? new XonXoffFilter() : null;
565 | start();
566 | } catch (Exception e) {
567 | status("Set flow control failed: "+e.getClass().getName()+" "+e.getMessage());
568 | flowControl = UsbSerialPort.FlowControl.NONE;
569 | flowControlFilter = null;
570 | start();
571 | }
572 | });
573 | builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
574 | builder.setNeutralButton("Info", (dialog, which) -> {
575 | dialog.dismiss();
576 | AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity());
577 | builder2.setTitle("Flow Control").setMessage("If send is stopped by the external device, the 'Send' button changes to 'Blocked' icon.");
578 | builder2.create().show();
579 | });
580 | builder.create().show();
581 | }
582 |
583 | public boolean showControlLines(boolean show) {
584 | showControlLines = show;
585 | start();
586 | return showControlLines;
587 | }
588 |
589 | void start() {
590 | if (showControlLines) {
591 | try {
592 | EnumSet lines = usbSerialPort.getSupportedControlLines();
593 | rtsBtn.setVisibility(lines.contains(UsbSerialPort.ControlLine.RTS) ? View.VISIBLE : View.INVISIBLE);
594 | ctsBtn.setVisibility(lines.contains(UsbSerialPort.ControlLine.CTS) ? View.VISIBLE : View.INVISIBLE);
595 | dtrBtn.setVisibility(lines.contains(UsbSerialPort.ControlLine.DTR) ? View.VISIBLE : View.INVISIBLE);
596 | dsrBtn.setVisibility(lines.contains(UsbSerialPort.ControlLine.DSR) ? View.VISIBLE : View.INVISIBLE);
597 | cdBtn.setVisibility(lines.contains(UsbSerialPort.ControlLine.CD) ? View.VISIBLE : View.INVISIBLE);
598 | riBtn.setVisibility(lines.contains(UsbSerialPort.ControlLine.RI) ? View.VISIBLE : View.INVISIBLE);
599 | } catch (IOException e) {
600 | showControlLines = false;
601 | status("getSupportedControlLines() failed: " + e.getMessage());
602 | }
603 | }
604 | frame.setVisibility(showControlLines ? View.VISIBLE : View.GONE);
605 | if(flowControl == UsbSerialPort.FlowControl.NONE) {
606 | sendAllowed = true;
607 | updateSendBtn(SendButtonState.Idle);
608 | }
609 |
610 | mainLooper.removeCallbacks(runnable);
611 | if (showControlLines || flowControl != UsbSerialPort.FlowControl.NONE) {
612 | run();
613 | }
614 | }
615 |
616 | void stop() {
617 | mainLooper.removeCallbacks(runnable);
618 | sendAllowed = true;
619 | updateSendBtn(SendButtonState.Idle);
620 | rtsBtn.setChecked(false);
621 | ctsBtn.setChecked(false);
622 | dtrBtn.setChecked(false);
623 | dsrBtn.setChecked(false);
624 | cdBtn.setChecked(false);
625 | riBtn.setChecked(false);
626 | }
627 |
628 | private void run() {
629 | if (connected != Connected.True)
630 | return;
631 | try {
632 | if (showControlLines) {
633 | EnumSet lines = usbSerialPort.getControlLines();
634 | if(rtsBtn.isChecked() != lines.contains(UsbSerialPort.ControlLine.RTS)) rtsBtn.setChecked(!rtsBtn.isChecked());
635 | if(ctsBtn.isChecked() != lines.contains(UsbSerialPort.ControlLine.CTS)) ctsBtn.setChecked(!ctsBtn.isChecked());
636 | if(dtrBtn.isChecked() != lines.contains(UsbSerialPort.ControlLine.DTR)) dtrBtn.setChecked(!dtrBtn.isChecked());
637 | if(dsrBtn.isChecked() != lines.contains(UsbSerialPort.ControlLine.DSR)) dsrBtn.setChecked(!dsrBtn.isChecked());
638 | if(cdBtn.isChecked() != lines.contains(UsbSerialPort.ControlLine.CD)) cdBtn.setChecked(!cdBtn.isChecked());
639 | if(riBtn.isChecked() != lines.contains(UsbSerialPort.ControlLine.RI)) riBtn.setChecked(!riBtn.isChecked());
640 | }
641 | if (flowControl != UsbSerialPort.FlowControl.NONE) {
642 | switch (usbSerialPort.getFlowControl()) {
643 | case DTR_DSR: sendAllowed = usbSerialPort.getDSR(); break;
644 | case RTS_CTS: sendAllowed = usbSerialPort.getCTS(); break;
645 | case XON_XOFF: sendAllowed = usbSerialPort.getXON(); break;
646 | case XON_XOFF_INLINE: sendAllowed = flowControlFilter != null && flowControlFilter.getXON(); break;
647 | default: sendAllowed = true;
648 | }
649 | updateSendBtn(sendAllowed ? SendButtonState.Idle : SendButtonState.Disabled);
650 | }
651 | mainLooper.postDelayed(runnable, refreshInterval);
652 | } catch (IOException e) {
653 | status("getControlLines() failed: " + e.getMessage() + " -> stopped control line refresh");
654 | }
655 | }
656 |
657 | private void toggle(View v) {
658 | ToggleButton btn = (ToggleButton) v;
659 | if (connected != Connected.True) {
660 | btn.setChecked(!btn.isChecked());
661 | Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
662 | return;
663 | }
664 | String ctrl = "";
665 | try {
666 | if (btn.equals(rtsBtn)) { ctrl = "RTS"; usbSerialPort.setRTS(btn.isChecked()); }
667 | if (btn.equals(dtrBtn)) { ctrl = "DTR"; usbSerialPort.setDTR(btn.isChecked()); }
668 | } catch (IOException e) {
669 | status("set" + ctrl + " failed: " + e.getMessage());
670 | }
671 | }
672 |
673 | }
674 |
675 | }
676 |
--------------------------------------------------------------------------------
/app/src/main/java/de/kai_morich/simple_usb_terminal/TextUtil.java:
--------------------------------------------------------------------------------
1 | package de.kai_morich.simple_usb_terminal;
2 |
3 | import android.text.Editable;
4 | import android.text.InputType;
5 | import android.text.Spannable;
6 | import android.text.SpannableStringBuilder;
7 | import android.text.TextWatcher;
8 | import android.text.style.BackgroundColorSpan;
9 | import android.widget.TextView;
10 |
11 | import androidx.annotation.ColorInt;
12 |
13 | import java.io.ByteArrayOutputStream;
14 |
15 | final class TextUtil {
16 |
17 | @ColorInt static int caretBackground = 0xff666666;
18 |
19 | final static String newline_crlf = "\r\n";
20 | final static String newline_lf = "\n";
21 |
22 | static byte[] fromHexString(final CharSequence s) {
23 | ByteArrayOutputStream buf = new ByteArrayOutputStream();
24 | byte b = 0;
25 | int nibble = 0;
26 | for(int pos = 0; pos='0' && c<='9') { nibble++; b *= 16; b += c-'0'; }
34 | if(c>='A' && c<='F') { nibble++; b *= 16; b += c-'A'+10; }
35 | if(c>='a' && c<='f') { nibble++; b *= 16; b += c-'a'+10; }
36 | }
37 | if(nibble>0)
38 | buf.write(b);
39 | return buf.toByteArray();
40 | }
41 |
42 | static String toHexString(final byte[] buf) {
43 | return toHexString(buf, 0, buf.length);
44 | }
45 |
46 | static String toHexString(final byte[] buf, int begin, int end) {
47 | StringBuilder sb = new StringBuilder(3*(end-begin));
48 | toHexString(sb, buf, begin, end);
49 | return sb.toString();
50 | }
51 |
52 | static void toHexString(StringBuilder sb, final byte[] buf) {
53 | toHexString(sb, buf, 0, buf.length);
54 | }
55 |
56 | static void toHexString(StringBuilder sb, final byte[] buf, int begin, int end) {
57 | for(int pos=begin; pos0)
59 | sb.append(' ');
60 | int c;
61 | c = (buf[pos]&0xff) / 16;
62 | if(c >= 10) c += 'A'-10;
63 | else c += '0';
64 | sb.append((char)c);
65 | c = (buf[pos]&0xff) % 16;
66 | if(c >= 10) c += 'A'-10;
67 | else c += '0';
68 | sb.append((char)c);
69 | }
70 | }
71 |
72 | /**
73 | * use https://en.wikipedia.org/wiki/Caret_notation to avoid invisible control characters
74 | */
75 | static CharSequence toCaretString(CharSequence s, boolean keepNewline) {
76 | return toCaretString(s, keepNewline, s.length());
77 | }
78 |
79 | static CharSequence toCaretString(CharSequence s, boolean keepNewline, int length) {
80 | boolean found = false;
81 | for (int pos = 0; pos < length; pos++) {
82 | if (s.charAt(pos) < 32 && (!keepNewline ||s.charAt(pos)!='\n')) {
83 | found = true;
84 | break;
85 | }
86 | }
87 | if(!found)
88 | return s;
89 | SpannableStringBuilder sb = new SpannableStringBuilder();
90 | for(int pos=0; pos= '0' && c <= '9') sb.append(c);
140 | if(c >= 'A' && c <= 'F') sb.append(c);
141 | if(c >= 'a' && c <= 'f') sb.append((char)(c+'A'-'a'));
142 | }
143 | for(i=2; i
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_delete_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_send_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
13 |
14 |
19 |
20 |
21 |
22 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/device_list_header.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/device_list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
16 |
17 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_terminal.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
15 |
16 |
23 |
24 |
33 |
34 |
37 |
38 |
45 |
46 |
55 |
56 |
59 |
60 |
69 |
70 |
79 |
80 |
81 |
82 |
86 |
87 |
96 |
97 |
101 |
102 |
106 |
107 |
114 |
115 |
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_devices.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_terminal.xml:
--------------------------------------------------------------------------------
1 |
2 |
37 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kai-morich/SimpleUsbTerminal/bb743dcf85e13190e77679d06631a4899a0fdaff/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kai-morich/SimpleUsbTerminal/bb743dcf85e13190e77679d06631a4899a0fdaff/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kai-morich/SimpleUsbTerminal/bb743dcf85e13190e77679d06631a4899a0fdaff/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kai-morich/SimpleUsbTerminal/bb743dcf85e13190e77679d06631a4899a0fdaff/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kai-morich/SimpleUsbTerminal/bb743dcf85e13190e77679d06631a4899a0fdaff/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/arrays.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - 2400
5 | - 9600
6 | - 19200
7 | - 57600
8 | - 115200
9 |
10 |
11 | - CR+LF
12 | - LF
13 | - <none>
14 |
15 |
16 | - \u000d\u000a
17 | - \u000a
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #d84315
4 | #bf360c
5 | #ff6e40
6 |
7 | #00FF00
8 | #82CAFF
9 | #FFDB58
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Simple USB Terminal
3 | USB Devices
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/usb_device_filter.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 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | }
6 | dependencies {
7 | classpath 'com.android.tools.build:gradle:8.4.2'
8 | }
9 | }
10 |
11 | allprojects {
12 | repositories {
13 | google()
14 | mavenCentral()
15 | mavenLocal()
16 | maven { url 'https://jitpack.io' }
17 | }
18 | }
19 |
20 | task clean(type: Delete) {
21 | delete rootProject.buildDir
22 | }
23 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | android.defaults.buildfeatures.buildconfig=true
10 | android.enableJetifier=true
11 | android.useAndroidX=true
12 | org.gradle.jvmargs=-Xmx1536m
13 | # When configured, Gradle will run in incubating parallel mode.
14 | # This option should only be used with decoupled projects. More details, visit
15 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
16 | # org.gradle.parallel=true
17 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kai-morich/SimpleUsbTerminal/bb743dcf85e13190e77679d06631a4899a0fdaff/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Oct 15 17:47:46 CEST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
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 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------