Giter VIP home page Giter VIP logo

simplebluetoothleterminal's Introduction

Codacy Badge

SimpleBluetoothLeTerminal

This Android app provides a line-oriented terminal / console for Bluetooth LE (4.x) devices implementing a custom serial profile

For an overview on Android BLE communication see Android Bluetooth LE Overview.

In contrast to classic Bluetooth, there is no predefined serial profile for Bluetooth LE, so each vendor uses GATT services with different service and characteristic UUIDs.

This app includes UUIDs for widely used serial profiles:

  • Nordic Semiconductor nRF51822
  • Texas Instruments CC254x
  • Microchip RN4870/1
  • Telit Bluemod

Motivation

I got various requests asking for help with Android development or source code for my Serial Bluetooth Terminal app. Here you find a simplified version of my app.

simplebluetoothleterminal's People

Contributors

furbrain avatar kai-morich avatar khwolf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simplebluetoothleterminal's Issues

connecting BLE code in flutter app

you are a Ble expert as mentioned below image we are making a final year project in which we are ready with flutter screens but there is a button to connect with ESP for this we are attaching your BLE code to that button and a scanning popup will come and show available devices but not working finally our team decided to contact with you hope you will help us and thank you for your reply

iPhone 12, 12 Pro – 8

Please it's a request

please if you can open source this file transferring and receiving through xmodem codes for Bluetooth serial application then it would really awesome

nrf51822 not found

Hi, thanks alot for this code! The full version is able to find and connect to my nrf custom pcb's, but they do not show up in the simple version. The UUID's provided are correct, so far I have not found a solution.

Thanks for your help

Serial Bluetooth Terminal

Hello,I am a newer,where I can find the Serial Bluetooth Terminal source code?This project is open source code?

how to disconnect bluetooth without using OnbackPressed

I'm trying to end the pairing with a device connected via Bluetooth, I turned off the public socket to be able to call it, but when I call it I can't disconnect it. How can I ensure disconnection when clicking a button?

UUID Serial profile for RN4020

Hello, First of all, thank you for making this source code available for us.
This is my first time working with android studio let alone BLE. I used your Serial Bluetooth Terminal from the play store and it works great with my RN4020.
I noticed in your description you mention that this app " include UUIDs for widely used serial profiles:" such as the Microchip RN4870/1.
When I scan, I can see my RN4020, but when I hold to select characteristics, nothing happen. When I tap to connect, I get "Connection failed: no serial profile found". I guess it is because the code doesn't include the UUID for the RN20. I opened your SerialSocket.java file and I saw the "device delegates" section which has all the devices you mentioned. so from my understanding, if I add the delegate for the RN4020, It will work? And if yes, how would I implement that?

Thank you.
Sorry for the long text.

Screenshot_20210326-224123_Simple_BLE_Terminal 1
Screenshot_20210326-224131_Simple_BLE_Terminal 1

Streaming data

Hi Kai,
I have a deivice which is streaming text data through transparent UART. I can connect and receive the text data. I have a question. Is the UART the same thing as service? Thanks

Ask for help with android app

Hi
sorry for my english
I remeber 2 weeks ago that i have an old Elogoo robot who work with bluetooth.
To control my robot i use the official app name's ELEGOO BLE TOOL APP.
I need your help because im actualy in school and i have for task to create a APP who can work with my arduino bluetooth card.
For now your app is the only one I find who connect and send data.
When i connect to Bluetooth i had to edit to had custom profil and this work well.
But i trie to create an app who can work with app inventor but it's not working.
I think maybe i can take the base of your app in android studio a rebuild to add functione like when i presse a bouton it's send "f" to the terminal ?
maybe you can help me ?

ESP32 SPP Support Merge Request

Kai
Thanks for writing this. I don't know how to contact you (I am pretty new to github, etc) but I cam across your code while looking for an example BLE application so I could add BLE to my little project.

