Git Product home page Git Product logo

androidbluetoothlibrary's Introduction

AndroidBluetoothLibrary

Licence MIT Release Downloads Android Arsenal

A Library for easy implementation of Serial Bluetooth Classic and Low Energy on Android. πŸ’™

  • Bluetooth Classic working from Android 2.1 (API 7)
  • Bluetooth Low Energy working from Android 4.3 (API 18)

Use

Configuration

Bluetooth Classic

BluetoothConfiguration config = new BluetoothConfiguration();
config.context = getApplicationContext();
config.bluetoothServiceClass = BluetoothClassicService.class;
config.bufferSize = 1024;
config.characterDelimiter = '\n';
config.deviceName = "Your App Name";
config.callListenersInMainThread = true;

config.uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // Required

BluetoothService.init(config);

Bluetooth Low Energy

BluetoothConfiguration config = new BluetoothConfiguration();
config.context = getApplicationContext();
config.bluetoothServiceClass = BluetoothLeService.class;
config.bufferSize = 1024;
config.characterDelimiter = '\n';
config.deviceName = "Your App Name";
config.callListenersInMainThread = true;

config.uuidService = UUID.fromString("e7810a71-73ae-499d-8c15-faa9aef0c3f2"); // Required
config.uuidCharacteristic = UUID.fromString("bef8d6c9-9c21-4c9e-b632-bd58c1009f9f"); // Required
config.transport = BluetoothDevice.TRANSPORT_LE; // Required for dual-mode devices
config.uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // Used to filter found devices. Set null to find all devices.

BluetoothService.init(config);

Getting BluetoothService

BluetoothService service = BluetoothService.getDefaultInstance();

Scanning

service.setOnScanCallback(new BluetoothService.OnBluetoothScanCallback() {
    @Override
    public void onDeviceDiscovered(BluetoothDevice device, int rssi) {
    }

    @Override
    public void onStartScan() {
    }

    @Override
    public void onStopScan() {
    }
});

service.startScan(); // See also service.stopScan();

Connecting

service.setOnEventCallback(new BluetoothService.OnBluetoothEventCallback() {
    @Override
    public void onDataRead(byte[] buffer, int length) {
    }

    @Override
    public void onStatusChange(BluetoothStatus status) {
    }

    @Override
    public void onDeviceName(String deviceName) {
    }

    @Override
    public void onToast(String message) {
    }

    @Override
    public void onDataWrite(byte[] buffer) {
    }
});

service.connect(device); // See also service.disconnect();

Writing

BluetoothWriter writer = new BluetoothWriter(service);

writer.writeln("Your text here");

Complete example

See the sample project.

Download

  1. Add it in your root build.gradle at the end of repositories:

    allprojects {
      repositories {
        ...
        maven { url "https://jitpack.io" }
      }
    }
  2. Add the dependency

    2.1. Bluetooth Classic

    dependencies {
      implementation 'com.github.douglasjunior.AndroidBluetoothLibrary:BluetoothClassicLibrary:0.3.5'
    }

    2.2. Bluetooth Low Energy

    dependencies {
      implementation 'com.github.douglasjunior.AndroidBluetoothLibrary:BluetoothLowEnergyLibrary:0.3.5'
    }
  3. Add permission in AndroidManifest.xml

<manifest ...>
  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  ...
</manifest>

Known Issues / Troubleshooting

  • Scanning will not detect bluetooth devices if the user has denied Location Privacy Permission to your app. This library does not test for the permission and will not raise errors. (Android 6.0+) See: http://stackoverflow.com/a/33045489/2826279

Contribute

New features, bug fixes and improvements are welcome! For questions and suggestions use the issues.

Before submit your PR, run the gradle check.

./gradlew build connectedCheck

Become a Patron! Donate

Licence

The MIT License (MIT)

Copyright (c) 2015 Douglas Nassif Roma Junior

See the full licence file.

androidbluetoothlibrary's People

Contributors

douglasjunior avatar johnhowe avatar masonlee avatar shinilms-nimo avatar ugreg 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

androidbluetoothlibrary's Issues

status NONE after try to connect

I am having a problem connecting to a paired device
when I try to connect to the device , status changes to connecting and right after that it changes to NONE

what should I do to fix this ? @douglasjunior

im using classic mode and set the uuid to be null as you said for finding all the devices

