AndroidAPS/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.kt

43 lines
1.8 KiB
Kotlin
Raw Normal View History

2020-03-31 20:22:32 +02:00
package info.nightscout.androidaps.receivers
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import dagger.android.DaggerBroadcastReceiver
import info.nightscout.androidaps.events.EventChargingState
2021-12-10 15:19:19 +01:00
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
2021-10-15 14:56:22 +02:00
import info.nightscout.androidaps.plugins.bus.RxBus
2020-03-31 20:22:32 +02:00
import javax.inject.Inject
class ChargingStateReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var aapsLogger: AAPSLogger
2021-10-15 14:56:22 +02:00
@Inject lateinit var rxBus: RxBus
2020-03-31 20:22:32 +02:00
@Inject lateinit var receiverStatusStore: ReceiverStatusStore
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
rxBus.send(grabChargingState(context))
2021-12-10 15:19:19 +01:00
aapsLogger.debug(
LTag.CORE, receiverStatusStore.lastChargingEvent?.toString()
2020-04-25 22:59:22 +02:00
?: "Unknown charging state")
2020-03-31 20:22:32 +02:00
}
private fun grabChargingState(context: Context): EventChargingState {
2020-04-25 22:59:22 +02:00
val batteryStatus = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
// Level
var batteryLevel = 0
val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
if (level != -1 && scale != -1)
batteryLevel = (level.toFloat() / scale.toFloat() * 100.0f).toInt()
// Status
2020-03-31 20:22:32 +02:00
val status: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING
|| status == BatteryManager.BATTERY_STATUS_FULL
2020-04-25 22:59:22 +02:00
return EventChargingState(isCharging, batteryLevel).also { receiverStatusStore.lastChargingEvent = it }
2020-03-31 20:22:32 +02:00
}
}