diff --git a/app/src/main/kotlin/com/bodycamera/twentyfoulabs/data/backend/BackendIntegrationManager.kt b/app/src/main/kotlin/com/bodycamera/twentyfoulabs/data/backend/BackendIntegrationManager.kt index 3da381f..ab65547 100644 --- a/app/src/main/kotlin/com/bodycamera/twentyfoulabs/data/backend/BackendIntegrationManager.kt +++ b/app/src/main/kotlin/com/bodycamera/twentyfoulabs/data/backend/BackendIntegrationManager.kt @@ -92,10 +92,58 @@ class BackendIntegrationManager @Inject constructor( fun publishTelemetry(payload: JSONObject) { val envelope = JSONObject() - .put("deviceId", deviceId) + .put("deviceId", BackendConfig.DEVICE_SERIAL) .put("timestamp", System.currentTimeMillis()) .put("payload", payload) - enqueuePublish("m530/$deviceId/telemetry", envelope) + httpExecutor.execute { + var conn: HttpURLConnection? = null + try { + val token = runBlocking { + authSessionStore.token.first() + }?.takeIf { it.isNotBlank() } + ?: error("No hay sesion JWT activa") + + val url = URL( + BackendConfig.API_BASE_URL.trimEnd('/') + + "/mobile/v1/devices/telemetry" + ) + + conn = (url.openConnection() as HttpURLConnection).apply { + requestMethod = "POST" + connectTimeout = 15_000 + readTimeout = 30_000 + doOutput = true + setRequestProperty("Content-Type", "application/json") + setRequestProperty("Accept", "application/json") + setRequestProperty("Authorization", "Bearer $token") + setRequestProperty( + "X-Device-Serial", + BackendConfig.DEVICE_SERIAL + ) + } + + conn.outputStream.use { + it.write(envelope.toString().toByteArray(Charsets.UTF_8)) + } + + val status = conn.responseCode + + if (status in 200..299) { + Log.i(TAG, "TELEMETRY HTTPS OK: HTTP $status") + } else { + val errorBody = conn.errorStream + ?.bufferedReader() + ?.use { it.readText() } + .orEmpty() + + Log.e(TAG, "TELEMETRY HTTPS ERROR: HTTP $status $errorBody") + } + } catch (e: Exception) { + Log.e(TAG, "TELEMETRY HTTPS ERROR", e) + } finally { + conn?.disconnect() + } + } } fun uploadMedia(file: File, kind: String, metadata: JSONObject = JSONObject()) { diff --git a/app/src/main/kotlin/com/bodycamera/twentyfoulabs/ui/screens/MainViewModel.kt b/app/src/main/kotlin/com/bodycamera/twentyfoulabs/ui/screens/MainViewModel.kt index c70ec4c..212877a 100644 --- a/app/src/main/kotlin/com/bodycamera/twentyfoulabs/ui/screens/MainViewModel.kt +++ b/app/src/main/kotlin/com/bodycamera/twentyfoulabs/ui/screens/MainViewModel.kt @@ -143,7 +143,7 @@ private fun vibrateRecordingStopped() { var ticks = 0 while (true) { refreshDeviceStatus() - if (ticks % 3 == 0) deviceController.logTelemetry() + if (ticks > 0 && ticks % 60 == 0) deviceController.logTelemetry() ticks++ delay(5000) }