From 1c065c75e8ed56ccfb29bc8c486f546e801ed60a Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 11 Aug 2021 18:10:44 +0200 Subject: [PATCH] API 30 lints --- .../activities/HistoryBrowseActivity.kt | 1 - .../data/defaultProfile/DefaultProfile.kt | 5 +- .../androidaps/dialogs/LoopDialog.kt | 3 +- .../androidaps/dialogs/WizardDialog.kt | 2 +- .../general/maintenance/MaintenancePlugin.kt | 5 +- .../general/automation/AutomationEvent.kt | 2 +- .../general/automation/triggers/Trigger.kt | 36 +++++++------- .../nightscout/androidaps/di/CoreModule.kt | 2 +- .../dialogs/DialogFragmentWithDate.kt | 42 +++++++++------- .../androidaps/dialogs/ErrorDialog.kt | 9 ++-- .../extensions/DeviceStatusExtension.kt | 10 ++-- .../versionChecker/VersionCheckerUtils.kt | 48 ++++++++++++------- .../maintenance/PrefFileListProvider.kt | 4 +- .../activities/PrefImportListActivity.kt | 2 +- .../receivers/NetworkChangeReceiver.kt | 2 +- .../androidaps/services/AlarmSoundService.kt | 5 +- .../nightscout/androidaps/utils/CryptoUtil.kt | 5 +- .../textValidator/DefaultEditTextValidator.kt | 43 +++++++++-------- .../validators/RegexpValidator.kt | 2 +- .../androidaps/dana/DanaFragment.kt | 3 +- .../danar/comm/MsgSettingUserOptions.kt | 8 +--- .../danars/activities/BLEScanActivity.kt | 5 +- .../androidaps/diaconn/DiaconnG8Fragment.kt | 3 +- .../activities/DiaconnG8BLEScanActivity.kt | 7 +-- .../pump/medtronic/MedtronicFragment.kt | 9 ++-- .../medtronic/comm/message/PumpMessage.kt | 17 ++++--- .../comm/ui/MedtronicUIPostprocessor.kt | 5 +- .../pump/common/sync/PumpSyncStorage.kt | 2 +- 28 files changed, 160 insertions(+), 127 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt index 6b0be2cc68..0691f6d0f1 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt @@ -226,7 +226,6 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { outState.putInt("rangeToDisplay", rangeToDisplay) outState.putLong("start", overviewData.fromTime) outState.putLong("end", overviewData.toTime) - } private fun prepareGraphsIfNeeded(numOfGraphs: Int) { diff --git a/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt index fa8b2774be..88066767bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt +++ b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt @@ -11,6 +11,7 @@ import org.json.JSONObject import java.util.* import javax.inject.Inject import javax.inject.Singleton +import kotlin.math.abs @Singleton class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { @@ -120,12 +121,12 @@ class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { val high = map.ceilingEntry(key) var res: Array? = 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 else high.value } 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 } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt index 7bacb0120b..6c335de9ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.dialogs import android.content.Context import android.os.Bundle import android.os.Handler +import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -62,7 +63,7 @@ class LoopDialog : DaggerDialogFragment() { private var showOkCancel: Boolean = true private var _binding: DialogLoopBinding? = null - private var loopHandler = Handler() + private var loopHandler = Handler(Looper.getMainLooper()) private lateinit var refreshDialog: Runnable // This property is only valid between onCreateView and diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 9d65cc01e1..1483359162 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -384,7 +384,7 @@ class WizardDialog : DaggerDialogFragment() { it.commitAllowingStateLoss() } } catch (e: IllegalStateException) { - aapsLogger.debug(e.localizedMessage) + aapsLogger.debug(e.localizedMessage ?: "") } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index deb2d9e7e8..ddbae593fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -85,9 +85,8 @@ class MaintenancePlugin @Inject constructor( } val exportDir = fileListProvider.ensureTempDirExists() if (exportDir.exists()) { - val expFiles = exportDir.listFiles() - for (file in expFiles) { - file.delete() + exportDir.listFiles()?.let { expFiles -> + for (file in expFiles) file.delete() } exportDir.delete() } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt index ca2ba012e0..f0e8bffd89 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt @@ -64,7 +64,7 @@ class AutomationEvent(private val injector: HasAndroidInjector) { .toString() } - fun fromJSON(data: String?): AutomationEvent { + fun fromJSON(data: String): AutomationEvent { val d = JSONObject(data) title = d.optString("title", "") isEnabled = d.optBoolean("enabled", true) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index c67c10bb75..a410ca3902 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -87,41 +87,41 @@ abstract class Trigger(val injector: HasAndroidInjector) { //return (clazz.primaryConstructor?.call(injector) as Trigger).fromJSON(data?.toString() ?: "") return when (type) { 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.simpleName -> TriggerBg(injector).fromJSON(data?.toString() ?: "") + TriggerBg::class.java.simpleName -> TriggerBg(injector).fromJSON(data.toString()) 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.simpleName -> TriggerBTDevice(injector).fromJSON(data?.toString() ?: "") + TriggerBTDevice::class.java.simpleName -> TriggerBTDevice(injector).fromJSON(data.toString()) 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.simpleName -> TriggerCOB(injector).fromJSON(data?.toString() ?: "") + TriggerCOB::class.java.simpleName -> TriggerCOB(injector).fromJSON(data.toString()) 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.simpleName -> TriggerDelta(injector).fromJSON(data?.toString() ?: "") + TriggerDelta::class.java.simpleName -> TriggerDelta(injector).fromJSON(data.toString()) 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.simpleName -> TriggerIob(injector).fromJSON(data?.toString() ?: "") + TriggerIob::class.java.simpleName -> TriggerIob(injector).fromJSON(data.toString()) 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.simpleName -> TriggerProfilePercent(injector).fromJSON(data?.toString() ?: "") + TriggerProfilePercent::class.java.simpleName -> TriggerProfilePercent(injector).fromJSON(data.toString()) 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.simpleName -> TriggerRecurringTime(injector).fromJSON(data?.toString() ?: "") + TriggerRecurringTime::class.java.simpleName -> TriggerRecurringTime(injector).fromJSON(data.toString()) 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.simpleName -> TriggerTime(injector).fromJSON(data?.toString() ?: "") + TriggerTime::class.java.simpleName -> TriggerTime(injector).fromJSON(data.toString()) 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.simpleName -> TriggerWifiSsid(injector).fromJSON(data?.toString() ?: "") + TriggerWifiSsid::class.java.simpleName -> TriggerWifiSsid(injector).fromJSON(data.toString()) else -> throw ClassNotFoundException(type) } } diff --git a/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt b/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt index ec2b5bb1ad..45aa71abeb 100644 --- a/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt +++ b/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.di import android.content.Context -import android.preference.PreferenceManager +import androidx.preference.PreferenceManager import dagger.Module import dagger.Provides import info.nightscout.androidaps.logging.AAPSLogger diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt index 0ad6a55114..25ff67e21d 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt @@ -40,7 +40,10 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { override fun 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) { @@ -67,22 +70,24 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { eventTimeView?.text = dateUtil.timeString(eventTime) // create an OnDateSetListener - val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> - val cal = Calendar.getInstance() - cal.timeInMillis = eventTime - cal.set(Calendar.YEAR, year) - cal.set(Calendar.MONTH, monthOfYear) - cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) - eventTime = cal.timeInMillis - eventTimeChanged = true - eventDateView?.text = dateUtil.dateString(eventTime) - } + val dateSetListener = + DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> + val cal = Calendar.getInstance() + cal.timeInMillis = eventTime + cal.set(Calendar.YEAR, year) + cal.set(Calendar.MONTH, monthOfYear) + cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) + eventTime = cal.timeInMillis + eventTimeChanged = true + eventDateView?.text = dateUtil.dateString(eventTime) + } eventDateView?.setOnClickListener { context?.let { val cal = Calendar.getInstance() cal.timeInMillis = eventTime - DatePickerDialog(it, dateSetListener, + DatePickerDialog( + it, dateSetListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH) @@ -96,7 +101,10 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { cal.timeInMillis = eventTime cal.set(Calendar.HOUR_OF_DAY, hour) 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 eventTimeChanged = true eventTimeView?.text = dateUtil.timeString(eventTime) @@ -106,7 +114,8 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { context?.let { val cal = Calendar.getInstance() cal.timeInMillis = eventTime - TimePickerDialog(it, timeSetListener, + TimePickerDialog( + it, timeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 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 { synchronized(okClicked) { @@ -137,7 +147,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { it.commitAllowingStateLoss() } } catch (e: IllegalStateException) { - aapsLogger.debug(e.localizedMessage) + aapsLogger.debug(e.localizedMessage ?: "") } } diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt index a5ccaa2b41..956dd54804 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt @@ -1,7 +1,9 @@ package info.nightscout.androidaps.dialogs +import android.content.Context import android.os.Bundle import android.os.Handler +import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -24,13 +26,14 @@ class ErrorDialog : DaggerDialogFragment() { @Inject lateinit var alarmSoundServiceHelper: AlarmSoundServiceHelper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var uel: UserEntryLogger + @Inject lateinit var ctx: Context var helperActivity: ErrorHelperActivity? = null var status: String = "" var title: String = "" var sound: Int = 0 - private var loopHandler = Handler() + private var loopHandler = Handler(Looper.getMainLooper()) private var _binding: DialogErrorBinding? = null @@ -106,9 +109,9 @@ class ErrorDialog : DaggerDialogFragment() { private fun startAlarm() { if (sound != 0) - context?.let { context -> alarmSoundServiceHelper.startAlarm(context, sound) } + alarmSoundServiceHelper.startAlarm(ctx, sound) } private fun stopAlarm() = - context?.let { context -> alarmSoundServiceHelper.stopService(context) } + alarmSoundServiceHelper.stopService(ctx) } diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt index 4239f72ab2..46aca076d5 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt @@ -16,14 +16,14 @@ fun DeviceStatus.toJson(dateUtil: DateUtil): JSONObject = .put("created_at", dateUtil.toISOString(timestamp)) .also { 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 -> - if (enacted != null) openaps.put("enacted", JSONObject(enacted)) - if (suggested != null) openaps.put("suggested", JSONObject(suggested)) - if (iob != null) openaps.put("iob", JSONObject(iob)) + enacted?.let { enacted -> openaps.put("enacted", JSONObject(enacted)) } + suggested?.let { suggested -> openaps.put("suggested", JSONObject(suggested)) } + iob?.let { iob -> openaps.put("iob", JSONObject(iob)) } }) 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( diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt b/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt index edf712bb52..e58fce4dd8 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.constraints.versionChecker import android.content.Context -import android.net.ConnectivityManager import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.Config 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.general.overview.events.EventNewNotification 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.sharedPreferences.SP import java.io.IOException @@ -24,24 +24,28 @@ class VersionCheckerUtils @Inject constructor( val resourceHelper: ResourceHelper, val rxBus: RxBusWrapper, private val config: Config, - val context: Context + val context: Context, + val receiverStatusStore: ReceiverStatusStore ) { - // check network connection - fun isConnected(): Boolean { - val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager - return connMgr.activeNetworkInfo?.isConnected ?: false - } + fun isConnected(): Boolean = receiverStatusStore.isConnected fun triggerCheckVersion() { 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. - 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 (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() } } @@ -49,7 +53,8 @@ class VersionCheckerUtils @Inject constructor( private fun checkVersion() = if (isConnected()) { Thread { 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) } catch (e: IOException) { aapsLogger.error(LTag.CORE, "Github master version check error: $e") @@ -81,8 +86,8 @@ class VersionCheckerUtils @Inject constructor( (newElem - currElem).let { when { - it > 0 -> return onNewVersionDetected(currentVersion, newVersion) - it < 0 -> return onOlderVersionDetected() + it > 0 -> return onNewVersionDetected(currentVersion, newVersion) + it < 0 -> return onOlderVersionDetected() it == 0 -> Unit } } @@ -107,7 +112,11 @@ class VersionCheckerUtils @Inject constructor( val now = System.currentTimeMillis() if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) { 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)) sp.putLong(R.string.key_last_versionchecker_warning, now) } @@ -126,7 +135,8 @@ class VersionCheckerUtils @Inject constructor( fun findVersion(file: String?): String? { 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 { @@ -142,14 +152,18 @@ fun String.numericVersionPart(): String = @Suppress("unused") fun findVersion(file: String?): String? { 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 { when (it) { in '0'..'9' -> it - '.' -> it + '.' -> it else -> null } }.joinToString(separator = "") \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt index 028b97ca75..c501b9cef0 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.maintenance +import android.content.Context import android.os.Environment import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.Config @@ -25,7 +26,8 @@ class PrefFileListProvider @Inject constructor( private val classicPrefsFormat: ClassicPrefsFormat, private val encryptedPrefsFormat: EncryptedPrefsFormat, private val storage: Storage, - private val versionCheckerUtils: VersionCheckerUtils + private val versionCheckerUtils: VersionCheckerUtils, + context: Context ) { private val path = File(Environment.getExternalStorageDirectory().toString()) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt index 77c361d869..9e29f529f9 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt @@ -81,7 +81,7 @@ class PrefImportListActivity : DaggerAppCompatActivity() { filelistName.text = prefFile.file.name 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() metalineName.visibility = visible diff --git a/core/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.kt b/core/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.kt index 9233ee1b1b..8ac514a213 100644 --- a/core/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.kt +++ b/core/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.kt @@ -25,7 +25,7 @@ class NetworkChangeReceiver : DaggerBroadcastReceiver() { rxBus.send(grabNetworkStatus(context, aapsLogger)) } - fun grabNetworkStatus(context: Context, aapsLogger: AAPSLogger): EventNetworkChange { + private fun grabNetworkStatus(context: Context, aapsLogger: AAPSLogger): EventNetworkChange { val event = EventNetworkChange() val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networks: Array = cm.allNetworks diff --git a/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt b/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt index 6480189f41..7af82b750d 100644 --- a/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt +++ b/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt @@ -7,6 +7,7 @@ import android.media.MediaPlayer import android.os.Binder import android.os.Handler import android.os.IBinder +import android.os.Looper import dagger.android.DaggerService import info.nightscout.androidaps.activities.ErrorHelperActivity 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 /* - * 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 * */ @@ -53,7 +54,7 @@ class AlarmSoundService : DaggerService() { private val binder = LocalBinder() override fun onBind(intent: Intent): IBinder = binder - private val increaseVolumeHandler = Handler() + private val increaseVolumeHandler = Handler(Looper.getMainLooper()) private var currentVolumeLevel = 0 override fun onCreate() { diff --git a/core/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt b/core/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt index 563db53270..4aa7b34084 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt @@ -17,6 +17,7 @@ import javax.crypto.spec.SecretKeySpec import javax.inject.Inject import javax.inject.Singleton +@Suppress("SpellCheckingInspection") @Singleton class CryptoUtil @Inject constructor( val aapsLogger: AAPSLogger @@ -39,7 +40,7 @@ class CryptoUtil @Inject constructor( return hashRaw.toHex() } - fun hmac256(str: String, secret: String): String? { + fun hmac256(str: String, secret: String): String { val sha256HMAC = Mac.getInstance("HmacSHA256") val secretKey = SecretKeySpec(secret.toByteArray(), "HmacSHA256") sha256HMAC.init(secretKey) @@ -68,7 +69,7 @@ class CryptoUtil @Inject constructor( secureRandom.nextBytes(iv) val cipherEnc: Cipher = Cipher.getInstance("AES/GCM/NoPadding") 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) byteBuffer.put(iv.size.toByte()) byteBuffer.put(iv) diff --git a/core/src/main/java/info/nightscout/androidaps/utils/textValidator/DefaultEditTextValidator.kt b/core/src/main/java/info/nightscout/androidaps/utils/textValidator/DefaultEditTextValidator.kt index 4306ae20fc..220bc2d980 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/textValidator/DefaultEditTextValidator.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/textValidator/DefaultEditTextValidator.kt @@ -9,25 +9,26 @@ import com.google.android.material.textfield.TextInputLayout import info.nightscout.androidaps.core.R import info.nightscout.androidaps.utils.textValidator.validators.* +@Suppress("SpellCheckingInspection") class DefaultEditTextValidator : EditTextValidator { - protected var mValidator: MultiValidator? = null - protected var testErrorString: String? = null - protected var emptyAllowed = false - protected lateinit var editTextView: EditText + private var mValidator: MultiValidator? = null + private var testErrorString: String? = null + private var emptyAllowed = false + private lateinit var editTextView: EditText private var tw: TextWatcher? = null private var defaultEmptyErrorString: String? = null - protected var testType: Int - protected var classType: String? = null - protected var customRegexp: String? = null - protected var customFormat: String? = null - protected var emptyErrorStringActual: String? = null - protected var emptyErrorStringDef: String? = null - protected var minLength = 0 - protected var minNumber = 0 - protected var maxNumber = 0 - protected var floatminNumber = 0f - protected var floatmaxNumber = 0f + private var testType: Int + private var classType: String? = null + private var customRegexp: String? = null + private var customFormat: String? = null + private var emptyErrorStringActual: String? = null + private var emptyErrorStringDef: String? = null + private var minLength = 0 + private var minNumber = 0 + private var maxNumber = 0 + private var floatminNumber = 0f + private var floatmaxNumber = 0f @Suppress("unused") constructor(editTextView: EditText, context: Context) { @@ -56,8 +57,7 @@ class DefaultEditTextValidator : EditTextValidator { @Throws(IllegalArgumentException::class) override fun addValidator(theValidator: Validator) { - requireNotNull(theValidator) { "theValidator argument should not be null" } - mValidator!!.enqueue(theValidator) + mValidator?.enqueue(theValidator) } private fun setEditText(editText: EditText) { @@ -105,9 +105,9 @@ class DefaultEditTextValidator : EditTextValidator { EditTextValidator.TEST_ALPHANUMERIC -> toAdd = AlphaNumericValidator( 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_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_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_REGEXP -> toAdd = RegexpValidator(testErrorString, customRegexp) + 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, floatminNumber.toString(), floatmaxNumber.toString()) else testErrorString, floatminNumber, floatmaxNumber) + 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_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) @@ -185,7 +185,7 @@ class DefaultEditTextValidator : EditTextValidator { return this } - fun setEmptyErrorString(emptyErrorString: String?): DefaultEditTextValidator { + private fun setEmptyErrorString(emptyErrorString: String?): DefaultEditTextValidator { emptyErrorStringActual = if (!TextUtils.isEmpty(emptyErrorString)) { emptyErrorString } else { @@ -243,6 +243,7 @@ class DefaultEditTextValidator : EditTextValidator { !TextUtils.isEmpty(editTextView.error) } + @Suppress("SpellCheckingInspection") data class Parameters( val testErrorString: String? = null, val emptyAllowed: Boolean = false, diff --git a/core/src/main/java/info/nightscout/androidaps/utils/textValidator/validators/RegexpValidator.kt b/core/src/main/java/info/nightscout/androidaps/utils/textValidator/validators/RegexpValidator.kt index 56f7278f35..a92d03299e 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/textValidator/validators/RegexpValidator.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/textValidator/validators/RegexpValidator.kt @@ -7,4 +7,4 @@ import java.util.regex.Pattern * * @author Andrea Baccega @andreabaccega.com> */ -open class RegexpValidator(message: String?, _regexp: String?) : PatternValidator(message, Pattern.compile(_regexp)) \ No newline at end of file +open class RegexpValidator(message: String?, _regexp: String) : PatternValidator(message, Pattern.compile(_regexp)) \ No newline at end of file diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt index 7c094f1824..ca509d3caf 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt @@ -4,6 +4,7 @@ import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.os.Handler +import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -61,7 +62,7 @@ class DanaFragment : DaggerFragment() { private var disposable: CompositeDisposable = CompositeDisposable() - private val loopHandler = Handler() + private val loopHandler = Handler(Looper.getMainLooper()) private lateinit var refreshLoop: Runnable private var _binding: DanarFragmentBinding? = null diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingUserOptions.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingUserOptions.kt index 2d7d703994..9f15346bb3 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingUserOptions.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingUserOptions.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag -import java.util.* class MsgSettingUserOptions( injector: HasAndroidInjector @@ -16,7 +15,7 @@ class MsgSettingUserOptions( override fun handleMessage(packet: ByteArray) { 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) { aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos]) } @@ -46,10 +45,7 @@ class MsgSettingUserOptions( aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaPump.lowReservoirRate) } - private fun getDataBytes(bytes: ByteArray?, len: Int): ByteArray? { - if (bytes == null) { - return null - } + private fun getDataBytes(bytes: ByteArray, len: Int): ByteArray { val ret = ByteArray(len) System.arraycopy(bytes, 6, ret, 0, len) return ret diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/activities/BLEScanActivity.kt b/danars/src/main/java/info/nightscout/androidaps/danars/activities/BLEScanActivity.kt index 0ed1dbc90a..283ae139e8 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/activities/BLEScanActivity.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/activities/BLEScanActivity.kt @@ -9,6 +9,7 @@ import android.bluetooth.le.ScanResult import android.content.pm.ActivityInfo import android.os.Bundle import android.os.Handler +import android.os.Looper import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter @@ -87,7 +88,7 @@ class BLEScanActivity : NoSplashAppCompatActivity() { return } devices.add(item) - Handler().post { listAdapter!!.notifyDataSetChanged() } + Handler(Looper.getMainLooper()).post { listAdapter?.notifyDataSetChanged() } } private val mBleScanCallback: ScanCallback = object : ScanCallback() { @@ -172,7 +173,7 @@ class BLEScanActivity : NoSplashAppCompatActivity() { 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 p = Pattern.compile(regex) val m = p.matcher(sn) diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt index 0c3ff324d7..fa5c058112 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt @@ -4,6 +4,7 @@ import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.os.Handler +import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -48,7 +49,7 @@ class DiaconnG8Fragment : DaggerFragment() { private var disposable: CompositeDisposable = CompositeDisposable() - private val loopHandler = Handler() + private val loopHandler = Handler(Looper.getMainLooper()) private lateinit var refreshLoop: Runnable private var _binding: DiaconnG8FragmentBinding? = null diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt index df908e0bca..0581f0a42b 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt @@ -11,6 +11,7 @@ import android.bluetooth.le.ScanSettings import android.content.pm.ActivityInfo import android.os.Bundle import android.os.Handler +import android.os.Looper import android.os.ParcelUuid import android.view.View import android.view.ViewGroup @@ -72,10 +73,10 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() { private fun startScan() = try { val filters: MutableList = ArrayList() - val scan_filter = ScanFilter.Builder() + val scanFilter = ScanFilter.Builder() .setServiceUuid(ParcelUuid(serviceUUID)) .build() - filters.add(scan_filter) + filters.add(scanFilter) val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) @@ -100,7 +101,7 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() { return } devices.add(item) - Handler().post { listAdapter!!.notifyDataSetChanged() } + Handler(Looper.getMainLooper()).post { listAdapter?.notifyDataSetChanged() } } private val mBleScanCallback: ScanCallback = object : ScanCallback() { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 57630d6248..672a7555f3 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -5,6 +5,7 @@ import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.Handler +import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -67,7 +68,7 @@ class MedtronicFragment : DaggerFragment() { private var disposable: CompositeDisposable = CompositeDisposable() - private val loopHandler = Handler() + private val loopHandler = Handler(Looper.getMainLooper()) private lateinit var refreshLoop: Runnable init { @@ -98,7 +99,7 @@ class MedtronicFragment : DaggerFragment() { binding.pumpStatusIcon.text = "{fa-bed}" binding.history.setOnClickListener { - if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration() == true) { + if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration()) { startActivity(Intent(context, MedtronicHistoryActivity::class.java)) } else { displayNotConfiguredDialog() @@ -106,7 +107,7 @@ class MedtronicFragment : DaggerFragment() { } binding.refresh.setOnClickListener { - if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration() != true) { + if (!medtronicPumpPlugin.rileyLinkService.verifyConfiguration()) { displayNotConfiguredDialog() } else { binding.refresh.isEnabled = false @@ -120,7 +121,7 @@ class MedtronicFragment : DaggerFragment() { } binding.stats.setOnClickListener { - if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration() == true) { + if (medtronicPumpPlugin.rileyLinkService.verifyConfiguration()) { startActivity(Intent(context, RileyLinkStatusActivity::class.java)) } else { displayNotConfiguredDialog() diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.kt index 82633d015d..462d589941 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.kt @@ -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.utils.ByteUtil import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType +import kotlin.math.min /** * Created by geoff on 5/29/16. @@ -15,7 +16,7 @@ class PumpMessage : RLMessage { private var packetType: PacketType? = PacketType.Carelink var address: ByteArray? = byteArrayOf(0, 0, 0) var commandType: MedtronicCommandType? = null - var invalidCommandType: Byte? = null + private var invalidCommandType: Byte? = null var messageBody: MessageBody? = MessageBody() var error: String? = null @@ -33,7 +34,7 @@ class PumpMessage : RLMessage { this.aapsLogger = aapsLogger } - val isErrorResponse: Boolean + @Suppress("unused") val isErrorResponse: Boolean get() = error != null fun init(packetType: PacketType?, address: ByteArray?, commandType: MedtronicCommandType?, messageBody: MessageBody?) { @@ -47,7 +48,7 @@ class PumpMessage : RLMessage { if (rxData == null) { return } - if (rxData.size > 0) { + if (rxData.isNotEmpty()) { packetType = PacketType.getByValue(rxData[0].toShort()) } if (rxData.size > 3) { @@ -87,7 +88,7 @@ class PumpMessage : RLMessage { // rawContent = just response without code (contents-2, messageBody.txData-1); val rawContent: ByteArray 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 var length = ByteUtil.asUINT8(data!![0]) // length is not always correct so, we check whole array if we have // data, after length @@ -109,7 +110,9 @@ class PumpMessage : RLMessage { length = data.size - 1 } val arrayOut = ByteArray(length) - System.arraycopy(messageBody!!.txData, 1, arrayOut, 0, length) + messageBody?.txData?.let { + System.arraycopy(it, 1, arrayOut, 0, length) + } // if (isLogEnabled()) // LOG.debug("PumpMessage - Length: " + length + ", Original Length: " + originalLength + ", CommandType: " @@ -120,10 +123,10 @@ class PumpMessage : RLMessage { val rawContentOfFrame: ByteArray get() { val raw = messageBody!!.txData - return if (raw == null || raw.size == 0) { + return if (raw == null || raw.isEmpty()) { byteArrayOf() } else { - ByteUtil.substring(raw, 1, Math.min(FRAME_DATA_LENGTH, raw.size - 1)) + ByteUtil.substring(raw, 1, min(FRAME_DATA_LENGTH, raw.size - 1)) } } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt index 9ad461c0d6..86afbc0014 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt @@ -143,10 +143,7 @@ class MedtronicUIPostprocessor @Inject constructor( } private fun postProcessSettings(uiTask: MedtronicUITask) { - val settings = uiTask.result as? Map - - if (settings == null) - return + val settings = uiTask.result as? Map ?: return medtronicUtil.settings = settings var checkValue: PumpSettingDTO diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt index dd4a55dced..0e285b6643 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt @@ -44,7 +44,7 @@ class PumpSyncStorage @Inject constructor( if (sp.contains(pumpSyncStorageKey)) { val jsonData: String = sp.getString(pumpSyncStorageKey, ""); - if (!jsonData.isBlank()) { + if (jsonData.isNotBlank()) { pumpSyncStorage = xstream.fromXML(jsonData, MutableMap::class.java) as MutableMap> aapsLogger.debug(LTag.PUMP, String.format("Loading Pump Sync Storage: boluses=%d, tbrs=%d.", pumpSyncStorage[BOLUS]!!.size, pumpSyncStorage[TBR]!!.size))