Trouble receiving onDataRead

Hi,

I'm currently using your library to connect to a Bluetooth device through a serial port. So far everything was working great without any hiccups.
However when i started refactoring my code to have something more modular and not pollute my Fragment class, i encountered something weird.
Everything was still working however i do not receive any onDataRead callback, yet all the others callback from OnBluetoothEventCallback still works perfectly.

Am i missing something ?
Thanks in advance for your help

Regards,
Roguyt

writeCharacteristic always returning false

Hi. I'm trying to write using your lib but on the logs I can see that the method writeCharacteristic is always returning false. I've been looking on the internet and it may have something to do with multiple gatt operations? I'm not sure, I have to write and read multiple times but it fails even on the first time

I'm writing like this

if (mService != null) {
            BluetoothWriter writer = new BluetoothWriter(mService);
            writer.writeln(msg+"\n");
            Log.d(TAG, "Writting: " + msg);
}

trying to send bytes, but always receiving ascii chars

Hi
Thank you for your great work on the AndroidBluetoothLibrary, made the work easy and reliable for some one new to BT connections like me.
I'm moving to a bit more advanced stuff and encountered a problem, I'm working on the app side while somebody else is doing the hardware part (SPP-C).
the problem is when he is trying to send anything like a byte that gets translated to 127 (11111111) which is a single bye on his side, it gets translated to ascii code counter parts on my side, in our example 127 becomes 49 (1) 50 (2) 7(55). (so i receive 3 bytes of ascii code instead of 1 byte of data equal to 127).

we tried several methods like sending as hex and other stuff but all had the same result for example for 0xAA I receive 65(A) 65(A).

I wanted to know if this problem is because of bluetooth protocol, library or maybe and error on our part.

thanks a lot

Crash when set minifyEnabled true with error ArrayIndexOutOfBoundsException

I am try to set minifyEnabled true in build.gradle and it crash when I call init

        val config = BluetoothConfiguration().apply {
            context = applicationContext
            bluetoothServiceClass = BluetoothClassicService::class.java
            bufferSize = 1024
            characterDelimiter = '\n'
            deviceName = "Android"
            callListenersInMainThread = true
            uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
        }

BluetoothService.init(config)

This is log for crash:

2021-09-12 10:30:19.942 4103-4103/ E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.dev, PID: 4103
java.lang.RuntimeException: Unable to create application com.android.MainApplication: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6733)
at android.app.ActivityThread.access$1500(ActivityThread.java:247)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2057)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.github.douglasjunior.bluetoothclassiclibrary.BluetoothService.e(SourceFile:188)
at com.android.MainApplication.t(SourceFile:131)
at com.android.MainApplication.onCreate(SourceFile:127)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1211)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6728)
at android.app.ActivityThread.access$1500(ActivityThread.java:247)Β 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2057)Β 
at android.os.Handler.dispatchMessage(Handler.java:106)Β 
at android.os.Looper.loopOnce(Looper.java:201)Β 
at android.os.Looper.loop(Looper.java:288)Β 
at android.app.ActivityThread.main(ActivityThread.java:7842)Β 
at java.lang.reflect.Method.invoke(Native Method)Β 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)Β 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)Β 

So I go to source com.github.douglasjunior.bluetoothclassiclibrary.BluetoothService.e(SourceFile:188) and found that this line make app crash
mDefaultConfiguration.bluetoothServiceClass.getDeclaredConstructors()[0]

