API 30 lints

This commit is contained in:
Milos Kozak 2021-08-11 18:10:44 +02:00
parent ff2b4f3427
commit 1c065c75e8
28 changed files with 160 additions and 127 deletions

View file

@ -226,7 +226,6 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
outState.putInt("rangeToDisplay", rangeToDisplay) outState.putInt("rangeToDisplay", rangeToDisplay)
outState.putLong("start", overviewData.fromTime) outState.putLong("start", overviewData.fromTime)
outState.putLong("end", overviewData.toTime) outState.putLong("end", overviewData.toTime)
} }
private fun prepareGraphsIfNeeded(numOfGraphs: Int) { private fun prepareGraphsIfNeeded(numOfGraphs: Int) {

View file

@ -11,6 +11,7 @@ import org.json.JSONObject
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.math.abs
@Singleton @Singleton
class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { class DefaultProfile @Inject constructor(val dateUtil: DateUtil) {
@ -120,12 +121,12 @@ class DefaultProfile @Inject constructor(val dateUtil: DateUtil) {
val high = map.ceilingEntry(key) val high = map.ceilingEntry(key)
var res: Array<Double>? = null var res: Array<Double>? = null
if (low != null && high != null) { if (low != null && high != null) {
res = if (Math.abs(key - low.key) < Math.abs(key - high.key)) res = if (abs(key - low.key) < abs(key - high.key))
low.value low.value
else else
high.value high.value
} else if (low != null || high != null) { } else if (low != null || high != null) {
res = if (low != null) low.value else high.value res = if (low != null) low.value else high!!.value
} }
return res return res
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.dialogs
import android.content.Context import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -62,7 +63,7 @@ class LoopDialog : DaggerDialogFragment() {
private var showOkCancel: Boolean = true private var showOkCancel: Boolean = true
private var _binding: DialogLoopBinding? = null private var _binding: DialogLoopBinding? = null
private var loopHandler = Handler() private var loopHandler = Handler(Looper.getMainLooper())
private lateinit var refreshDialog: Runnable private lateinit var refreshDialog: Runnable
// This property is only valid between onCreateView and // This property is only valid between onCreateView and

View file

@ -384,7 +384,7 @@ class WizardDialog : DaggerDialogFragment() {
it.commitAllowingStateLoss() it.commitAllowingStateLoss()
} }
} catch (e: IllegalStateException) { } catch (e: IllegalStateException) {
aapsLogger.debug(e.localizedMessage) aapsLogger.debug(e.localizedMessage ?: "")
} }
} }
} }

View file

@ -85,9 +85,8 @@ class MaintenancePlugin @Inject constructor(
} }
val exportDir = fileListProvider.ensureTempDirExists() val exportDir = fileListProvider.ensureTempDirExists()
if (exportDir.exists()) { if (exportDir.exists()) {
val expFiles = exportDir.listFiles() exportDir.listFiles()?.let { expFiles ->
for (file in expFiles) { for (file in expFiles) file.delete()
file.delete()
} }
exportDir.delete() exportDir.delete()
} }

View file

