无法成功通过蓝牙读取数据 [英] Unable to read data via bluetooth successfully

查看:95
本文介绍了无法成功通过蓝牙读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以接收数据并将数据发送到微控制器(ESP32)的App.但是由于某种原因,我无法从微控制器成功接收数据.

I'm trying to create an App which can receive data and send data to the microcontroller (ESP32). But for some reason, I'm unable to receive data from microcontroller successfully.

该应用程序是用Kotlin编写的,我已经尝试过StackOverflow上提到的一些示例,但是这些示例实际上都无法在我的代码上运行. 我可以通过蓝牙成功将数据发送到微控制器,但是无法从蓝牙接收数据. (我在微控制器中使用的方法只是"ESP_BT.println("Check");"

The app is written in Kotlin, and I already tried some examples mentioned on StackOverflow, but none of them actually works on my code. I can successfully send data to the microcontroller via Bluetooth, but I can't receive data from Bluetooth. (The method I used in the microcontroller is just simply "ESP_BT.println("Check");"

在代码段中,与我的接收数据有关的功能称为"receiveBluetooth"

In the code snippet, the function relates to my receiving data is called "receiveBluetooth"

class ControlActivity: AppCompatActivity() {

    companion object {
        val myUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
        var myBluetoothSocket: BluetoothSocket? = null
        lateinit var myProgress: ProgressDialog
        lateinit var myBluetoothAdapter: BluetoothAdapter
        var myIsConnected: Boolean = false
        lateinit var myAddress: String
        val mmInStream: InputStream? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.control_layout)
        myAddress = intent.getStringExtra(SelectDeviceActivity.EXTRA_ADDRESS)

        ConnectToDevice(this).execute()
        val btnShow = findViewById<Button>(R.id.btnShow)
        var inputRPM: String
        //Read in value and store it as String
        btnShow.setOnClickListener{
            inputRPM = receiveInput()
            sendCommand(inputRPM)
        }

        //Read RPM from microcontroller (bluetooth)
        val showCountTextView = findViewById<TextView>(R.id.textView)
        btnRefresh.setOnClickListener {
            //showCountTextView.text = receiveBluetooth()
            receiveBluetooth(showCountTextView)
        }

        control_disconnect.setOnClickListener{
            disconnect()
        }
    }



    private fun receiveInput(): String {
        val input = findViewById<EditText>(R.id.editText)
        return input.text.toString()
    }

    private fun sendCommand(input: String) {
        if (myBluetoothSocket != null) {
            try{
                myBluetoothSocket!!.outputStream.write(input.toByteArray())
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    private fun receiveBluetooth(input: TextView) {
        val buffer = ByteArray(256)
        val bytes:Int
        var tmpIn: InputStream? = null
        if (myBluetoothSocket != null) {
            try {
                tmpIn = myBluetoothSocket!!.inputStream
                val mmInStream = DataInputStream(tmpIn)
                bytes = mmInStream.read(buffer)
                val readMessage = String(buffer, 0, bytes)
                input.text = readMessage
                //input.text="123"
            } catch (e:IOException) {
                e.printStackTrace()
            }
        }


    }


    private fun disconnect() {
        if (myBluetoothSocket != null) {
            try {
                myBluetoothSocket!!.close()
                myBluetoothSocket = null
                myIsConnected = false
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        finish()
    }
    private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String> () {
        private var connectSuccess: Boolean = true
        private val context: Context

        init {
            this.context = c
        }

        override fun onPreExecute() {
            super.onPreExecute()
            myProgress = ProgressDialog.show(context, "Connecting", "Please wait")
        }

        override fun doInBackground(vararg params: Void?): String? {
            try {
                if (myBluetoothSocket == null || !myIsConnected) {
                    myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
                    val device: BluetoothDevice = myBluetoothAdapter.getRemoteDevice(myAddress)
                    myBluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID)
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
                    myBluetoothSocket!!.connect()
                }
            } catch (e: IOException) {
                connectSuccess = false
                e.printStackTrace()
            }
            //Needs be fixed
            return null
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            if (!connectSuccess) {
                Log.i("data", "couldn't connect")
            } else {
                myIsConnected = true
            }
            myProgress.dismiss()
        }
    }
}

我希望文本将完全显示检查",但是,我的文本将仅显示我分配的初始值.

I expect the text will show exactly "Check", but instead, my text will only show the initial value that I assigned.

推荐答案

也许您应该使用一个库.对我来说, RxAndroidBle 库效果很好:

Maybe you should use a library. For me works fine RxAndroidBle library:

成绩:

implementation "com.polidea.rxandroidble2:rxandroidble:1.8.1"

实施:

我的项目中,该版本使用Android Java和 ESP32 我也通过一些简单的实现来阅读一些特征或值,例如:

In my project with Android Java and ESP32 too, I read some characteristics or values with simple implementations, for example:

public void setupNotification() {
    if (isConnected()) {
        final Disposable disposable = connectionObservable
                .flatMap(rxBleConnection -> rxBleConnection.setupNotification(charactSensorDataUuid))
                .doOnNext(notificationObservable -> { notificationHasBeenSetUp(); })
                .flatMap(notificationObservable -> notificationObservable)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onNotificationReceived, this::onNotificationSetupFailure);
        compositeDisposable.add(disposable);
    }
}

public void readSensorConfig(){
    if (isConnected()) {
        final Disposable disposable = connectionObservable
                .firstOrError()
                .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(charactConfigUuid))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onSensorConfigRead, this::onReadFailure);
        compositeDisposable.add(disposable);
    }
}

public void readSensorData(){
    if (isConnected()) {
        final Disposable disposable = connectionObservable
                .firstOrError()
                .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(charactSensorDataUuid))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onSensorDataRead, this::onReadFailure);
        compositeDisposable.add(disposable);
    }
}

完整的Java实现在这里:

The complete Java implementation is here:

向Kotlin的迁移应该很简单,在此库上,主要目标是蓝牙BLE ,并且它们有许多

The migration to Kotlin should be simple, also on this library the main target is Bluetooth BLE, and they have many samples on Kotlin

这篇关于无法成功通过蓝牙读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