public static void init(BluetoothConfiguration config) {
        mDefaultConfiguration = config;
        if (mDefaultServiceInstance != null) {
            mDefaultServiceInstance.stopService();
            mDefaultServiceInstance = null;
        }
        try {
            Constructor<? extends BluetoothService> constructor =
                    (Constructor<? extends BluetoothService>) mDefaultConfiguration.bluetoothServiceClass.getDeclaredConstructors()[0];
            constructor.setAccessible(true);
            BluetoothService bluetoothService = constructor.newInstance(mDefaultConfiguration);
            mDefaultServiceInstance = bluetoothService;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

Status Connect

OlΓ‘,
Estou tentando conectar a um dispositivo BLE (consigo escanear e adicionar na RecyclerView), quando clico nele na RecyclerView sΓ³ uma vez, ele muda de status para Connecting e depois None, e sΓ³ depois que eu clico trΓͺs ou mais vezes seguidas, ele conecta (o led do Bluetooth fica normal em vez de piscando), mas mesmo ele conectando, nΓ£o retorna o status como Connected.

Bluetooth Device Connection Without Pairing Passcode

Can we connect to the Bluetooth device (e.g. Health Device, Wireless EarPhone etc etc.) without entering any pairing passcode with this library?

For example, I need to connect to this device without entering any pairing code for the first time or anytime.

This device has their own application and it is capable to connect automatically when the device is in range. So I know this thing is possible but don't know how to do this.

Is this library capable to connect like the flow I have mentioned above?

Thank you very much for your help in advance.

startScan returns duplicated devices.

It's actually tested on React Native project with react-native-easybluetooth-classic which wraps this library.

Hi, thanks for the great library.

I tried scan with below code.

            (async () => {
                const config = {
                    "deviceName": "XXXXX",
                    "bufferSize": 1024,
                    "characterDelimiter": "\n"
                }
                let res = EasyBluetooth.init(config);
                console.log('[BT init]', res);

                res = await EasyBluetooth.startScan();
                console.log('[BT startScan]', res);
            })();

It returns 26 objects but the problem is that they are all same objects.
I'm not testing in a special place but just in the house.
The address and name of them are all same.

Any help?

Thanks.

Unable to connect device

Hi there, I'm using Bluetooth classic library to connect devices such as phone and tablets via Bluetooth but it is not working, every time i try to connect device i get error

 W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
 W/System.err:     at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:772)
 W/System.err:     at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:786)
 W/System.err:     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:404)
 W/System.err:     at com.github.douglasjunior.bluetoothclassiclibrary.BluetoothClassicService$ConnectThread.run(BluetoothClassicService.java:262)

even using sample app provided by you same error is coming, please help on this

Enabling BLE Notifications

I'm trying to implement BLE notifications and I've basically copied the BluetoothLeService class and added this

 UUID CONFIG_DESCRIPTOR = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
 BluetoothGattDescriptor desc = characteristic.getDescriptor(CONFIG_DESCRIPTOR);
 desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
 gatt.writeDescriptor(desc);
 gatt.setCharacteristicNotification(desc.getCharacteristic(), true);

to this line

.

So it first glance it appears to be working and onCharacteristicRead get hit consistently but when it gets to onDataRead and I decode it to hex I get

onDataRead: 010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000000000000000000000000000000000000001000000000000000000000000000000000000000100000000000000000000000000000000000000010000

Which looks to be garbage data.

My setup config is

        this.config = BluetoothConfiguration()
        this.config.bluetoothServiceClass = MyBluetoothLeService::class.java
        this.config.context = context
        this.config.bufferSize = 1024
        this.config.characterDelimiter = '\n'
        this.config.deviceName = "GNSS Mapper"
        this.config.callListenersInMainThread = true
        this.config.uuid = null

        this.config.uuidService = UUID.fromString("3cfc0000-89d0-472c-ad37-80d868ffbaa5")
        this.config.uuidCharacteristic = UUID.fromString("3cfc0004-89d0-472c-ad37-80d868ffbaa5")
        this.config.transport = BluetoothDevice.TRANSPORT_LE
        this.config.connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_HIGH

        MyBluetoothLeService.init(this.config);
        this.service = MyBluetoothLeService.getDefaultInstance()
        this.service.setOnScanCallback(this)
        this.service.setOnEventCallback(this)

Kotlin: not find any device

I implement your library in Kotlin , it starts scanning but no device is found , is there anything more than implementing the scan callback ?
onDeviceDescover won't call , but after some times of scanning , onScanStop gets called

I set the uuid to be null and I'm using the basic library

Currupt data in onDataRead(byte[] buffer, int length), BLE.

I'm using the latest version of your library (0.3.3 BLE version) for communication with an Arduino board, its repeatedly sends a string of data via Bluetooth LE, - {imei: 861311006131360,name: 'Bluetooth nmea',ver: 8}

Before stating the issue I want to assure you that the problem is not with my Arduino board, since I've used it with google's official android Bluetooth LE API and it worked flawlessly.

The issue
I've noticed that the data passed to onDataRead event callback sometimes has missing/misplaced characters in comparison to the raw data which is logged inside onCharacteristicChanged of BluetoothLeService. I suspect that the reason is readData(byte[] data) which is called in onCharacteristicChanged.