My hardware is ESP32-C3 based and your code does not support ESP32 so I managed to port it over and got it working with the esp32_spp_server.cpp demo which espressif provides. (see https://github.com/BrianAtDocumentedDesigns/SimpleBluetoothLeTerminal/tree/ESP32_C3_SPP_Support).

I am pretty sure the ESP32 spp server does not implement flow control so I set

        writeCredits = Integer.MAX_VALUE;

as a sort of a kludge.

I know I am not much of a programmer but I thought I'd let you know in case you were interested in incorporating support for the popular ESP32 family into your code.

I will probably add flow control to the ESP32 code when I make some progress on my project.

Thanks again

Brian Piccioni
Documented Designs.

How to reconnect?

How can I make automatic reconnection if the connection to the device is lost, and then reappeared?

ANSI/VT100 terminal color support

would be so nice to support some of the basic terminal colors, or at least an option to hide (do not print out) escape sequences from rx stream.

When I receive something like this:

�[34mFIB> �[33mhelp

�[32mHello World! 51
�[31mFAIL: ‑2

I am expecting to see (colored or not):

FIB> help 

Hello World! 51
FAIL: -2

note. the is ASCII escape symbol 033 aka \e

nice article if unfamiliar: https://misc.flogisoft.com/bash/tip_colors_and_formatting

would love to contribute myself, but I have no experience with java or mobile app development :/

super nice app tho! love it

getting read characteristic CCCD descriptor not writable

Thanks for the great example app,
I am getting this issue when I disable and enable the bluetooth first time, subsequent connection are working fine.

Here is how I go the issue

  1. turn off bluetooth
  2. turn on bluetooth and connect to ble (Error will come)
  3. try reconnecting while bluetooth is on (Than it is working)

Here is what I tried

  1. Add delay after bluetooth is turned on, yet still getting the same issue

How to configure UUID in SerialSocket.java

Hi,
I was able to configure the original app where you can insert devices while using configuring the app on the phone.
I see that this app does not allow to do so, but you have to put the UUIDs in the code.
I tried putting Service UUID, Read Characteristic UUID and Write Characteristic UUID taken from the full app into the serialSocket.java file as below:

    private static final UUID BLUETOOTH_LE_TIO_SERVICE          = UUID.fromString("xxxx-xxxx-xxxx-xxxx-xxxx");
    private static final UUID BLUETOOTH_LE_TIO_CHAR_TX          = UUID.fromString("yyyy-xxxx-xxxx-xxxx-xxxx"); // WNR
    private static final UUID BLUETOOTH_LE_TIO_CHAR_RX          = UUID.fromString("zzzz-xxxx-xxxx-xxxx-xxxx"); // N
    private static final UUID BLUETOOTH_LE_TIO_CHAR_TX_CREDITS  = UUID.fromString("yyyy-xxxx-xxxx-xxxx-xxxx"); // W
    private static final UUID BLUETOOTH_LE_TIO_CHAR_RX_CREDITS  = UUID.fromString("zzzz-xxxx-xxxx-xxxx-xxxx"); // I

I considered RX as READ, and TX as WRITE, but I got "read credits characteristic not found".
What am I missing ? Thanks

Can't stream data

Hello.

Thank you for this BLE usage sample!

I am using JDY-10 UART-BluetoothLE module. I ran into following problem: everything larger than 56 bytes that I send through JDY-10 at baud rate 115200 is trunkated to 56 bytes (Android receives it as 3 onCharacteristicChanged: 20+20+16), only the beginning of packet is received.
When I try using small packets (10-11 bytes each) and send them almost at maximum speed of UART, something around 70% of data is lost.

Is that OK (BLE is just not capable to send faster)? Or am I doing something wrong?
I read that BLE supports 1 Mbits/sec, seems a lot more than 115200.

P.S. I found that onMtuChanged logs mtu size 23, payload size 20. Did not become 512.

Add "STX/ETX" while Sending and Receiving Commands

How can I add "STX/ETX" while working with commands. Yes you have provided option of CR+LF, LF and none in NewLine, but can you also specify how to add "STX/ETX"(Start of Text Character/End of Text Character).

How to restore service after fragment is destoyed

Hi,
Is it possible to retain the service reference, after the fragment is destroyed by the system?

In some phones when the app is on the background, the activity gets destoyed and also the terminal fragment. When the fragment is recreated, the service reference is null and I have to reconnect again. Is there a way to keep or restore the service?

Notify/Indicate, Increased MTU & Chunking?

I've been trying to determine if your terminal app &/or any of the supported protocols support:

  • BLE Notify vs BLE Indicate;
  • increasing the MTU above 20;
  • adding packet sequencing & 'chunking' of large strings (only usefull if BLE Indicate is supported).

I don't see support for this in this 'Simple' version, and it's not clear if (any of) the supported protocols actually support these features.

Could you please provide some guidance?

Is removeCallbacks(this::stopScan) correct?

This is a minor remark, since the app still works well. However, I would like to check my understanding

The following line (264) in DeviceFragment.java seems not correct to me:

leScanStopHandler.removeCallbacks(this::stopScan);

This because, as far as I know, when you pass a method to a Handler in postDelayed(), it gets encapsulated in a Runnable object and then scheduled.
Calling removeCallbacks without referencing the original Runnable object should not do what was intended for.
Am I correct?

Thanks!

not find any ble devices

hi.
I test google play version on my two device that support BLE but not find each other.
if two device paired, found in classic section but when connecting show this error:
Read failed, socket might closed or timeout, read ret: -1
I try "SimpleBluetoothTerminal" and "SimpleBluetoothLeTerminal" source code but show same result.
any help would be appreciated.

Sort found devices by distance

Just an idea, to put strongest rssi ones first instead of alphabet order.
E.g. I have 50devices around me, but I'm standing next to the one I want to connect to.

Android studio: Cannot resolve symbol "R"

I clone this repository and use android studio in it.
I was able to sucessfuly build the project with gradle and upload the app on my app and use the app without a problem.
However I wanted to edit the code and make my own version. And when you use R the IDE doesn't seem to understand:

I try to clean gradle project.
I also try to sync the project with gradle file.
But It's doesn't work for me.

I'm a begginer with android studio. So If you have any ideas to help me it's will be great.

Connecting to multiple UART Servers

I'm trying to extend this so I can connect to multiple UART servers simultaneously.

I've already got the scan filtering for UART devices only and am passing the list of device labels to the TerminalFragement

But it looks like I'm overwriting the socket connection when I loop through the devices and create them in the service.

If i send a message I only get a reply from one of the devices. Is there an elegant way of doing this without just creating an array of services?

for(String d:deviceList) {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(d);
status("connecting..." + device);
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device); // need to make multiple connectons and retrieve address
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}

Disconnect from BLE peripheral does not allow indicates to go to new central

I have a BLE server/peripheral that accepts connections. It sends a msg to a client on connect. It also automatically disconnects a client after 20 seconds. After disconnecting, new clients are able to connect since advertisements are started.

Now it gets tricky

I have phones A and B with the serial bluetooth monitor app (from play store)

Scenario 1

A connects to server first

  • receives msg
  • disconnected by server after 20 sec

then B connects to server

  • receives msg
  • disconnected by server after 20 sec
    Everything works as expected here

Scenario 2

B connects to server first

  • receives msg
  • disconnected by server after 20 sec

then A connects to server

  • does not receive msg (indication is being sent by the server, but nothing received)

Bind to service from a different activity issue

Hi,
I am trying to bind to the serial service from a different activity after I connect to a bluetooth LE device. I can see that the service is running in the background "D/SerialSocket: read, len=61" being printed. In my activity the I can see in the log that it is connected. But I cannot receive any data onSerialRead. Is that the right way to connect?

` public class BoundToService extends AppCompatActivity implements ServiceConnection, SerialListener {

private SerialService serialService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bound_to_service);
    bindService(new Intent(getApplicationContext(), SerialService.class),this, Context.BIND_AUTO_CREATE);
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    Log.i("OnServiceCONNECTED ", "On connected");
    serialService = ((SerialService.SerialBinder) service).getService();
}

@Override
public void onServiceDisconnected(ComponentName name) { }
@Override
public void onSerialConnect() {Log.i("SERIAL", "onSerialConnect(");}
@Override
public void onSerialConnectError(Exception e) {Log.i("SERIAL", "onSerialConnectError");}
@Override
public void onSerialRead(byte[] data) {Log.i("onSerialRead ", new String(data)); }
@Override
public void onSerialIoError(Exception e) {Log.i("SERIAL", "onSerialIoError"); }

}`

How to achieve the same terminal working in FlutterApp

Hi @kai-morich , i have downloaded the app from Playstore and checked connecting with BluetoothLE Device. It's really working well. Also have checked the (Native App)source code

Now, I have problem where i am trying develop same funtionality in the Flutter App. But i am not getting expected output as the Native App.
Trying with this as a reference in Flutter - https://pub.dev/packages/flutter_blue

Please help me out, how can achieve it in flutter. Any help would be appreciated.

when send data but socket is null

java.lang.NullPointerException: Attempt to invoke virtual method 'void de.kai_morich.simple_bluetooth_le_terminal.SerialSocket.write(byte[])' on a null object reference

service.write(data); call the write function socket.write(data),but socket is NULL.

Your implementation can be inserted in a existent fragment?

Hi, i need usage communication with BLE (with Arduino) and your app was a unique app that works with my CC2541, i'm read your code and i have a fragment screen (from NavigationDrawer) and i need implements a big part of your code here, everything works until we click on some device to connect, this error is returned to me:

2020-01-03 16:54:41.755 25872-25872/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.agrolucros2019, PID: 25872 java.lang.IllegalArgumentException: No view found for id 0x7f09009c (com.example.agrolucros2019:id/fragment) for fragment TerminalFragment{25fdc20 (8f432817-1c28-4b66-a395-1f86dbd4b273) id=0x7f09009c terminal} at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875) at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303) at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439) at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824) at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727) at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7097) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

