Parses and stores temperature and humidity stats from bluetooth stream
This commit is contained in:
parent
ccc3988c51
commit
06c4940a20
@ -12,7 +12,9 @@ import android.widget.Toast
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.app.ActivityCompat
|
||||
import java.io.BufferedReader
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.util.*
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
@ -27,6 +29,9 @@ class MainActivity : AppCompatActivity() {
|
||||
private var bluetoothSocket: BluetoothSocket? = null
|
||||
private var isConnected = false
|
||||
|
||||
private data class SensorReading(val secSinceStart: Long, val temperature: Float, val humidity: Float)
|
||||
private val sensorHistory = mutableListOf<SensorReading>()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
@ -91,13 +96,27 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
private fun listenForData() {
|
||||
val inputStream = bluetoothSocket?.inputStream ?: return
|
||||
val buffer = ByteArray(64)
|
||||
val reader = BufferedReader(InputStreamReader(inputStream))
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
val bytes = inputStream.read(buffer)
|
||||
val message = String(buffer, 0, bytes)
|
||||
val message = reader.readLine()?.trim() ?: break
|
||||
|
||||
Log.i(tag, "Received: $message")
|
||||
|
||||
val parts = message.split(";")
|
||||
if (parts.size == 2) {
|
||||
val temp = parts[0].toFloatOrNull()
|
||||
val hum = parts[1].toFloatOrNull()
|
||||
|
||||
if (temp != null && hum != null) {
|
||||
val reading = SensorReading(System.currentTimeMillis(), temp, hum)
|
||||
sensorHistory.add(reading)
|
||||
Log.d(tag, "Store: $reading")
|
||||
} else {
|
||||
Log.w(tag, "Invalid message format: $message")
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.e(tag, "Can't read data", e)
|
||||
break
|
||||
|
||||
Loading…
Reference in New Issue
Block a user