For brevity I use StringBuilder in onDataRead callback to append and log the data from the buffer.

public void onDataRead(byte[] buffer, int length) {
                String s = new String(buffer, 0, length);
                sb.append(s);
                Log.d(TAG, sb.toString());
            }

In the attached log you can see that the displayed data differs from the raw data of the characteristic, for example:
Line 25 - the IMEI value has a missing character - 86131100631360.
Line 29 - IMEI is 86311006131360.
Line 34 - iei instead of imei.
However onCharacteristicChanged always have the proper value, received in three parts:

{imei: 8613110061313
60, name: 'Bluetooth
nmea', ver: 8}

I guess that reaData(byte[] data) does something weird.
Solution - fix reaData or just return the raw characteristic from onCharacteristicChanged.

Here is the BluetoothConfiguration:

BluetoothConfiguration config = new BluetoothConfiguration();
        config.context = getApplicationContext();
        config.bluetoothServiceClass = BluetoothLeService.class;
        config.bufferSize = 23;
        config.characterDelimiter = '\n';
        config.deviceName = "Your App Name";
        config.callListenersInMainThread = false;

        config.uuidService = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
        config.uuidCharacteristic = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            config.transport = BluetoothDevice.TRANSPORT_LE;
        }
        BluetoothService.init(config);
        service = BluetoothService.getDefaultInstance();

I've tried changing the configuration: buffer size, delimiter and running of main thread but the result is always the same - missing characters in the string created from buffer of onDataRead.

make the buffering using characterDelimiter optional when receiving data

The characterDelimiter feature prevents some protocol to actually be implemented if a message payload is defined by a different mean than delimiter at the end (for instance the first 2 received bytes could define the payload length).

If the "buffering" was part of the react native application instead of being in the bluetooth bridge, that would open up a whole new set of possibilities.

This actually prevent me from receiving a message from my body scale that doesn't have a character delimiter at the end of it's messages...

Read data from Bluetooth device

Hi @johnhowe @douglasjunior ,
I would like try to read the data from bluetooth device over android app. When I was send the data to bluetooth device over android app the data has been sent successfully. But at the same time when i was try to read the data at android app side, am unable to read the data. I am using HM-10 bluetooth module. Here mDevice is a bluetooth mac address.
This is my code

