无法成功通过蓝牙读取数据

时间:2019-04-14 21:26:43

标签: android kotlin bluetooth bluetooth-lowenergy esp32

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

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

在代码段中,与我的接收数据有关的功能称为“ 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()
        }
    }
}

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

1 个答案:

答案 0 :(得分:0)

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

成绩

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

实施

my project中也使用Android Java和 ESP32 ,我通过简单的实现读取了一些特征或值,例如:

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实现在这里:

https://github.com/kike-canaries/android-hpma115s0/blob/master/app/src/main/java/hpsaturn/pollutionreporter/common/BLEHandler.java

向Kotlin的迁移应该很简单,在此库上,主要目标是蓝牙BLE ,并且在 Kotlin samples >