Do you have a some idea that can be cause it?

I'm really desesperate now, thanks in advance!

Works since here:
This image

When i pressed on a device, error return.

Hex mode

An option to receive/send in hex mode would be very useful.
Low level is already in binary, so this would be UI only change.

Since there won't be line break, it could append to line until other side talks.

Please help on deprecated commands.

startLeScan and stopLeScan has been deprecated. It needs to be removed from the code and replaced with startScan and stopScan respectively. please help on this.

file:
DevicesFragment.java
commands:
bluetoothAdapter.startLeScan(null, leScanCallback);
bluetoothAdapter.stopLeScan(leScanCallback);

Thanks a lot :-) 👍

Ble not working in redmi note 9 pro

This was working in redmi note 7 pro. However, with my redmi note 9 pro, i do not get any device when i scan. If i scan from ble settings, i am able to detect my device

only receiving 20 bytes at a time

Good day,

I am using your code library. (Thank you by the way for this, very helpful)

however I am having an issue when I get larger responses like 60bytes etc, the receive callback is only getting a byte array of 20 characters?

What could be causing this?

Inactivity, disconnecting from the service

@hi @kai-morich ,

I am trying to implement your example code into my application and i having several problems. I have got the scanning up and running but i got issues with the terminalFragment. I am not able to connnect to my devices, its like the intentService never gets to the point of being created. It will be of much help if you can help me with that.