final BluetoothService service = BluetoothService.getDefaultInstance();
        //
        service.setOnEventCallback(new BluetoothService.OnBluetoothEventCallback() {
            @Override
            public void onDataRead(byte[] buffer, int length) {
                str = new String(buffer,0,length);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"received data="+str,Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onStatusChange(BluetoothStatus status) {
                Log.d(TAG,"status:"+status);
            }

            @Override
            public void onDeviceName(String deviceName) {
                Log.d(TAG,"device:"+deviceName);
            }

            @Override
            public void onToast(String message) {
                Log.d(TAG,"message:"+message);

            }

            @Override
            public void onDataWrite(byte[] buffer) {

            }
        });
        service.connect(mDevice);

Can anyone please help me. How to receive the data over the android app.
Thanks in advance
Amar Pulli.

Library fails when targetSdkVersion > 22

Library fails on discovery and pairing when the targetSdkVersion is 23 or above. I only works on SDK versions 7 (assumed based on ReadME) to 22.

I was trying to mimic your kotlin implementation and checked on everything, my configuration is basically the same as what you have on your demo app, the ony difference is the targetSdkVersion I changed mine to 22 and then it worked. I changed your sample to 26, the sample failed to do discovery and pairing.

can't start scan

when i start scan it will stop immediately.

    private fun initializeBluetoothService() {
        val config = BluetoothConfiguration()
        config.context = applicationContext
        config.bluetoothServiceClass = BluetoothClassicService::class.java // BluetoothClassicService.class or BluetoothLeService.class
        config.bufferSize = 1024
        config.characterDelimiter = '\n'
        config.deviceName = "Test"
        config.callListenersInMainThread = true

// Bluetooth Classic
        config.uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb") // Required\

        BluetoothService.init(config)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //init bt
        initializeBluetoothService()
        mservice = BluetoothService.getDefaultInstance()

        //start scan
        mservice!!.setOnScanCallback(object : BluetoothService.OnBluetoothScanCallback {
            override fun onDeviceDiscovered(device: BluetoothDevice, rssi: Int) {
                if(device.name=="test_device")
                {
                    showToast("connect ${device.name},${device.uuids}");
                    bt_device=device;
                    mservice!!.connect(device) // See also service.disconnect();
                }
                else
                {
                    showToast(device.name);
                }
            }

            override fun onStartScan() {
                showToast("start scan");
            }

            override fun onStopScan() {
                showToast("stop scan");
            }
        })

        //connect callback
        mservice!!.setOnEventCallback(this)

        BtConnectBT.setOnClickListener {
            mservice!!.startScan() // See also service.stopScan();
        }

    }

    override fun onResume() {
        super.onResume()
        mservice!!.setOnEventCallback(this)
    }


    override fun onDataRead(p0: ByteArray?, p1: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onStatusChange(p0: BluetoothStatus?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onDataWrite(p0: ByteArray?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onToast(p0: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onDeviceName(p0: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

it work should like :
button down->start scan->find device name "test device"->connect

but when i press button ,i will see start scan and stop scan immediately

is there auto connection ?

Hi
Thank you for this Library
I have question about this Library
Is there any option for auto connection for Specific Device after Loss Connection ?

There is a problem connecting to iOS/OSX BLE.

There is a problem connecting to iOS/OSX BLE.
Connection is completed and writing is ok.
However, onDataRead does not work.
I did various tests and found a solution.
But, I do not know why because I do not know about Bluetooth.

--- BluetoothLeService.java 200 line ---

boolean isOK = gatt.setCharacteristicNotification(characteristic, true);
if (isOK) {
     for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) { 
          descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
          gatt.writeDescriptor(descriptor);
     }
}

Reading on demand.

Hello, sorry if this is a stupid question but I was wondering if there is a way to read from a peripheral device on demand, like for example when I press a button or something else? As far as I understand you can read when a device writes to you, but I was still wondering if there is another way to read.
Thank you in advance.

Pairing

Hi,Thank you for being so helpful the last time... Could you please guide me with pairing using the library ... Help would be appreciated

Connection not working using other package name

The connection works fine when using the default package name of the sample project, the connection stops working after changing the package name. the activity initiates StartScan() and then stops by calling StopScan() after some time.
The project worked fine before changing the package name (com.github.douglasjunior.bluetoothsamplekotlin) -> (com.example.company)
The project builds without any error.

Multiple characteristics per single service

I would like to use your AndroidBluetoothLibrary (the BLE implementation) in one personal project and I'm wondering how to setup a service with multiple characteristics. From the sample code it looks like it's possible to pass only one characteristic per service.

D is set to true in BluetoothService.

The D property is set to true in BluetoothService, it results in debug log messages always being produced when using BluetoothClassicService.
The library currently can't be used for production since google forbids logging in release grade applications.

Connected status

How to check whether Bluetooth is connected or not after restarting the app and on different-different activities.

OnReadyRead only when bufferSize is reached

As mentioned in #41
OnDataRead will be called when a characterDelimiter is received, or when the total data received exceeds the character limit of bufferSize.

Originally posted by @douglasjunior in #41 (comment)

Is there anyway to set OnDataRead to be called ONLY when config.bufferSize is reached?
I don't care about character delimiter. Just want to read fixed-size portions of data.

bufferArray & characterDelimiter

I try to connect to bluetooth kitchen scale. Scale send data like this:

[Condition]+[sp]+[Weight] + [Unit]+[sp]+[sp]+[Checksum] +[CR]+[LF]
(Total 16 Characters. The instrument sends the package continuously)

How can i find and set correct buffer size or correct characterDelimiter.

onDataRead doesn't invoke

I'm struggling on reading data . I'm using RN4871 device and connecting and writing works like a charm, but can't get onDataRead invoke. I've been trying different characterDelimiters and bufferSizes and I understand how they should work, but I'm not able to receive anything.

My config code on main activity:

 BluetoothConfiguration config = new BluetoothConfiguration();
        config.context = getApplicationContext();
        config.bluetoothServiceClass = BluetoothLeService.class;
        config.bufferSize = 24;
        config.characterDelimiter = '\n';
        config.deviceName = "ble test";
        config.callListenersInMainThread = false;
        config.uuidService = UUID.fromString("49535343-FE7D-4AE5-8FA9-9FAFD205E455"); // Required
        config.uuidCharacteristic = UUID.fromString("49535343-1E4D-4BD9-BA61-23C647249616"); // Required
        config.uuid = null;
        BluetoothService.init(config);

        mService = BluetoothService.getDefaultInstance();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        deviceList.addAll(mBluetoothAdapter.getBondedDevices());

        mService.setOnEventCallback(this);

setOnEventCallback:

  @Override
    public void onDataRead(byte[] buffer, int length) {
        Log.d(TAG, "onDataRead");
    }

    @Override
    public void onStatusChange(BluetoothStatus status) {
        Log.d(TAG, "onStatusChange: " + status);
    }

    @Override
    public void onDeviceName(String deviceName) {
        Log.d(TAG, "onDeviceName: " + deviceName);
    }

    @Override
    public void onToast(String message) {
        Log.d(TAG, "onToast");
    }

    @Override
    public void onDataWrite(byte[] buffer) {
        Log.d(TAG, "onDataWrite");
    }

On AndroidManifest I have added location and bluetooth permissions except BLUETOOTH_PRIVILEGED, which seems to be protected permission.

What I'm missing?

BluetoothService init

When calling BluetoothService.init(config), app crashes with 'InstantiationException'. Error message: 'Can't instantiate abstract class com.github.douglasjunior.bluetoothclassiclibrary.BluetoothService'. Help please

Client/Server Architecture?

Hi. Can I somehow connect to multiple Bluetooth devices simultaneously with library? I basically want to connect several Bluetooth clients to one Bluetooth server. Or can the BluetoothService object only handle one connection at a time?

Message Queueing

@douglasjunior How can I wait for a response before running another command? I.e I have a list of 3 commands, before running the second command, I wait for a response from the first one.

Unable to send message.

I am trying to send a message over BLE, the devices are connected to each other but the message is not sent. I think the issue is this:
E/BluetoothLeService: Could not find uuidService:e7810a71-73ae-499d-8c15-faa9aef0c3f2 and uuidCharacteristic:bef8d6c9-9c21-4c9e-b632-bd58c1009f9f
but I don't understand what to do with it.

P.S
I am just getting a list of devices and then I user the normal connection method(service.connect()) to connect with one of them.

Write/notifiy different characteristic

Hello,

Thank you for this awesome library.
I have to use two characteristics for the read and write operations.
If I understand correctly this is not possible:
#16

Do I understand it well or I misunderstand something?

Thank you.

BLE and Serial in same project?

I was wondering if it were possible to use this library to use both BLE and Bluetooth Serial at the same time (at least for scanning)?
My application needs to connect to Bluetooth LE, Serial and Wifi devices, 1 active connection, but needs support for all three methods of connection. From my initial research into this library it doesn't seem possible. Am I wrong? Can both libraries be used in the same project?

Envio duplicado

Oi Douglas! Primeiramente queria te parabenizar por seu trabalho!
Cara estou com um problema aqui em alguns momentos que aciono comando de envio de mensagem (writeln) acabo recebendo a mensagem de forma duplicada, atΓ© no logcat parece que sua lib faz o envio duplicado. Alguma chance de ser o fato de estar conectado a uma Characteristic com dois Descriptor, nesse caso o dispositivo BLE (HMSoft-10 lendo na serial) receberia uma mensagem em cada Descriptor?

Nao consigo recepcionar nada no public void onDataRead(byte[] buffer, int length) {

Boas, tudo bem?
Olha o meu objectivo era fazer um pedido a um servidor remoto, que responde de imediato, enviando uma trama, e receber a resposta.
Testei com um terminal e funciona, mas desta forma nao.

Enviar, sem problemas, receber Γ© que nao

 service.setOnEventCallback(new BluetoothService.OnBluetoothEventCallback() {
            @Override
            public void onDataRead(byte[] buffer, int length) {
                String text = new String(buffer, 0, length);
                Toast.makeText(getApplication().getBaseContext(), text, Toast.LENGTH_SHORT).show();
            }

 public void enviar(View view) throws UnsupportedEncodingException {

        writer = new BluetoothWriter(service);
...
writer.writeln(joined);
}

podes ajudar?

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.