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.activity.enableEdgeToEdge
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.core.app.ActivityCompat
|
import androidx.core.app.ActivityCompat
|
||||||
|
import java.io.BufferedReader
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
import java.util.*
|
import java.util.*
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
@ -27,6 +29,9 @@ class MainActivity : AppCompatActivity() {
|
|||||||
private var bluetoothSocket: BluetoothSocket? = null
|
private var bluetoothSocket: BluetoothSocket? = null
|
||||||
private var isConnected = false
|
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?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
@ -91,13 +96,27 @@ class MainActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
private fun listenForData() {
|
private fun listenForData() {
|
||||||
val inputStream = bluetoothSocket?.inputStream ?: return
|
val inputStream = bluetoothSocket?.inputStream ?: return
|
||||||
val buffer = ByteArray(64)
|
val reader = BufferedReader(InputStreamReader(inputStream))
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
try {
|
try {
|
||||||
val bytes = inputStream.read(buffer)
|
val message = reader.readLine()?.trim() ?: break
|
||||||
val message = String(buffer, 0, bytes)
|
|
||||||
Log.i(tag, "Received: $message")
|
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) {
|
} catch (e: IOException) {
|
||||||
Log.e(tag, "Can't read data", e)
|
Log.e(tag, "Can't read data", e)
|
||||||
break
|
break
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user