Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.ksp)
alias(libs.plugins.koin.compiler)
}

android {
Expand Down Expand Up @@ -37,6 +37,7 @@ android {
}
}


dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
Expand All @@ -56,11 +57,15 @@ dependencies {

// Koin
implementation(platform(libs.koin.bom))
implementation(libs.koin.core)
implementation(libs.koin.annotations)
implementation(libs.koin.android)
implementation(libs.koin.compose)
implementation(libs.koin.annotations)
ksp(libs.koin.compiler)

koinCompiler {
userLogs = true
compileSafety = true
}
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<application
android:name=".app.CanvaCompassApp"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/dev/jekis/canvacompass/ComposeViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package dev.jekis.canvacompass

import androidx.lifecycle.ViewModel
import org.koin.core.annotation.KoinViewModel

@KoinViewModel
class ComposeViewModel : ViewModel() {
// ViewModel logic for Compose Fragment
}
11 changes: 8 additions & 3 deletions app/src/main/java/dev/jekis/canvacompass/XmlFragment.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
package dev.jekis.canvacompass

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import dev.jekis.canvacompass.databinding.FragmentXmlBinding
import org.koin.androidx.viewmodel.ext.android.viewModel

private const val LISTENER_KEY = "XmlFragmentListenerKey"
class XmlFragment : Fragment() {

private var _binding: FragmentXmlBinding? = null
private val binding get() = _binding!!

private val viewModel: XmlViewModel by viewModels()
private val viewModel: XmlViewModel by viewModel()

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
Expand All @@ -30,6 +30,11 @@ class XmlFragment : Fragment() {
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
Expand Down
19 changes: 17 additions & 2 deletions app/src/main/java/dev/jekis/canvacompass/XmlViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
package dev.jekis.canvacompass

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.jekis.canvacompass.domain.GetCompassOrientationUseCase
import kotlinx.coroutines.launch
import org.koin.core.annotation.KoinViewModel

class XmlViewModel : ViewModel() {
// ViewModel logic for XML Fragment
@KoinViewModel
class XmlViewModel(
private val getCompassOrientation: GetCompassOrientationUseCase
) : ViewModel() {

init {
viewModelScope.launch {
getCompassOrientation.invoke().collect { state ->
Log.d("check_state", "$state")
}
}
}
}
16 changes: 16 additions & 0 deletions app/src/main/java/dev/jekis/canvacompass/app/CanvaCompassApp.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package dev.jekis.canvacompass.app

import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.core.annotation.KoinApplication
import org.koin.plugin.module.dsl.startKoin

@KoinApplication
class CanvaCompassApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin<CanvaCompassApp> {
androidContext(this@CanvaCompassApp)
}
}
}

This file was deleted.

120 changes: 120 additions & 0 deletions app/src/main/java/dev/jekis/canvacompass/data/SensorRepositoryImpl.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package dev.jekis.canvacompass.data

import android.hardware.SensorManager
import dev.jekis.canvacompass.data.datasource.sensors.AccelerometerSensor
import dev.jekis.canvacompass.data.datasource.sensors.MagnetometerSensor
import dev.jekis.canvacompass.data.datasource.sensors.RotationVectorSensor
import dev.jekis.canvacompass.domain.CompassOrientation
import dev.jekis.canvacompass.domain.SensorAccuracy
import dev.jekis.canvacompass.domain.SensorRepository
import dev.jekis.canvacompass.util.normalizeAzimuth
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.sample
import org.koin.core.annotation.Single

private const val DATA_INTERVAL = 40L
@Single
class SensorRepositoryImpl(
private val sensorManager: SensorManager
) : SensorRepository {
@OptIn(FlowPreview::class)
override fun fetchOrientationData(): Flow<CompassOrientation> {

val accelerometer = AccelerometerSensor(sensorManager)
val magnetometer = MagnetometerSensor(sensorManager)
val rotationVector = RotationVectorSensor(sensorManager)

val orientationFlow = if (rotationVector.isAvailable()) {
rotationVector.sensorState
.filter { it.values.isNotEmpty() }
.conflate()
.map { fuseFromRotationVector(it.values) }
} else {
combine(
accelerometer.sensorState.filter { it.values.isNotEmpty() },
magnetometer.sensorState.filter { it.values.isNotEmpty() }
) { accel, mag -> fuseFromAccelMag(accel.values, mag.values) }
.conflate()
}

return combine(
orientationFlow,
magnetometer.sensorState
) { orientation, magState ->
orientation.copy(
accuracy = mapAccuracy(magState.accuracy),
isCalibrated = (magState.accuracy
?: 0) >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM
)
}
.distinctUntilChanged { old, new ->
old.azimuth == new.azimuth &&
old.pitch == new.pitch &&
old.roll == new.roll &&
old.isCalibrated == new.isCalibrated
}
.sample(DATA_INTERVAL)
}

private fun fuseFromRotationVector(values: FloatArray): CompassOrientation {
val rotationMatrix = FloatArray(9)
val orientationAngles = FloatArray(3)

if (values.isNotEmpty()) {
SensorManager.getRotationMatrixFromVector(rotationMatrix, values)
}
SensorManager.getOrientation(rotationMatrix, orientationAngles)

return CompassOrientation(
azimuth = Math.toDegrees(orientationAngles[0].toDouble()).toFloat().normalizeAzimuth(),
trueAzimuth = null,
pitch = Math.toDegrees(orientationAngles[1].toDouble()).toFloat(),
roll = Math.toDegrees(orientationAngles[2].toDouble()).toFloat(),
accuracy = SensorAccuracy.UNRELIABLE,
magneticDeclination = 0f,
timestamp = System.currentTimeMillis(),
isCalibrated = false
)
}

private fun fuseFromAccelMag(
accelValues: FloatArray,
magValues: FloatArray
): CompassOrientation {
val rotationMatrix = FloatArray(9)
val orientationAngles = FloatArray(3)

val success = SensorManager.getRotationMatrix(rotationMatrix, null, accelValues, magValues)
if (!success) {
// getRotationMatrix возвращает false, если устройство в свободном падении
// или в near-magnetic-pole сингулярности — нужно решить, что возвращать в этом случае
}

SensorManager.getOrientation(rotationMatrix, orientationAngles)

return CompassOrientation(
azimuth = Math.toDegrees(orientationAngles[0].toDouble()).toFloat().normalizeAzimuth(),
trueAzimuth = null,
pitch = Math.toDegrees(orientationAngles[1].toDouble()).toFloat(),
roll = Math.toDegrees(orientationAngles[2].toDouble()).toFloat(),
accuracy = SensorAccuracy.UNRELIABLE,
magneticDeclination = 0f,
timestamp = System.currentTimeMillis(),
isCalibrated = false
)
}

private fun mapAccuracy(raw: Int?): SensorAccuracy = when (raw) {
SensorManager.SENSOR_STATUS_ACCURACY_HIGH -> SensorAccuracy.HIGH
SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM -> SensorAccuracy.MEDIUM
SensorManager.SENSOR_STATUS_ACCURACY_LOW -> SensorAccuracy.LOW
else -> SensorAccuracy.UNRELIABLE
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package dev.jekis.canvacompass.data.datasource.sensors

import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener2
import android.hardware.SensorManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

abstract class AbstractSensor(
protected val sensorManager: SensorManager,
private val sensorType: Int
) {
private val sensor: Sensor? = sensorManager.getDefaultSensor(sensorType)
private val _sensorState = MutableStateFlow(SensorState(name = sensor?.name))
val sensorState: StateFlow<SensorState> = _sensorState.asStateFlow()

private val sensorListener = object : SensorEventListener2 {
override fun onFlushCompleted(sensor: Sensor?) {
}

override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
_sensorState.update { state -> state.copy(accuracy = accuracy) }
}

override fun onSensorChanged(event: SensorEvent?) {
event?.let { event ->
_sensorState.update { state ->
state.copy(
values = event.values.clone(),
accuracy = event.accuracy,
timestamp = event.timestamp
)
}
}?: return
}
}

init {
startListening()
}

fun isAvailable(): Boolean = sensor != null

fun startListening() {
sensor?.let {
sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_UI)
}
}

fun stopListening() {
sensor?.let {
sensorManager.unregisterListener(sensorListener)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package dev.jekis.canvacompass.data.datasource.sensors

import android.hardware.Sensor
import android.hardware.SensorManager

/**
* Реализован датчик магнитного поля (магнитометр).
* Измеряет напряженность окружающего магнитного поля по трем осям.
* Используется для определения ориентации устройства относительно северного магнитного полюса.
*
* @param SensorManager - системный сервис для работы с датчиками Android.
*/
class AccelerometerSensor(sensorManager: SensorManager) :
AbstractSensor(sensorManager, Sensor.TYPE_ACCELEROMETER)
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package dev.jekis.canvacompass.data.datasource.sensors

import android.hardware.Sensor
import android.hardware.SensorManager
import org.koin.core.annotation.Singleton

/**
* Implementation of a magnetic field sensor (magnetometer).
* Measures the strength of the surrounding magnetic field along three axes.
* Used to determine the orientation of the device relative to magnetic north.
*
* @param SensorManager is a system service for working with Android sensors.
*/
@Singleton
class MagnetometerSensor(sensorManager: SensorManager) :
AbstractSensor(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package dev.jekis.canvacompass.data.datasource.sensors

import android.hardware.Sensor
import android.hardware.SensorManager

/**
* Implementation of the rotation vector sensor.
* Provides device orientation data as a result of the synthesis of several sensors
* (accelerometer, magnetometer, gyroscope). It is the most accurate way to determine orientation.
*
* @param SensorManager is a system service for working with Android sensors.
*/
class RotationVectorSensor(
sensorManager: SensorManager
): AbstractSensor(sensorManager, Sensor.TYPE_ROTATION_VECTOR)
Loading
Loading