Я пытаюсь прочитать вес из взвешивания, подключенной к блутузу, задержка чувствует себя хуже всего, эта часть моего приложения будет использоваться в быстро меняющемся действии, так что это слишком много, мне нужно, чтобы ответ был заполнен менее 1 сек, если я должен был поместить элемент следующей фракции секунды, я должен был видеть, как вес заполняется, я использую Android Kotlin+Java < /P>
< /> < /P> < /P>
java < /p> < /p> < /p> < /p> < /p>
java < /p>private fun connectToScale(device: BluetoothDevice) {
CoroutineScope(Dispatchers.IO).launch {
try {
withContext(Dispatchers.Main) {
kotBinding.progressBar.visibility = View.VISIBLE // Move to main thread
}
val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // SPP UUID
if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
} else {
runOnUiThread {
Toast.makeText(this@KotActivity, "Bluetooth permission not granted", Toast.LENGTH_SHORT).show()
}
}
bluetoothSocket?.connect()
readWeightFromScale()
} catch (e: Exception) {
runOnUiThread {
Toast.makeText(this@KotActivity, "Connection failed", Toast.LENGTH_SHORT).show()
kotBinding.measureWithScale.isChecked = false
}
} finally {
withContext(Dispatchers.Main) {
kotBinding.progressBar.visibility = View.GONE // Move to main thread
} }
}
}
private fun readWeightFromScale() {
val inputStream: InputStream? = bluetoothSocket?.inputStream
val buffer = ByteArray(1024)
val stringBuilder = StringBuilder()
val weightRegex = Regex("""-?\d{1,3}\.\d{1,3}""")
var lastWeightValue = 0.0
val minWeightDifferenceThreshold = 0.003 // Fine-grained sensitivity
CoroutineScope(Dispatchers.IO).launch {
while (isReadingBluetooth) {
try {
if (inputStream != null && inputStream.available() > 0) {
val bytes = inputStream.read(buffer)
if (bytes > 0) {
val incomingData = String(buffer, 0, bytes)
stringBuilder.append(incomingData)
val match = weightRegex.find(stringBuilder)
if (match != null) {
val rawWeight = match.value.trim()
val cleanWeight = try {
rawWeight.toBigDecimal().setScale(3).toPlainString()
} catch (e: Exception) {
continue
}
stringBuilder.clear()
val newWeightValue = cleanWeight.toDoubleOrNull() ?: continue
if (kotlin.math.abs(newWeightValue - lastWeightValue) >= minWeightDifferenceThreshold) {
lastWeightValue = newWeightValue
Log.d("FastWeight", "Updated Weight: $cleanWeight")
runOnUiThread {
kotBinding.quantity.setText(cleanWeight)
}
}
}
}
}
delay(10) // Poll frequently, avoid CPU overuse
} catch (e: Exception) {
runOnUiThread {
Toast.makeText(this@KotActivity, "Error reading weight", Toast.LENGTH_SHORT).show()
kotBinding.measureWithScale.isChecked = false
}
break
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... in-android
Bluetooth Scale Scale Проблема задержки чтения в Android ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Scipy-correlate: как изменить задержки точек данных на временные задержки?
Anonymous » » в форуме Python - 0 Ответы
- 149 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Android Get Bluetooth Device Новое имя изменилось в настройках Bluetooth
Anonymous » » в форуме Android - 0 Ответы
- 4 Просмотры
-
Последнее сообщение Anonymous
-