@ -64,7 +64,7 @@ class AutomationEvent(private val injector: HasAndroidInjector) {
.toString() .toString()
} }
fun fromJSON(data: String?): AutomationEvent { fun fromJSON(data: String): AutomationEvent {
val d = JSONObject(data) val d = JSONObject(data)
title = d.optString("title", "") title = d.optString("title", "")
isEnabled = d.optBoolean("enabled", true) isEnabled = d.optBoolean("enabled", true)

View file

@ -87,41 +87,41 @@ abstract class Trigger(val injector: HasAndroidInjector) {
//return (clazz.primaryConstructor?.call(injector) as Trigger).fromJSON(data?.toString() ?: "") //return (clazz.primaryConstructor?.call(injector) as Trigger).fromJSON(data?.toString() ?: "")
return when (type) { return when (type) {
TriggerAutosensValue::class.java.name, // backward compatibility TriggerAutosensValue::class.java.name, // backward compatibility
TriggerAutosensValue::class.java.simpleName -> TriggerAutosensValue(injector).fromJSON(data?.toString() ?: "") TriggerAutosensValue::class.java.simpleName -> TriggerAutosensValue(injector).fromJSON(data.toString())
TriggerBg::class.java.name, TriggerBg::class.java.name,
TriggerBg::class.java.simpleName -> TriggerBg(injector).fromJSON(data?.toString() ?: "") TriggerBg::class.java.simpleName -> TriggerBg(injector).fromJSON(data.toString())
TriggerBolusAgo::class.java.name, TriggerBolusAgo::class.java.name,
TriggerBolusAgo::class.java.simpleName -> TriggerBolusAgo(injector).fromJSON(data?.toString() ?: "") TriggerBolusAgo::class.java.simpleName -> TriggerBolusAgo(injector).fromJSON(data.toString())
TriggerBTDevice::class.java.name, TriggerBTDevice::class.java.name,
TriggerBTDevice::class.java.simpleName -> TriggerBTDevice(injector).fromJSON(data?.toString() ?: "") TriggerBTDevice::class.java.simpleName -> TriggerBTDevice(injector).fromJSON(data.toString())
TriggerIob::class.java.name, TriggerIob::class.java.name,
TriggerIob::class.java.simpleName -> TriggerIob(injector).fromJSON(data?.toString() ?: "") TriggerIob::class.java.simpleName -> TriggerIob(injector).fromJSON(data.toString())
TriggerCOB::class.java.name, TriggerCOB::class.java.name,
TriggerCOB::class.java.simpleName -> TriggerCOB(injector).fromJSON(data?.toString() ?: "") TriggerCOB::class.java.simpleName -> TriggerCOB(injector).fromJSON(data.toString())
TriggerConnector::class.java.name, TriggerConnector::class.java.name,
TriggerConnector::class.java.simpleName -> TriggerConnector(injector).fromJSON(data?.toString() ?: "") TriggerConnector::class.java.simpleName -> TriggerConnector(injector).fromJSON(data.toString())
TriggerDelta::class.java.name, TriggerDelta::class.java.name,
TriggerDelta::class.java.simpleName -> TriggerDelta(injector).fromJSON(data?.toString() ?: "") TriggerDelta::class.java.simpleName -> TriggerDelta(injector).fromJSON(data.toString())
TriggerDummy::class.java.name, TriggerDummy::class.java.name,
TriggerDummy::class.java.simpleName -> TriggerDummy(injector).fromJSON(data?.toString() ?: "") TriggerDummy::class.java.simpleName -> TriggerDummy(injector).fromJSON(data.toString())
TriggerIob::class.java.name, TriggerIob::class.java.name,
TriggerIob::class.java.simpleName -> TriggerIob(injector).fromJSON(data?.toString() ?: "") TriggerIob::class.java.simpleName -> TriggerIob(injector).fromJSON(data.toString())
TriggerLocation::class.java.name, TriggerLocation::class.java.name,
TriggerLocation::class.java.simpleName -> TriggerLocation(injector).fromJSON(data?.toString() ?: "") TriggerLocation::class.java.simpleName -> TriggerLocation(injector).fromJSON(data.toString())
TriggerProfilePercent::class.java.name, TriggerProfilePercent::class.java.name,
TriggerProfilePercent::class.java.simpleName -> TriggerProfilePercent(injector).fromJSON(data?.toString() ?: "") TriggerProfilePercent::class.java.simpleName -> TriggerProfilePercent(injector).fromJSON(data.toString())
TriggerPumpLastConnection::class.java.name, TriggerPumpLastConnection::class.java.name,
TriggerPumpLastConnection::class.java.simpleName -> TriggerPumpLastConnection(injector).fromJSON(data?.toString() ?: "") TriggerPumpLastConnection::class.java.simpleName -> TriggerPumpLastConnection(injector).fromJSON(data.toString())
TriggerRecurringTime::class.java.name, TriggerRecurringTime::class.java.name,
TriggerRecurringTime::class.java.simpleName -> TriggerRecurringTime(injector).fromJSON(data?.toString() ?: "") TriggerRecurringTime::class.java.simpleName -> TriggerRecurringTime(injector).fromJSON(data.toString())
TriggerTempTarget::class.java.name, TriggerTempTarget::class.java.name,
TriggerTempTarget::class.java.simpleName -> TriggerTempTarget(injector).fromJSON(data?.toString() ?: "") TriggerTempTarget::class.java.simpleName -> TriggerTempTarget(injector).fromJSON(data.toString())
TriggerTime::class.java.name, TriggerTime::class.java.name,
TriggerTime::class.java.simpleName -> TriggerTime(injector).fromJSON(data?.toString() ?: "") TriggerTime::class.java.simpleName -> TriggerTime(injector).fromJSON(data.toString())
TriggerTimeRange::class.java.name, TriggerTimeRange::class.java.name,
TriggerTimeRange::class.java.simpleName -> TriggerTimeRange(injector).fromJSON(data?.toString() ?: "") TriggerTimeRange::class.java.simpleName -> TriggerTimeRange(injector).fromJSON(data.toString())
TriggerWifiSsid::class.java.name, TriggerWifiSsid::class.java.name,
TriggerWifiSsid::class.java.simpleName -> TriggerWifiSsid(injector).fromJSON(data?.toString() ?: "") TriggerWifiSsid::class.java.simpleName -> TriggerWifiSsid(injector).fromJSON(data.toString())
else -> throw ClassNotFoundException(type) else -> throw ClassNotFoundException(type)
} }
} }

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.di package info.nightscout.androidaps.di
import android.content.Context import android.content.Context
import android.preference.PreferenceManager import androidx.preference.PreferenceManager
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger

View file

@ -40,7 +40,10 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
} }
override fun onSaveInstanceState(savedInstanceState: Bundle) { override fun onSaveInstanceState(savedInstanceState: Bundle) {
@ -67,7 +70,8 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
eventTimeView?.text = dateUtil.timeString(eventTime) eventTimeView?.text = dateUtil.timeString(eventTime)
// create an OnDateSetListener // create an OnDateSetListener
val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> val dateSetListener =
DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
val cal = Calendar.getInstance() val cal = Calendar.getInstance()
cal.timeInMillis = eventTime cal.timeInMillis = eventTime
cal.set(Calendar.YEAR, year) cal.set(Calendar.YEAR, year)
@ -82,7 +86,8 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
context?.let { context?.let {
val cal = Calendar.getInstance() val cal = Calendar.getInstance()
cal.timeInMillis = eventTime cal.timeInMillis = eventTime
DatePickerDialog(it, dateSetListener, DatePickerDialog(
it, dateSetListener,
cal.get(Calendar.YEAR), cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH) cal.get(Calendar.DAY_OF_MONTH)
@ -96,7 +101,10 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
cal.timeInMillis = eventTime cal.timeInMillis = eventTime
cal.set(Calendar.HOUR_OF_DAY, hour) cal.set(Calendar.HOUR_OF_DAY, hour)
cal.set(Calendar.MINUTE, minute) cal.set(Calendar.MINUTE, minute)
cal.set(Calendar.SECOND, seconds++) // randomize seconds to prevent creating record of the same time, if user choose time manually cal.set(
Calendar.SECOND,
seconds++
) // randomize seconds to prevent creating record of the same time, if user choose time manually
eventTime = cal.timeInMillis eventTime = cal.timeInMillis
eventTimeChanged = true eventTimeChanged = true
eventTimeView?.text = dateUtil.timeString(eventTime) eventTimeView?.text = dateUtil.timeString(eventTime)
@ -106,7 +114,8 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
context?.let { context?.let {
val cal = Calendar.getInstance() val cal = Calendar.getInstance()
cal.timeInMillis = eventTime cal.timeInMillis = eventTime
TimePickerDialog(it, timeSetListener, TimePickerDialog(
it, timeSetListener,
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), cal.get(Calendar.MINUTE),
DateFormat.is24HourFormat(context) DateFormat.is24HourFormat(context)
@ -114,7 +123,8 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
} }
} }
(view.findViewById(R.id.notes_layout) as View?)?.visibility = sp.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility() (view.findViewById(R.id.notes_layout) as View?)?.visibility =
sp.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility()
(view.findViewById(R.id.ok) as Button?)?.setOnClickListener { (view.findViewById(R.id.ok) as Button?)?.setOnClickListener {
synchronized(okClicked) { synchronized(okClicked) {
@ -137,7 +147,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
it.commitAllowingStateLoss() it.commitAllowingStateLoss()
} }
} catch (e: IllegalStateException) { } catch (e: IllegalStateException) {
aapsLogger.debug(e.localizedMessage) aapsLogger.debug(e.localizedMessage ?: "")
} }
} }

View file

@ -1,7 +1,9 @@
package info.nightscout.androidaps.dialogs package info.nightscout.androidaps.dialogs
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -24,13 +26,14 @@ class ErrorDialog : DaggerDialogFragment() {
@Inject lateinit var alarmSoundServiceHelper: AlarmSoundServiceHelper @Inject lateinit var alarmSoundServiceHelper: AlarmSoundServiceHelper
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var ctx: Context
var helperActivity: ErrorHelperActivity? = null var helperActivity: ErrorHelperActivity? = null
var status: String = "" var status: String = ""
var title: String = "" var title: String = ""
var sound: Int = 0 var sound: Int = 0
private var loopHandler = Handler() private var loopHandler = Handler(Looper.getMainLooper())
private var _binding: DialogErrorBinding? = null private var _binding: DialogErrorBinding? = null
@ -106,9 +109,9 @@ class ErrorDialog : DaggerDialogFragment() {
private fun startAlarm() { private fun startAlarm() {
if (sound != 0) if (sound != 0)
context?.let { context -> alarmSoundServiceHelper.startAlarm(context, sound) } alarmSoundServiceHelper.startAlarm(ctx, sound)
} }
private fun stopAlarm() = private fun stopAlarm() =
context?.let { context -> alarmSoundServiceHelper.stopService(context) } alarmSoundServiceHelper.stopService(ctx)
} }

View file

@ -16,14 +16,14 @@ fun DeviceStatus.toJson(dateUtil: DateUtil): JSONObject =
.put("created_at", dateUtil.toISOString(timestamp)) .put("created_at", dateUtil.toISOString(timestamp))
.also { .also {
if (device != null) it.put("device", device) if (device != null) it.put("device", device)
if (pump != null) it.put("pump", JSONObject(pump)) pump?.let { pump -> it.put("pump", JSONObject(pump)) }
it.put("openaps", JSONObject().also { openaps -> it.put("openaps", JSONObject().also { openaps ->
if (enacted != null) openaps.put("enacted", JSONObject(enacted)) enacted?.let { enacted -> openaps.put("enacted", JSONObject(enacted)) }
if (suggested != null) openaps.put("suggested", JSONObject(suggested)) suggested?.let { suggested -> openaps.put("suggested", JSONObject(suggested)) }
if (iob != null) openaps.put("iob", JSONObject(iob)) iob?.let { iob -> openaps.put("iob", JSONObject(iob)) }
}) })
if (uploaderBattery != 0) it.put("uploaderBattery", uploaderBattery) if (uploaderBattery != 0) it.put("uploaderBattery", uploaderBattery)
if (configuration != null) it.put("configuration", JSONObject(configuration)) configuration?.let { configuration -> it.put("configuration", JSONObject(configuration)) }
} }
fun buildDeviceStatus( fun buildDeviceStatus(

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.constraints.versionChecker package info.nightscout.androidaps.plugins.constraints.versionChecker
import android.content.Context import android.content.Context
import android.net.ConnectivityManager
import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -9,6 +8,7 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.io.IOException import java.io.IOException
@ -24,24 +24,28 @@ class VersionCheckerUtils @Inject constructor(
val resourceHelper: ResourceHelper, val resourceHelper: ResourceHelper,
val rxBus: RxBusWrapper, val rxBus: RxBusWrapper,
private val config: Config, private val config: Config,
val context: Context val context: Context,
val receiverStatusStore: ReceiverStatusStore
) { ) {
// check network connection fun isConnected(): Boolean = receiverStatusStore.isConnected
fun isConnected(): Boolean {
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connMgr.activeNetworkInfo?.isConnected ?: false
}
fun triggerCheckVersion() { fun triggerCheckVersion() {
if (!sp.contains(R.string.key_last_time_this_version_detected)) { if (!sp.contains(R.string.key_last_time_this_version_detected)) {
// On a new installation, set it as 30 days old in order to warn that there is a new version. // On a new installation, set it as 30 days old in order to warn that there is a new version.
sp.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)) sp.putLong(
R.string.key_last_time_this_version_detected,
System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)
)
} }
// If we are good, only check once every day. // If we are good, only check once every day.
if (System.currentTimeMillis() > sp.getLong(R.string.key_last_time_this_version_detected, 0) + CHECK_EVERY) { if (System.currentTimeMillis() > sp.getLong(
R.string.key_last_time_this_version_detected,
0
) + CHECK_EVERY
) {
checkVersion() checkVersion()
} }
} }
@ -49,7 +53,8 @@ class VersionCheckerUtils @Inject constructor(
private fun checkVersion() = if (isConnected()) { private fun checkVersion() = if (isConnected()) {
Thread { Thread {
try { try {
val version: String? = findVersion(URL("https://raw.githubusercontent.com/nightscout/AndroidAPS/master/app/build.gradle").readText()) val version: String? =
findVersion(URL("https://raw.githubusercontent.com/nightscout/AndroidAPS/master/app/build.gradle").readText())
compareWithCurrentVersion(version, config.VERSION_NAME) compareWithCurrentVersion(version, config.VERSION_NAME)
} catch (e: IOException) { } catch (e: IOException) {
aapsLogger.error(LTag.CORE, "Github master version check error: $e") aapsLogger.error(LTag.CORE, "Github master version check error: $e")
@ -107,7 +112,11 @@ class VersionCheckerUtils @Inject constructor(
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) { if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
aapsLogger.debug(LTag.CORE, "Version $currentVersion outdated. Found $newVersion") aapsLogger.debug(LTag.CORE, "Version $currentVersion outdated. Found $newVersion")
val notification = Notification(Notification.NEW_VERSION_DETECTED, resourceHelper.gs(R.string.versionavailable, newVersion.toString()), Notification.LOW) val notification = Notification(
Notification.NEW_VERSION_DETECTED,
resourceHelper.gs(R.string.versionavailable, newVersion.toString()),
Notification.LOW
)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
sp.putLong(R.string.key_last_versionchecker_warning, now) sp.putLong(R.string.key_last_versionchecker_warning, now)
} }
@ -126,7 +135,8 @@ class VersionCheckerUtils @Inject constructor(
fun findVersion(file: String?): String? { fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex() val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull() return file?.lines()?.filter { regex.matches(it) }
?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
} }
companion object { companion object {
@ -142,10 +152,14 @@ fun String.numericVersionPart(): String =
@Suppress("unused") fun findVersion(file: String?): String? { @Suppress("unused") fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex() val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull() return file?.lines()?.filter { regex.matches(it) }
?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
} }
@Deprecated(replaceWith = ReplaceWith("numericVersionPart()"), message = "Will not work if RCs have another index number in it.") @Deprecated(
replaceWith = ReplaceWith("numericVersionPart()"),
message = "Will not work if RCs have another index number in it."
)
fun String.versionStrip() = this.mapNotNull { fun String.versionStrip() = this.mapNotNull {
when (it) { when (it) {
in '0'..'9' -> it in '0'..'9' -> it

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.general.maintenance package info.nightscout.androidaps.plugins.general.maintenance
import android.content.Context
import android.os.Environment import android.os.Environment
import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.Config
@ -25,7 +26,8 @@ class PrefFileListProvider @Inject constructor(
private val classicPrefsFormat: ClassicPrefsFormat, private val classicPrefsFormat: ClassicPrefsFormat,
private val encryptedPrefsFormat: EncryptedPrefsFormat, private val encryptedPrefsFormat: EncryptedPrefsFormat,
private val storage: Storage, private val storage: Storage,
private val versionCheckerUtils: VersionCheckerUtils private val versionCheckerUtils: VersionCheckerUtils,
context: Context
) { ) {
private val path = File(Environment.getExternalStorageDirectory().toString()) private val path = File(Environment.getExternalStorageDirectory().toString())

View file

@ -81,7 +81,7 @@ class PrefImportListActivity : DaggerAppCompatActivity() {
filelistName.text = prefFile.file.name filelistName.text = prefFile.file.name
filelistName.tag = prefFile filelistName.tag = prefFile
filelistDir.text = resourceHelper.gs(R.string.in_directory, prefFile.file.parentFile.absolutePath) filelistDir.text = resourceHelper.gs(R.string.in_directory, prefFile.file.parentFile?.absolutePath)
val visible = (prefFile.handler != PrefsFormatsHandler.CLASSIC).toVisibility() val visible = (prefFile.handler != PrefsFormatsHandler.CLASSIC).toVisibility()
metalineName.visibility = visible metalineName.visibility = visible

View file

@ -25,7 +25,7 @@ class NetworkChangeReceiver : DaggerBroadcastReceiver() {
rxBus.send(grabNetworkStatus(context, aapsLogger)) rxBus.send(grabNetworkStatus(context, aapsLogger))
} }
fun grabNetworkStatus(context: Context, aapsLogger: AAPSLogger): EventNetworkChange { private fun grabNetworkStatus(context: Context, aapsLogger: AAPSLogger): EventNetworkChange {
val event = EventNetworkChange() val event = EventNetworkChange()
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networks: Array<Network> = cm.allNetworks val networks: Array<Network> = cm.allNetworks

View file

@ -7,6 +7,7 @@ import android.media.MediaPlayer
import android.os.Binder import android.os.Binder
import android.os.Handler import android.os.Handler
import android.os.IBinder import android.os.IBinder
import android.os.Looper
import dagger.android.DaggerService import dagger.android.DaggerService
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.R
@ -37,7 +38,7 @@ class AlarmSoundService : DaggerService() {
private const val VOLUME_INCREASE_MIN_DELAY_MILLIS = 2_000L // Minimum delay between volume increments private const val VOLUME_INCREASE_MIN_DELAY_MILLIS = 2_000L // Minimum delay between volume increments
/* /*
* Delay until the next volumen increment will be the lowest value of VOLUME_INCREASE_MIN_DELAY_MILLIS and * Delay until the next volume increment will be the lowest value of VOLUME_INCREASE_MIN_DELAY_MILLIS and
* VOLUME_INCREASE_BASE_DELAY_MILLIS - (currentVolumeLevel - 1) ^ VOLUME_INCREASE_DELAY_DECREMENT_EXPONENT * 1000 * VOLUME_INCREASE_BASE_DELAY_MILLIS - (currentVolumeLevel - 1) ^ VOLUME_INCREASE_DELAY_DECREMENT_EXPONENT * 1000
* *
*/ */
@ -53,7 +54,7 @@ class AlarmSoundService : DaggerService() {
private val binder = LocalBinder() private val binder = LocalBinder()
override fun onBind(intent: Intent): IBinder = binder override fun onBind(intent: Intent): IBinder = binder
private val increaseVolumeHandler = Handler() private val increaseVolumeHandler = Handler(Looper.getMainLooper())
private var currentVolumeLevel = 0 private var currentVolumeLevel = 0
override fun onCreate() { override fun onCreate() {

View file

@ -17,6 +17,7 @@ import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@Suppress("SpellCheckingInspection")
@Singleton @Singleton
class CryptoUtil @Inject constructor( class CryptoUtil @Inject constructor(
val aapsLogger: AAPSLogger val aapsLogger: AAPSLogger
@ -39,7 +40,7 @@ class CryptoUtil @Inject constructor(
return hashRaw.toHex() return hashRaw.toHex()
} }
fun hmac256(str: String, secret: String): String? { fun hmac256(str: String, secret: String): String {
val sha256HMAC = Mac.getInstance("HmacSHA256") val sha256HMAC = Mac.getInstance("HmacSHA256")
val secretKey = SecretKeySpec(secret.toByteArray(), "HmacSHA256") val secretKey = SecretKeySpec(secret.toByteArray(), "HmacSHA256")
sha256HMAC.init(secretKey) sha256HMAC.init(secretKey)
@ -68,7 +69,7 @@ class CryptoUtil @Inject constructor(
secureRandom.nextBytes(iv) secureRandom.nextBytes(iv)
val cipherEnc: Cipher = Cipher.getInstance("AES/GCM/NoPadding") val cipherEnc: Cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipherEnc.init(Cipher.ENCRYPT_MODE, prepCipherKey(passPhrase, salt), GCMParameterSpec(TAG_LENGTH_BIT, iv)) cipherEnc.init(Cipher.ENCRYPT_MODE, prepCipherKey(passPhrase, salt), GCMParameterSpec(TAG_LENGTH_BIT, iv))
encrypted = cipherEnc.doFinal(rawData.toByteArray()) encrypted = cipherEnc.doFinal(rawData.toByteArray()) ?: return null
val byteBuffer: ByteBuffer = ByteBuffer.allocate(1 + iv.size + encrypted.size) val byteBuffer: ByteBuffer = ByteBuffer.allocate(1 + iv.size + encrypted.size)
byteBuffer.put(iv.size.toByte()) byteBuffer.put(iv.size.toByte())
byteBuffer.put(iv) byteBuffer.put(iv)

View file

@ -9,25 +9,26 @@ import com.google.android.material.textfield.TextInputLayout
import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.utils.textValidator.validators.* import info.nightscout.androidaps.utils.textValidator.validators.*
@Suppress("SpellCheckingInspection")
class DefaultEditTextValidator : EditTextValidator { class DefaultEditTextValidator : EditTextValidator {
protected var mValidator: MultiValidator? = null private var mValidator: MultiValidator? = null
protected var testErrorString: String? = null private var testErrorString: String? = null
protected var emptyAllowed = false private var emptyAllowed = false
protected lateinit var editTextView: EditText private lateinit var editTextView: EditText
private var tw: TextWatcher? = null private var tw: TextWatcher? = null
private var defaultEmptyErrorString: String? = null private var defaultEmptyErrorString: String? = null
protected var testType: Int private var testType: Int
protected var classType: String? = null private var classType: String? = null
protected var customRegexp: String? = null private var customRegexp: String? = null
protected var customFormat: String? = null private var customFormat: String? = null
protected var emptyErrorStringActual: String? = null private var emptyErrorStringActual: String? = null
protected var emptyErrorStringDef: String? = null private var emptyErrorStringDef: String? = null
protected var minLength = 0 private var minLength = 0
protected var minNumber = 0 private var minNumber = 0
protected var maxNumber = 0 private var maxNumber = 0
protected var floatminNumber = 0f private var floatminNumber = 0f
protected var floatmaxNumber = 0f private var floatmaxNumber = 0f
@Suppress("unused") @Suppress("unused")
constructor(editTextView: EditText, context: Context) { constructor(editTextView: EditText, context: Context) {
@ -56,8 +57,7 @@ class DefaultEditTextValidator : EditTextValidator {
@Throws(IllegalArgumentException::class) @Throws(IllegalArgumentException::class)
override fun addValidator(theValidator: Validator) { override fun addValidator(theValidator: Validator) {
requireNotNull(theValidator) { "theValidator argument should not be null" } mValidator?.enqueue(theValidator)
mValidator!!.enqueue(theValidator)
} }
private fun setEditText(editText: EditText) { private fun setEditText(editText: EditText) {
@ -105,9 +105,9 @@ class DefaultEditTextValidator : EditTextValidator {
EditTextValidator.TEST_ALPHANUMERIC -> toAdd = AlphaNumericValidator( EditTextValidator.TEST_ALPHANUMERIC -> toAdd = AlphaNumericValidator(
if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_this_field_cannot_contain_special_character) else testErrorString) if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_this_field_cannot_contain_special_character) else testErrorString)
EditTextValidator.TEST_NUMERIC -> toAdd = NumericValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_allowed) else testErrorString) EditTextValidator.TEST_NUMERIC -> toAdd = NumericValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_allowed) else testErrorString)
EditTextValidator.TEST_NUMERIC_RANGE -> toAdd = NumericRangeValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_range_allowed, Integer.toString(minNumber), Integer.toString(maxNumber)) else testErrorString, minNumber, maxNumber) EditTextValidator.TEST_NUMERIC_RANGE -> toAdd = NumericRangeValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_range_allowed, minNumber.toString(), maxNumber.toString()) else testErrorString, minNumber, maxNumber)
EditTextValidator.TEST_FLOAT_NUMERIC_RANGE -> toAdd = FloatNumericRangeValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_range_allowed, java.lang.Float.toString(floatminNumber), java.lang.Float.toString(floatmaxNumber)) else testErrorString, floatminNumber, floatmaxNumber) EditTextValidator.TEST_FLOAT_NUMERIC_RANGE -> toAdd = FloatNumericRangeValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_range_allowed, floatminNumber.toString(), floatmaxNumber.toString()) else testErrorString, floatminNumber, floatmaxNumber)
EditTextValidator.TEST_REGEXP -> toAdd = RegexpValidator(testErrorString, customRegexp) EditTextValidator.TEST_REGEXP -> toAdd = RegexpValidator(testErrorString, customRegexp ?: "")
EditTextValidator.TEST_CREDITCARD -> toAdd = CreditCardValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_creditcard_number_not_valid) else testErrorString) EditTextValidator.TEST_CREDITCARD -> toAdd = CreditCardValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_creditcard_number_not_valid) else testErrorString)
EditTextValidator.TEST_EMAIL -> toAdd = EmailValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_email_address_not_valid) else testErrorString) EditTextValidator.TEST_EMAIL -> toAdd = EmailValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_email_address_not_valid) else testErrorString)
EditTextValidator.TEST_PHONE -> toAdd = PhoneValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_phone_not_valid) else testErrorString) EditTextValidator.TEST_PHONE -> toAdd = PhoneValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_phone_not_valid) else testErrorString)
@ -185,7 +185,7 @@ class DefaultEditTextValidator : EditTextValidator {
return this return this
} }
fun setEmptyErrorString(emptyErrorString: String?): DefaultEditTextValidator { private fun setEmptyErrorString(emptyErrorString: String?): DefaultEditTextValidator {
emptyErrorStringActual = if (!TextUtils.isEmpty(emptyErrorString)) { emptyErrorStringActual = if (!TextUtils.isEmpty(emptyErrorString)) {
emptyErrorString emptyErrorString
} else { } else {
@ -243,6 +243,7 @@ class DefaultEditTextValidator : EditTextValidator {
!TextUtils.isEmpty(editTextView.error) !TextUtils.isEmpty(editTextView.error)
} }
@Suppress("SpellCheckingInspection")
data class Parameters( data class Parameters(
val testErrorString: String? = null, val testErrorString: String? = null,
val emptyAllowed: Boolean = false, val emptyAllowed: Boolean = false,

View file

@ -7,4 +7,4 @@ import java.util.regex.Pattern
* *
* @author Andrea Baccega <me></me>@andreabaccega.com> * @author Andrea Baccega <me></me>@andreabaccega.com>
*/ */
open class RegexpValidator(message: String?, _regexp: String?) : PatternValidator(message, Pattern.compile(_regexp)) open class RegexpValidator(message: String?, _regexp: String) : PatternValidator(message, Pattern.compile(_regexp))

View file

@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -61,7 +62,7 @@ class DanaFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler() private val loopHandler = Handler(Looper.getMainLooper())
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private var _binding: DanarFragmentBinding? = null private var _binding: DanarFragmentBinding? = null

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.danar.comm
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import java.util.*
class MsgSettingUserOptions( class MsgSettingUserOptions(
injector: HasAndroidInjector injector: HasAndroidInjector
@ -16,7 +15,7 @@ class MsgSettingUserOptions(
override fun handleMessage(packet: ByteArray) { override fun handleMessage(packet: ByteArray) {
val bytes = getDataBytes(packet, packet.size - 10) val bytes = getDataBytes(packet, packet.size - 10)
danaPump.userOptionsFrompump = Arrays.copyOf(bytes, bytes!!.size) // saving pumpDataBytes to use it in MsgSetUserOptions danaPump.userOptionsFrompump = bytes.copyOf(bytes.size) // saving pumpDataBytes to use it in MsgSetUserOptions
for (pos in bytes.indices) { for (pos in bytes.indices) {
aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos]) aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos])
} }
@ -46,10 +45,7 @@ class MsgSettingUserOptions(
aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaPump.lowReservoirRate) aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaPump.lowReservoirRate)
} }
private fun getDataBytes(bytes: ByteArray?, len: Int): ByteArray? { private fun getDataBytes(bytes: ByteArray, len: Int): ByteArray {
if (bytes == null) {
return null
}
val ret = ByteArray(len) val ret = ByteArray(len)
System.arraycopy(bytes, 6, ret, 0, len) System.arraycopy(bytes, 6, ret, 0, len)
return ret return ret

View file

@ -9,6 +9,7 @@ import android.bluetooth.le.ScanResult
import android.content.pm.ActivityInfo import android.content.pm.ActivityInfo
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.BaseAdapter import android.widget.BaseAdapter
@ -87,7 +88,7 @@ class BLEScanActivity : NoSplashAppCompatActivity() {
return return
} }
devices.add(item) devices.add(item)
Handler().post { listAdapter!!.notifyDataSetChanged() } Handler(Looper.getMainLooper()).post { listAdapter?.notifyDataSetChanged() }
} }
private val mBleScanCallback: ScanCallback = object : ScanCallback() { private val mBleScanCallback: ScanCallback = object : ScanCallback() {
@ -172,7 +173,7 @@ class BLEScanActivity : NoSplashAppCompatActivity() {
override fun hashCode(): Int = device.hashCode() override fun hashCode(): Int = device.hashCode()
} }
private fun isSNCheck(sn: String?): Boolean { private fun isSNCheck(sn: String): Boolean {
val regex = "^([a-zA-Z]{3})([0-9]{5})([a-zA-Z]{2})$" val regex = "^([a-zA-Z]{3})([0-9]{5})([a-zA-Z]{2})$"
val p = Pattern.compile(regex) val p = Pattern.compile(regex)
val m = p.matcher(sn) val m = p.matcher(sn)

View file

@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -48,7 +49,7 @@ class DiaconnG8Fragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler() private val loopHandler = Handler(Looper.getMainLooper())
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private var _binding: DiaconnG8FragmentBinding? = null private var _binding: DiaconnG8FragmentBinding? = null

View file

@ -11,6 +11,7 @@ import android.bluetooth.le.ScanSettings
import android.content.pm.ActivityInfo import android.content.pm.ActivityInfo
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.os.ParcelUuid import android.os.ParcelUuid
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -72,10 +73,10 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
private fun startScan() = private fun startScan() =
try { try {
val filters: MutableList<ScanFilter> = ArrayList() val filters: MutableList<ScanFilter> = ArrayList()
val scan_filter = ScanFilter.Builder() val scanFilter = ScanFilter.Builder()
.setServiceUuid(ParcelUuid(serviceUUID)) .setServiceUuid(ParcelUuid(serviceUUID))
.build() .build()
filters.add(scan_filter) filters.add(scanFilter)
val settings = ScanSettings.Builder() val settings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
@ -100,7 +101,7 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
return return
} }
devices.add(item) devices.add(item)
Handler().post { listAdapter!!.notifyDataSetChanged() } Handler(Looper.getMainLooper()).post { listAdapter?.notifyDataSetChanged() }
} }
private val mBleScanCallback: ScanCallback = object : ScanCallback() { private val mBleScanCallback: ScanCallback = object : ScanCallback() {

View file

@ -5,6 +5,7 @@ import android.content.Intent
import android.graphics.Color import android.graphics.Color
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -67,7 +68,7 @@ class MedtronicFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler() private val loopHandler = Handler(Looper.getMainLooper())
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
init { init {
@ -98,7 +99,7 @@ class MedtronicFragment : DaggerFragment() {
binding.pumpStatusIcon.text = "{fa-bed}" binding.pumpStatusIcon.text = "{fa-bed}"
binding.history.setOnClickListener { binding.history.setOnClickListener {
if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration() == true) { if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration()) {
startActivity(Intent(context, MedtronicHistoryActivity::class.java)) startActivity(Intent(context, MedtronicHistoryActivity::class.java))
} else { } else {
displayNotConfiguredDialog() displayNotConfiguredDialog()
@ -106,7 +107,7 @@ class MedtronicFragment : DaggerFragment() {
} }
binding.refresh.setOnClickListener { binding.refresh.setOnClickListener {
if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration() != true) { if (!medtronicPumpPlugin.rileyLinkService.verifyConfiguration()) {
displayNotConfiguredDialog() displayNotConfiguredDialog()
} else { } else {
binding.refresh.isEnabled = false binding.refresh.isEnabled = false
@ -120,7 +121,7 @@ class MedtronicFragment : DaggerFragment() {
} }
binding.stats.setOnClickListener { binding.stats.setOnClickListener {
if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration() == true) { if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration()) {
startActivity(Intent(context, RileyLinkStatusActivity::class.java)) startActivity(Intent(context, RileyLinkStatusActivity::class.java))
} else { } else {
displayNotConfiguredDialog() displayNotConfiguredDialog()

View file

@ -5,6 +5,7 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType
import kotlin.math.min
/** /**
* Created by geoff on 5/29/16. * Created by geoff on 5/29/16.
@ -15,7 +16,7 @@ class PumpMessage : RLMessage {
private var packetType: PacketType? = PacketType.Carelink private var packetType: PacketType? = PacketType.Carelink
var address: ByteArray? = byteArrayOf(0, 0, 0) var address: ByteArray? = byteArrayOf(0, 0, 0)
var commandType: MedtronicCommandType? = null var commandType: MedtronicCommandType? = null
var invalidCommandType: Byte? = null private var invalidCommandType: Byte? = null
var messageBody: MessageBody? = MessageBody() var messageBody: MessageBody? = MessageBody()
var error: String? = null var error: String? = null
@ -33,7 +34,7 @@ class PumpMessage : RLMessage {
this.aapsLogger = aapsLogger this.aapsLogger = aapsLogger
} }
val isErrorResponse: Boolean @Suppress("unused") val isErrorResponse: Boolean
get() = error != null get() = error != null
fun init(packetType: PacketType?, address: ByteArray?, commandType: MedtronicCommandType?, messageBody: MessageBody?) { fun init(packetType: PacketType?, address: ByteArray?, commandType: MedtronicCommandType?, messageBody: MessageBody?) {
@ -47,7 +48,7 @@ class PumpMessage : RLMessage {
if (rxData == null) { if (rxData == null) {
return return
} }
if (rxData.size > 0) { if (rxData.isNotEmpty()) {
packetType = PacketType.getByValue(rxData[0].toShort()) packetType = PacketType.getByValue(rxData[0].toShort())
} }
if (rxData.size > 3) { if (rxData.size > 3) {
@ -87,7 +88,7 @@ class PumpMessage : RLMessage {
// rawContent = just response without code (contents-2, messageBody.txData-1); // rawContent = just response without code (contents-2, messageBody.txData-1);
val rawContent: ByteArray val rawContent: ByteArray
get() { get() {
if (messageBody == null || messageBody!!.txData == null || messageBody!!.txData!!.size == 0) return byteArrayOf() if (messageBody == null || messageBody!!.txData == null || messageBody?.txData?.size == 0) return byteArrayOf()
val data = messageBody!!.txData val data = messageBody!!.txData
var length = ByteUtil.asUINT8(data!![0]) // length is not always correct so, we check whole array if we have var length = ByteUtil.asUINT8(data!![0]) // length is not always correct so, we check whole array if we have
// data, after length // data, after length
@ -109,7 +110,9 @@ class PumpMessage : RLMessage {
length = data.size - 1 length = data.size - 1
} }
val arrayOut = ByteArray(length) val arrayOut = ByteArray(length)
System.arraycopy(messageBody!!.txData, 1, arrayOut, 0, length) messageBody?.txData?.let {
System.arraycopy(it, 1, arrayOut, 0, length)
}
// if (isLogEnabled()) // if (isLogEnabled())
// LOG.debug("PumpMessage - Length: " + length + ", Original Length: " + originalLength + ", CommandType: " // LOG.debug("PumpMessage - Length: " + length + ", Original Length: " + originalLength + ", CommandType: "
@ -120,10 +123,10 @@ class PumpMessage : RLMessage {
val rawContentOfFrame: ByteArray val rawContentOfFrame: ByteArray
get() { get() {
val raw = messageBody!!.txData val raw = messageBody!!.txData
return if (raw == null || raw.size == 0) { return if (raw == null || raw.isEmpty()) {
byteArrayOf() byteArrayOf()
} else { } else {
ByteUtil.substring(raw, 1, Math.min(FRAME_DATA_LENGTH, raw.size - 1)) ByteUtil.substring(raw, 1, min(FRAME_DATA_LENGTH, raw.size - 1))
} }
} }

View file

@ -143,10 +143,7 @@ class MedtronicUIPostprocessor @Inject constructor(
} }
private fun postProcessSettings(uiTask: MedtronicUITask) { private fun postProcessSettings(uiTask: MedtronicUITask) {
val settings = uiTask.result as? Map<String, PumpSettingDTO> val settings = uiTask.result as? Map<String, PumpSettingDTO> ?: return
if (settings == null)
return
medtronicUtil.settings = settings medtronicUtil.settings = settings
var checkValue: PumpSettingDTO var checkValue: PumpSettingDTO

View file

@ -44,7 +44,7 @@ class PumpSyncStorage @Inject constructor(
if (sp.contains(pumpSyncStorageKey)) { if (sp.contains(pumpSyncStorageKey)) {
val jsonData: String = sp.getString(pumpSyncStorageKey, ""); val jsonData: String = sp.getString(pumpSyncStorageKey, "");
if (!jsonData.isBlank()) { if (jsonData.isNotBlank()) {
pumpSyncStorage = xstream.fromXML(jsonData, MutableMap::class.java) as MutableMap<String, MutableList<PumpDbEntry>> pumpSyncStorage = xstream.fromXML(jsonData, MutableMap::class.java) as MutableMap<String, MutableList<PumpDbEntry>>
aapsLogger.debug(LTag.PUMP, String.format("Loading Pump Sync Storage: boluses=%d, tbrs=%d.", pumpSyncStorage[BOLUS]!!.size, pumpSyncStorage[TBR]!!.size)) aapsLogger.debug(LTag.PUMP, String.format("Loading Pump Sync Storage: boluses=%d, tbrs=%d.", pumpSyncStorage[BOLUS]!!.size, pumpSyncStorage[TBR]!!.size))