Search code examples
androidkotlinbluetoothbluetooth-lowenergyesp32

Kotlin app failing to connect to bluetooth socket (ESP32S device)


val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice(deviceAddress)
        val uuid: UUID = UUID.fromString(uuidString)
        try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
            Log.d("BluetoothHelper", "Socket created: $bluetoothSocket")
            bluetoothSocket.connect()
            Log.d("BluetoothHelper", "Socket connected: $bluetoothSocket")
            inputStream = bluetoothSocket.inputStream
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("BluetoothHelper", "Socket failed!!!!!!!!!!!! $bluetoothSocket")
        }

I'm trying to connect my app via bluetooth to an ESP32S device but connect() function doesn't seem to be working. Socket created and failed logs get printed out and connected obviously doesn't. From what I've gathered from debugging it seems that bluetoothSocket does change its values appropriately and saves the device it's assigned to it (both uuid and deviceAddress are hardcoded) aswell as OutputStream gaining some value but the connection isn't happening and inputStream stays null. The only thing I've tried is reversing the uuid since im using a byte array in my cpp code and string in my Kotlin app but it doesn't help. What else could be the issue if other functions are working properly? How could I even be affecting connect() if im not giving it any additional parameters that weren't previously used in functions that have passed? Also, I'm using BLE.

[Values after running the app

Values after running the app


Solution

  • The code that you have provided is for classic Bluetooth, and therefore it will not work for the ESP32S which is a BLE device. For BLE, you need to use the connectGatt() function. Please see links below for more info:-