What I am trying to do is very simple. The user goes to the device and click on it. Once it is click ,a new intent is opened (the one i provide). What i want is that once it is connected the system will send messages in order to know the state.

package com.example.smartmask.activity;


import androidx.appcompat.app.AppCompatActivity;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;

import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.smartmask.R;
import com.example.smartmask.classes.bluetooth.SerialListener;
import com.example.smartmask.classes.bluetooth.SerialService;
import com.example.smartmask.classes.bluetooth.SerialSocket;
import com.example.smartmask.classes.bluetooth.TextUtil;

public class BluetoothSettings extends AppCompatActivity implements ServiceConnection, SerialListener {
    private enum Connected { False, Pending, True }

    private String deviceAddress;
    private SerialService service;

    private TextView receiveText;

    private Connected connected = Connected.False;
    private boolean initialStart = true;
    private boolean hexEnabled = false;
    private boolean pendingNewline = false;
    private String newline = TextUtil.newline_crlf;
    private Button bConnect;
    private TextView ssid;
    private TextView password;
    private TextView nameDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_settings);
        getSupportActionBar().hide();
        receiveText=findViewById(R.id.status);
        receiveText.setText("Mierda");
        nameDevice= findViewById(R.id.NameDevice);
        ssid= findViewById(R.id.ssid);
        password= findViewById(R.id.password);
        bConnect= findViewById(R.id.bConnect);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            deviceAddress = extras.getString("DeviceAddress");
            nameDevice.setText(extras.getString("DeviceName"));
        }

        bConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bConnect.getText().equals("Connect")){
                    BluetoothSettings.this.startService(new Intent(BluetoothSettings.this, SerialService.class));
                    //BluetoothSettings.this.bindService(new Intent(BluetoothSettings.this, SerialService.class), BluetoothSettings.this, Context.BIND_AUTO_CREATE);
                    //connect();
                }else if (bConnect.getText().equals("Disconnect")){
                    try { BluetoothSettings.this.unbindService(BluetoothSettings.this); } catch(Exception ignored) {}
                   bConnect.setText("Connect");

                }
            }
        });

    }
    @Override
    public void onStart() {
        super.onStart();
        if(service != null)
            service.attach(this);
        else
            BluetoothSettings.this.startService(new Intent(this, SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change

    }
    @Override
    public void onDestroy() {
        if (connected != Connected.False)
            disconnect();
        this.stopService(new Intent(this, SerialService.class));
        super.onDestroy();
    }
    @Override
    public void onStop() {
        if(service != null && !this.isChangingConfigurations())
            service.detach();
        super.onStop();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        service = ((SerialService.SerialBinder) binder).getService();
        service.attach(this);
        if(initialStart) {
            initialStart = false;
            this.runOnUiThread(this::connect);
        }
        receiveText.setText("puto");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        service = null;
    }

    @Override
    public void onSerialConnect() {
        status("connected");
        connected = Connected.True;
    }

    @Override
    public void onSerialConnectError(Exception e) {
        status("connection failed: " + e.getMessage());
        disconnect();
    }

    @Override
    public void onSerialRead(byte[] data) {
        receive(data);
    }

    @Override
    public void onSerialIoError(Exception e) {
        status("connection lost: " + e.getMessage());
        disconnect();
    }
    private void connect() {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
            status("connecting...");
            connected = Connected.Pending;
            SerialSocket socket = new SerialSocket(this.getApplicationContext(), device);
            service.connect(socket);
        } catch (Exception e) {
            onSerialConnectError(e);
        }
    }
    private void status(String str) {

        receiveText.setText(str);
    }
    private void disconnect() {
        connected = Connected.False;
        service.disconnect();
    }
    private void receive(byte[] data) {
            String msg = new String(data);
            Toast.makeText(this, msg+"No hex",Toast.LENGTH_SHORT).show();

    }
    private void send(String str) {
        if(connected != Connected.True) {
            Toast.makeText(this, "not connected", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            String msg;
            byte[] data;
            msg = str;
            data = (str + newline).getBytes();

            Toast.makeText(this,str,Toast.LENGTH_SHORT);
            service.write(data);
        } catch (Exception e) {
            onSerialIoError(e);
        }
    }
}

Integration in flutter app

I have flutter app in which i want to integrate this ble app code but getting errors, please reply i need help,

Please give xmodem file receiving option on Bluetooth serial app

Please give xmodem file receiving option on Bluetooth serial terminal app, I really trying to contact you a lot of time on different platforms buti didn't get any reply, please please give this option also app hangs a lot while sharing file using xmodem please do something for that also if possible introduce new file transferring Protocols like kermit, Ymodem, Zmodem, Quick van, B- plus 🙏 it's a request, you are really doing an awesome job, please help mine

Support for nRF52840

I just tried to connect to a Particle Argon which exposes UART via these default nRF UUIDs for their UART service/characteristics

const BleUuid serviceUuid("6E400001-B5A3-F393-E0A9-E50E24DCCA9E");
const BleUuid rxUuid("6E400002-B5A3-F393-E0A9-E50E24DCCA9E");
const BleUuid txUuid("6E400003-B5A3-F393-E0A9-E50E24DCCA9E");

However, I only get Connection failed: no write characteristic although it's there and Adafruit Bluefruit recognises it.
At www.kai-morich.de/android/ble_troubleshooting.html it's mentioned that UUIDs could be customised, but I can't find where and how.

Telit Terminal IO profile?

Hello kai, thanks for directing me here from the Play Store app page.

This particular BLE device I'm working on uses a Telit chipset. This simplified version of your Play Store app does not seem to include the profile for these, however your app on the Play Store works flawlessly.

I've tried adding Telit's UUIDs:

private static final UUID BLUETOOTH_LE_TELIT_SERVICE = UUID.fromString("0000fefb-0000-1000-8000-00805f9b34fb");
    private static final UUID TELIT_DATA_RX = UUID.fromString("00000001-0000-1000-8000-008025000000");
    private static final UUID TELIT_DATA_TX = UUID.fromString("00000002-0000-1000-8000-008025000000");
 @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        Log.d(TAG, "servicesDiscovered, status " + status);
        if (canceled) {
            return;
        }
        writePending = false;
        for (BluetoothGattService gattService : gatt.getServices()) {
            UUID uuid = gattService.getUuid();
            if (uuid.equals(BLUETOOTH_LE_CC254X_SERVICE)) {
                Log.d(TAG, "service cc254x uart");
                //for(BluetoothGattCharacteristic characteristic : gattService.getCharacteristics())
                //    Log.d(TAG, "characteristic "+characteristic.getUuid());
                readCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_CC254X_CHAR_RW);
                writeCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_CC254X_CHAR_RW);
            } else if (uuid.equals(BLUETOOTH_LE_NRF_SERVICE)) {
                Log.d(TAG, "service nrf uart");
                //for(BluetoothGattCharacteristic characteristic : gattService.getCharacteristics())
                //    Log.d(TAG, "characteristic "+characteristic.getUuid());
                BluetoothGattCharacteristic rw2 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW2);
                BluetoothGattCharacteristic rw3 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW3);
                if (rw2 != null && rw3 != null) {
                    int rw2prop = rw2.getProperties();
                    int rw3prop = rw3.getProperties();
                    boolean rw2write = (rw2prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
                    boolean rw3write = (rw3prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0;
                    Log.d(TAG, "characteristic properties " + rw2prop + "/" + rw3prop);
                    if (rw2write && rw3write) {
                        onSerialConnectError(new IOException("multiple write characteristics (" + rw2prop + "/" + rw3prop + ")"));
                        return;
                    } else if (rw2write) { // some devices use this ...
                        writeCharacteristic = rw2;
                        readCharacteristic = rw3;
                    } else if (rw3write) { // ... and other devices use this characteristic
                        writeCharacteristic = rw3;
                        readCharacteristic = rw2;
                    } else {
                        onSerialConnectError(new IOException("no write characteristic (" + rw2prop + "/" + rw3prop));
                        return;
                    }
                }
            } else if (uuid.equals(BLUETOOTH_LE_TELIT_SERVICE)) {
                Log.d(TAG, "service cc254x uart");
                //for(BluetoothGattCharacteristic characteristic : gattService.getCharacteristics())
                //    Log.d(TAG, "characteristic "+characteristic.getUuid());
                readCharacteristic = gattService.getCharacteristic(TELIT_DATA_RX);
                writeCharacteristic = gattService.getCharacteristic(TELIT_DATA_TX);
            }
        }
        if (readCharacteristic == null || writeCharacteristic == null) {
            for (BluetoothGattService gattService : gatt.getServices()) {
                Log.d(TAG, "service " + gattService.getUuid());
            }
            onSerialConnectError(new IOException("no serial profile found"));
            return;
        }
        int writeProperties = writeCharacteristic.getProperties();
        if ((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE +     // Microbit,HM10-clone have WRITE
                BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) == 0) { // HM10,TI uart have only WRITE_NO_RESPONSE
            onSerialConnectError(new IOException("write characteristic not writable"));
            return;
        }
        if (!gatt.setCharacteristicNotification(readCharacteristic, true)) {
            onSerialConnectError(new IOException("no notification for read characteristic"));
            return;
        }
        BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
        if (readDescriptor == null) {
            onSerialConnectError(new IOException("no CCCD descriptor for read characteristic"));
            return;
        }
        int readProperties = readCharacteristic.getProperties();
        if ((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
            Log.d(TAG, "enable read indication");
            readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        } else if ((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
            Log.d(TAG, "enable read notification");
            readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        } else {
            onSerialConnectError(new IOException("no indication/notification for read characteristic (" + readProperties + ")"));
            return;
        }
        Log.d(TAG, "writing read characterictic descriptor");
        if (!gatt.writeDescriptor(readDescriptor)) {
            onSerialConnectError(new IOException("read characteristic CCCD descriptor not writable"));
        }
        Log.d(TAG, "writing read characteristic descriptor");
        // continues asynchronously in onDescriptorWrite()
    }

Am I doing anything wrong?

EDIT: Nevermind. I figured out what the "credits" characteristic is for.

For anyone reading this, the credits are needed for sending/receiving data. If you don't send enough credits on the characteristic with UUID:

private static final UUID RX_CREDITS = UUID.fromString("00000003-0000-1000-8000-008025000000");
With this code:

private void trySend(BluetoothGattCharacteristic characteristic, int nCredits) {
        boolean bResult = characteristic.setValue(nCredits, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        Log.v("ble", "trySendCredits setValue(): " + bResult);
        bResult = btGatt.writeCharacteristic(characteristic);
        Log.v("ble", "trySendCredits writeCharacteristic(): " + bResult);
    }

Then nothing will work.

RNBD451 Remote Command Charateristic

https://onlinedocs.microchip.com/oxy/GUID-26457D23-798C-47B0-9F40-C5DA6E995C6F-en-US-2/GUID-A7263185-4F92-4567-9A18-7433617D925E.html

Can you add RNBD451 Transparent Control Point (TCP) . This allows ASCII BLE commands to remotely control the RNBD451.
Transparent Control Point (TCP) – UUID 49535343-4C8A-39B3-2F49-511CFF073B7E

My guess in the data flow
a) Send ASCII commands from SimpleBluetoothLeTerminal
SimpleBluetoothLeTerminal Remote Commands using 49535343-4C8A-39B3-2F49-511CFF073B7E -->RNBD451

b) Receive echoed response from RNBD451
RNBD451 Rx --->Transparent UART Receive (RX) Characteristics UUID – 49535343-8841-43F4-A8D4-ECBE34729BB3 SimpleBluetoothLeTerminal

How to add timestamp in the terminal

Hi @kai-morich I want to add timestamp at starting of line in the terminal. This feature is available in your app from playstore. But when I am trying to implement it the timestamp shows up in between the receiving data. Please help me with it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.