unify Handlers

This commit is contained in:
Milos Kozak 2021-11-25 20:19:27 +01:00
parent a00dea8c0d
commit 6095a29595
19 changed files with 341 additions and 308 deletions

View file

@ -3,7 +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.os.HandlerThread
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -15,29 +15,30 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.OfflineEvent import info.nightscout.androidaps.database.entities.OfflineEvent
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.transactions.CancelCurrentOfflineEventIfAnyTransaction import info.nightscout.androidaps.database.transactions.CancelCurrentOfflineEventIfAnyTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentOfflineEventTransaction import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentOfflineEventTransaction
import info.nightscout.androidaps.databinding.DialogLoopBinding import info.nightscout.androidaps.databinding.DialogLoopBinding
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.extensions.runOnUiThread
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
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 io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -65,7 +66,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(Looper.getMainLooper()) private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
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
@ -87,8 +88,10 @@ class LoopDialog : DaggerDialogFragment() {
savedInstanceState.putInt("showOkCancel", if (showOkCancel) 1 else 0) savedInstanceState.putInt("showOkCancel", if (showOkCancel) 1 else 0)
} }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(
savedInstanceState: Bundle?): View { inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// load data from bundle // load data from bundle
(savedInstanceState ?: arguments)?.let { bundle -> (savedInstanceState ?: arguments)?.let { bundle ->
showOkCancel = bundle.getInt("showOkCancel", 1) == 1 showOkCancel = bundle.getInt("showOkCancel", 1) == 1
@ -126,35 +129,22 @@ class LoopDialog : DaggerDialogFragment() {
binding.cancel.setOnClickListener { dismiss() } binding.cancel.setOnClickListener { dismiss() }
refreshDialog = Runnable { refreshDialog = Runnable {
scheduleUpdateGUI() runOnUiThread { updateGUI("refreshDialog") }
loopHandler.postDelayed(refreshDialog, 15 * 1000L) handler.postDelayed(refreshDialog, 15 * 1000L)
} }
loopHandler.postDelayed(refreshDialog, 15 * 1000L) handler.postDelayed(refreshDialog, 15 * 1000L)
} }
@Synchronized @Synchronized
override fun onDestroyView() { override fun onDestroyView() {
super.onDestroyView() super.onDestroyView()
_binding = null _binding = null
loopHandler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
disposable.clear() disposable.clear()
} }
var task: Runnable? = null var task: Runnable? = null
private fun scheduleUpdateGUI() {
class UpdateRunnable : Runnable {
override fun run() {
updateGUI("refreshDialog")
task = null
}
}
view?.removeCallbacks(task)
task = UpdateRunnable()
view?.postDelayed(task, 500)
}
@Synchronized @Synchronized
fun updateGUI(from: String) { fun updateGUI(from: String) {
if (_binding == null) return if (_binding == null) return
@ -226,7 +216,8 @@ class LoopDialog : DaggerDialogFragment() {
} }
apsMode == "open" -> { apsMode == "open" -> {
binding.overviewCloseloop.visibility = closedLoopAllowed2.toVisibility() //show CloseLoop button only if Objective 6 is completed (closedLoopAllowed always false in open loop mode) binding.overviewCloseloop.visibility =
closedLoopAllowed2.toVisibility() //show CloseLoop button only if Objective 6 is completed (closedLoopAllowed always false in open loop mode)
binding.overviewLgsloop.visibility = lgsEnabled.value().toVisibility() binding.overviewLgsloop.visibility = lgsEnabled.value().toVisibility()
binding.overviewOpenloop.visibility = View.GONE binding.overviewOpenloop.visibility = View.GONE
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.constraints.objectives
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.HandlerThread
import android.os.Looper import android.os.Looper
import android.os.SystemClock import android.os.SystemClock
import android.view.Gravity import android.view.Gravity
@ -59,7 +60,7 @@ class ObjectivesFragment : DaggerFragment() {
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
private val objectivesAdapter = ObjectivesAdapter() private val objectivesAdapter = ObjectivesAdapter()
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()

View file

@ -56,19 +56,22 @@ class NSClientPlugin @Inject constructor(
private val nsClientReceiverDelegate: NsClientReceiverDelegate, private val nsClientReceiverDelegate: NsClientReceiverDelegate,
private val config: Config, private val config: Config,
private val buildHelper: BuildHelper private val buildHelper: BuildHelper
) : PluginBase(PluginDescription() ) : PluginBase(
PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(NSClientFragment::class.java.name) .fragmentClass(NSClientFragment::class.java.name)
.pluginIcon(R.drawable.ic_nightscout_syncs) .pluginIcon(R.drawable.ic_nightscout_syncs)
.pluginName(R.string.nsclientinternal) .pluginName(R.string.nsclientinternal)
.shortName(R.string.nsclientinternal_shortname) .shortName(R.string.nsclientinternal_shortname)
.preferencesId(R.xml.pref_nsclientinternal) .preferencesId(R.xml.pref_nsclientinternal)
.alwaysEnabled(config.NSCLIENT)
.visibleByDefault(config.NSCLIENT)
.description(R.string.description_ns_client), .description(R.string.description_ns_client),
aapsLogger, rh, injector aapsLogger, rh, injector
) { ) {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
var handler: Handler? = null private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private val listLog: MutableList<EventNSClientNewLog> = ArrayList() private val listLog: MutableList<EventNSClientNewLog> = ArrayList()
var textLog = fromHtml("") var textLog = fromHtml("")
var paused = false var paused = false
@ -78,17 +81,6 @@ class NSClientPlugin @Inject constructor(
val isAllowed: Boolean val isAllowed: Boolean
get() = nsClientReceiverDelegate.allowed get() = nsClientReceiverDelegate.allowed
init {
if (config.NSCLIENT) {
pluginDescription.alwaysEnabled(true).visibleByDefault(true)
}
if (handler == null) {
val handlerThread = HandlerThread(NSClientPlugin::class.java.simpleName + "Handler")
handlerThread.start()
handler = Handler(handlerThread.looper)
}
}
override fun onStart() { override fun onStart() {
paused = sp.getBoolean(R.string.key_nsclientinternal_paused, false) paused = sp.getBoolean(R.string.key_nsclientinternal_paused, false)
autoscroll = sp.getBoolean(R.string.key_nsclientinternal_autoscroll, true) autoscroll = sp.getBoolean(R.string.key_nsclientinternal_autoscroll, true)
@ -96,7 +88,8 @@ class NSClientPlugin @Inject constructor(
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE) context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
super.onStart() super.onStart()
nsClientReceiverDelegate.grabReceiversState() nsClientReceiverDelegate.grabReceiversState()
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventNSClientStatus::class.java) .toObservable(EventNSClientStatus::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientStatus -> .subscribe({ event: EventNSClientStatus ->
@ -104,22 +97,26 @@ class NSClientPlugin @Inject constructor(
rxBus.send(EventNSClientUpdateGUI()) rxBus.send(EventNSClientUpdateGUI())
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventNetworkChange::class.java) .toObservable(EventNetworkChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException) .subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException) .subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventAppExit::class.java) .toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ if (nsClientService != null) context.unbindService(mConnection) }, fabricPrivacy::logException) .subscribe({ if (nsClientService != null) context.unbindService(mConnection) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventNSClientNewLog::class.java) .toObservable(EventNSClientNewLog::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientNewLog -> .subscribe({ event: EventNSClientNewLog ->
@ -127,12 +124,14 @@ class NSClientPlugin @Inject constructor(
aapsLogger.debug(LTag.NSCLIENT, event.action + " " + event.logText) aapsLogger.debug(LTag.NSCLIENT, event.action + " " + event.logText)
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventChargingState::class.java) .toObservable(EventChargingState::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException) .subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventNSClientResend::class.java) .toObservable(EventNSClientResend::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event -> resend(event.reason) }, fabricPrivacy::logException) .subscribe({ event -> resend(event.reason) }, fabricPrivacy::logException)
@ -177,14 +176,14 @@ class NSClientPlugin @Inject constructor(
} }
@Synchronized fun clearLog() { @Synchronized fun clearLog() {
handler?.post { handler.post {
synchronized(listLog) { listLog.clear() } synchronized(listLog) { listLog.clear() }
rxBus.send(EventNSClientUpdateGUI()) rxBus.send(EventNSClientUpdateGUI())
} }
} }
@Synchronized private fun addToLog(ev: EventNSClientNewLog) { @Synchronized private fun addToLog(ev: EventNSClientNewLog) {
handler?.post { handler.post {
synchronized(listLog) { synchronized(listLog) {
listLog.add(ev) listLog.add(ev)
// remove the first line if log is too large // remove the first line if log is too large

View file

@ -91,7 +91,7 @@ class NSClientService : DaggerService() {
private var wakeLock: PowerManager.WakeLock? = null private var wakeLock: PowerManager.WakeLock? = null
private val binder: IBinder = LocalBinder() private val binder: IBinder = LocalBinder()
private var handler: Handler? = null private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private var socket: Socket? = null private var socket: Socket? = null
private var dataCounter = 0 private var dataCounter = 0
private var connectCounter = 0 private var connectCounter = 0
@ -114,7 +114,8 @@ class NSClientService : DaggerService() {
wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService") wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService")
wakeLock?.acquire() wakeLock?.acquire()
initialize() initialize()
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventConfigBuilderChange::class.java) .toObservable(EventConfigBuilderChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
@ -125,20 +126,23 @@ class NSClientService : DaggerService() {
} }
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange -> .subscribe({ event: EventPreferenceChange ->
if (event.isChanged(rh, R.string.key_nsclientinternal_url) || if (event.isChanged(rh, R.string.key_nsclientinternal_url) ||
event.isChanged(rh, R.string.key_nsclientinternal_api_secret) || event.isChanged(rh, R.string.key_nsclientinternal_api_secret) ||
event.isChanged(rh, R.string.key_nsclientinternal_paused)) { event.isChanged(rh, R.string.key_nsclientinternal_paused)
) {
latestDateInReceivedData = 0 latestDateInReceivedData = 0
destroy() destroy()
initialize() initialize()
} }
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventAppExit::class.java) .toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
@ -147,7 +151,8 @@ class NSClientService : DaggerService() {
stopSelf() stopSelf()
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(EventNSClientRestart::class.java) .toObservable(EventNSClientRestart::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
@ -155,17 +160,20 @@ class NSClientService : DaggerService() {
restart() restart()
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(NSAuthAck::class.java) .toObservable(NSAuthAck::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ack -> processAuthAck(ack) }, fabricPrivacy::logException) .subscribe({ ack -> processAuthAck(ack) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(NSUpdateAck::class.java) .toObservable(NSUpdateAck::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ack -> processUpdateAck(ack) }, fabricPrivacy::logException) .subscribe({ ack -> processUpdateAck(ack) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(
rxBus
.toObservable(NSAddAck::class.java) .toObservable(NSAddAck::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ ack -> processAddAck(ack) }, fabricPrivacy::logException) .subscribe({ ack -> processAddAck(ack) }, fabricPrivacy::logException)
@ -183,7 +191,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue( dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientAddAckWorker::class.java) OneTimeWorkRequest.Builder(NSClientAddAckWorker::class.java)
.setInputData(dataWorker.storeInputData(ack, null)) .setInputData(dataWorker.storeInputData(ack, null))
.build()) .build()
)
} }
private fun processUpdateAck(ack: NSUpdateAck) { private fun processUpdateAck(ack: NSUpdateAck) {
@ -191,7 +200,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue( dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientUpdateRemoveAckWorker::class.java) OneTimeWorkRequest.Builder(NSClientUpdateRemoveAckWorker::class.java)
.setInputData(dataWorker.storeInputData(ack, null)) .setInputData(dataWorker.storeInputData(ack, null))
.build()) .build()
)
} }
private fun processAuthAck(ack: NSAuthAck) { private fun processAuthAck(ack: NSAuthAck) {
@ -448,7 +458,7 @@ class NSClientService : DaggerService() {
} }
} }
private val onDataUpdate = Emitter.Listener { args -> private val onDataUpdate = Emitter.Listener { args ->
handler?.post { handler.post {
// val powerManager = getSystemService(POWER_SERVICE) as PowerManager // val powerManager = getSystemService(POWER_SERVICE) as PowerManager
// val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, // val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
// "AndroidAPS:NSClientService_onDataUpdate") // "AndroidAPS:NSClientService_onDataUpdate")
@ -474,7 +484,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue( dataWorker.enqueue(
OneTimeWorkRequest.Builder(LocalProfilePlugin.NSProfileWorker::class.java) OneTimeWorkRequest.Builder(LocalProfilePlugin.NSProfileWorker::class.java)
.setInputData(dataWorker.storeInputData(profileStoreJson, null)) .setInputData(dataWorker.storeInputData(profileStoreJson, null))
.build()) .build()
)
xDripBroadcast.sendProfile(profileStoreJson) xDripBroadcast.sendProfile(profileStoreJson)
} }
} }
@ -492,7 +503,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue( dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientAddUpdateWorker::class.java) OneTimeWorkRequest.Builder(NSClientAddUpdateWorker::class.java)
.setInputData(dataWorker.storeInputData(addedOrUpdatedTreatments, null)) .setInputData(dataWorker.storeInputData(addedOrUpdatedTreatments, null))
.build()) .build()
)
xDripBroadcast.sendTreatments(addedOrUpdatedTreatments) xDripBroadcast.sendTreatments(addedOrUpdatedTreatments)
} }
} }
@ -509,7 +521,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue( dataWorker.enqueue(
OneTimeWorkRequest.Builder(FoodWorker::class.java) OneTimeWorkRequest.Builder(FoodWorker::class.java)
.setInputData(dataWorker.storeInputData(foods, null)) .setInputData(dataWorker.storeInputData(foods, null))
.build()) .build()
)
} }
if (data.has("mbgs")) { if (data.has("mbgs")) {
val mbgArray = data.getJSONArray("mbgs") val mbgArray = data.getJSONArray("mbgs")
@ -517,7 +530,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue( dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientMbgWorker::class.java) OneTimeWorkRequest.Builder(NSClientMbgWorker::class.java)
.setInputData(dataWorker.storeInputData(mbgArray, null)) .setInputData(dataWorker.storeInputData(mbgArray, null))
.build()) .build()
)
} }
if (data.has("cals")) { if (data.has("cals")) {
val cals = data.getJSONArray("cals") val cals = data.getJSONArray("cals")
@ -527,9 +541,11 @@ class NSClientService : DaggerService() {
if (data.has("sgvs")) { if (data.has("sgvs")) {
val sgvs = data.getJSONArray("sgvs") val sgvs = data.getJSONArray("sgvs")
if (sgvs.length() > 0) rxBus.send(EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs")) if (sgvs.length() > 0) rxBus.send(EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"))
dataWorker.enqueue(OneTimeWorkRequest.Builder(NSClientSourceWorker::class.java) dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientSourceWorker::class.java)
.setInputData(dataWorker.storeInputData(sgvs, null)) .setInputData(dataWorker.storeInputData(sgvs, null))
.build()) .build()
)
xDripBroadcast.sendSgvs(sgvs) xDripBroadcast.sendSgvs(sgvs)
} }
rxBus.send(EventNSClientNewLog("LAST", dateUtil.dateAndTimeString(latestDateInReceivedData))) rxBus.send(EventNSClientNewLog("LAST", dateUtil.dateAndTimeString(latestDateInReceivedData)))
@ -552,8 +568,12 @@ class NSClientService : DaggerService() {
message.put("_id", _id) message.put("_id", _id)
message.put("data", data) message.put("data", data)
socket?.emit("dbUpdate", message, NSUpdateAck("dbUpdate", _id, aapsLogger, rxBus, originalObject)) socket?.emit("dbUpdate", message, NSUpdateAck("dbUpdate", _id, aapsLogger, rxBus, originalObject))
rxBus.send(EventNSClientNewLog("DBUPDATE $collection", "Sent " + originalObject.javaClass.simpleName + " " + rxBus.send(
"" + _id + " " + data + progress)) EventNSClientNewLog(
"DBUPDATE $collection", "Sent " + originalObject.javaClass.simpleName + " " +
"" + _id + " " + data + progress
)
)
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)
} }
@ -580,7 +600,7 @@ class NSClientService : DaggerService() {
fun resend(reason: String) { fun resend(reason: String) {
if (!isConnected || !hasWriteAuth) return if (!isConnected || !hasWriteAuth) return
handler?.post { handler.post {
if (socket?.connected() != true) return@post if (socket?.connected() != true) return@post
if (lastAckTime > System.currentTimeMillis() - 10 * 1000L) { if (lastAckTime > System.currentTimeMillis() - 10 * 1000L) {
aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastAckTime: " + (System.currentTimeMillis() - lastAckTime) / 1000L + " sec") aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastAckTime: " + (System.currentTimeMillis() - lastAckTime) / 1000L + " sec")
@ -643,12 +663,4 @@ class NSClientService : DaggerService() {
aapsLogger.debug(LTag.NSCLIENT, alarm.toString()) aapsLogger.debug(LTag.NSCLIENT, alarm.toString())
} }
} }
init {
if (handler == null) {
val handlerThread = HandlerThread(NSClientService::class.java.simpleName + "Handler")
handlerThread.start()
handler = Handler(handlerThread.looper)
}
}
} }

View file

@ -45,7 +45,6 @@ import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.extensions.valueToUnitsString import info.nightscout.androidaps.extensions.valueToUnitsString
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification
@ -132,7 +131,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
private lateinit var dm: DisplayMetrics private lateinit var dm: DisplayMetrics
private var axisWidth: Int = 0 private var axisWidth: Int = 0
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private lateinit var handler: Handler private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private val secondaryGraphs = ArrayList<GraphView>() private val secondaryGraphs = ArrayList<GraphView>()
private val secondaryGraphsLabel = ArrayList<TextView>() private val secondaryGraphsLabel = ArrayList<TextView>()
@ -158,7 +158,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
// pre-process landscape mode // pre-process landscape mode
val screenWidth = dm.widthPixels val screenWidth = dm.widthPixels

View file

@ -39,7 +39,7 @@ class VirtualPumpFragment : DaggerFragment() {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private lateinit var handler: Handler private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private var _binding: VirtualpumpFragmentBinding? = null private var _binding: VirtualpumpFragmentBinding? = null
@ -54,8 +54,8 @@ class VirtualPumpFragment : DaggerFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
} }
@Synchronized @Synchronized
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()

View file

@ -50,7 +50,7 @@ class GlunovoPlugin @Inject constructor(
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
), BgSource { ), BgSource {
private val loopHandler: Handler = Handler(HandlerThread(this::class.java.simpleName + "Handler").also { it.start() }.looper) private val handler = Handler(HandlerThread(this::class.java.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private val contentUri: Uri = Uri.parse("content://$AUTHORITY/$TABLE_NAME") private val contentUri: Uri = Uri.parse("content://$AUTHORITY/$TABLE_NAME")
@ -65,7 +65,7 @@ class GlunovoPlugin @Inject constructor(
} }
val lastReadTimestamp = sp.getLong(R.string.key_last_processed_glunovo_timestamp, 0L) val lastReadTimestamp = sp.getLong(R.string.key_last_processed_glunovo_timestamp, 0L)
val differenceToNow = INTERVAL - (dateUtil.now() - lastReadTimestamp) % INTERVAL + T.secs(10).msecs() val differenceToNow = INTERVAL - (dateUtil.now() - lastReadTimestamp) % INTERVAL + T.secs(10).msecs()
loopHandler.postDelayed(refreshLoop, differenceToNow) handler.postDelayed(refreshLoop, differenceToNow)
} }
} }
@ -73,12 +73,12 @@ class GlunovoPlugin @Inject constructor(
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
loopHandler.postDelayed(refreshLoop, T.secs(30).msecs()) // do not start immediately, app may be still starting handler.postDelayed(refreshLoop, T.secs(30).msecs()) // do not start immediately, app may be still starting
} }
override fun onStop() { override fun onStop() {
super.onStop() super.onStop()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
disposable.clear() disposable.clear()
} }

View file

@ -45,7 +45,7 @@ class RandomBgPlugin @Inject constructor(
aapsLogger, rh, injector aapsLogger, rh, injector
), BgSource { ), BgSource {
private val loopHandler: Handler = Handler(HandlerThread(RandomBgPlugin::class.java.simpleName + "Handler").also { it.start() }.looper) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
companion object { companion object {
@ -58,7 +58,7 @@ class RandomBgPlugin @Inject constructor(
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
loopHandler.postDelayed(refreshLoop, T.mins(interval).msecs()) handler.postDelayed(refreshLoop, T.mins(interval).msecs())
handleNewData() handleNewData()
} }
} }
@ -74,13 +74,13 @@ class RandomBgPlugin @Inject constructor(
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
loopHandler.postDelayed(refreshLoop, T.mins(interval).msecs()) handler.postDelayed(refreshLoop, T.mins(interval).msecs())
disposable.clear() disposable.clear()
} }
override fun onStop() { override fun onStop() {
super.onStop() super.onStop()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
} }
override fun specialEnableCondition(): Boolean { override fun specialEnableCondition(): Boolean {

View file

@ -77,7 +77,7 @@ class AutomationPlugin @Inject constructor(
var executionLog: MutableList<String> = ArrayList() var executionLog: MutableList<String> = ArrayList()
var btConnects: MutableList<EventBTChange> = ArrayList() var btConnects: MutableList<EventBTChange> = ArrayList()
private val loopHandler: Handler = Handler(HandlerThread(AutomationPlugin::class.java.simpleName + "Handler").also { it.start() }.looper) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
companion object { companion object {
@ -89,7 +89,7 @@ class AutomationPlugin @Inject constructor(
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
processActions() processActions()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
} }
} }
@ -100,7 +100,7 @@ class AutomationPlugin @Inject constructor(
super.onStart() super.onStart()
loadFromSP() loadFromSP()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus disposable += rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
@ -148,7 +148,7 @@ class AutomationPlugin @Inject constructor(
override fun onStop() { override fun onStop() {
disposable.clear() disposable.clear()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
locationServiceHelper.stopService(context) locationServiceHelper.stopService(context)
super.onStop() super.onStop()
} }

View file

@ -3,7 +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.os.HandlerThread
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -33,7 +33,7 @@ class ErrorDialog : DaggerDialogFragment() {
var title: String = "" var title: String = ""
var sound: Int = 0 var sound: Int = 0
private var loopHandler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private var _binding: DialogErrorBinding? = null private var _binding: DialogErrorBinding? = null
@ -73,7 +73,7 @@ class ErrorDialog : DaggerDialogFragment() {
binding.mute5min.setOnClickListener { binding.mute5min.setOnClickListener {
uel.log(Action.ERROR_DIALOG_MUTE_5MIN, Sources.Unknown) uel.log(Action.ERROR_DIALOG_MUTE_5MIN, Sources.Unknown)
stopAlarm() stopAlarm()
loopHandler.postDelayed(this::startAlarm, T.mins(5).msecs()) handler.postDelayed(this::startAlarm, T.mins(5).msecs())
} }
startAlarm() startAlarm()
} }
@ -103,7 +103,7 @@ class ErrorDialog : DaggerDialogFragment() {
override fun dismiss() { override fun dismiss() {
super.dismissAllowingStateLoss() super.dismissAllowingStateLoss()
helperActivity?.finish() helperActivity?.finish()
loopHandler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
stopAlarm() stopAlarm()
} }

View file

@ -4,7 +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.os.HandlerThread
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 +62,7 @@ class DanaFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private var pumpStatus = "" private var pumpStatus = ""
private var pumpStatusIcon = "{fa-bluetooth-b}" private var pumpStatusIcon = "{fa-bluetooth-b}"
@ -76,7 +76,7 @@ class DanaFragment : DaggerFragment() {
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
activity?.runOnUiThread { updateGUI() } activity?.runOnUiThread { updateGUI() }
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
} }
} }
@ -131,7 +131,7 @@ class DanaFragment : DaggerFragment() {
@Synchronized @Synchronized
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus disposable += rxBus
.toObservable(EventInitializationChanged::class.java) .toObservable(EventInitializationChanged::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
@ -182,7 +182,7 @@ class DanaFragment : DaggerFragment() {
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
disposable.clear() disposable.clear()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
pumpStatus = "" pumpStatus = ""
pumpStatusIcon = "{fa-bluetooth-b}" pumpStatusIcon = "{fa-bluetooth-b}"
} }

View file

@ -4,7 +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.os.HandlerThread
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -29,11 +29,11 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.utils.WarnColors
import io.reactivex.rxkotlin.plusAssign
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 io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject import javax.inject.Inject
class DiaconnG8Fragment : DaggerFragment() { class DiaconnG8Fragment : DaggerFragment() {
@ -51,7 +51,7 @@ class DiaconnG8Fragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
private var _binding: DiaconnG8FragmentBinding? = null private var _binding: DiaconnG8FragmentBinding? = null
@ -63,7 +63,7 @@ class DiaconnG8Fragment : DaggerFragment() {
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
activity?.runOnUiThread { updateGUI() } activity?.runOnUiThread { updateGUI() }
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
} }
} }
@ -89,7 +89,7 @@ class DiaconnG8Fragment : DaggerFragment() {
@Synchronized @Synchronized
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus disposable += rxBus
.toObservable(EventInitializationChanged::class.java) .toObservable(EventInitializationChanged::class.java)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
@ -140,7 +140,7 @@ class DiaconnG8Fragment : DaggerFragment() {
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
disposable.clear() disposable.clear()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
} }
@Synchronized @Synchronized

View file

@ -5,7 +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.os.HandlerThread
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -68,13 +68,13 @@ class MedtronicFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
activity?.runOnUiThread { updateGUI() } activity?.runOnUiThread { updateGUI() }
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
} }
} }
@ -130,7 +130,7 @@ class MedtronicFragment : DaggerFragment() {
@Synchronized @Synchronized
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus disposable += rxBus
.toObservable(EventRefreshButtonState::class.java) .toObservable(EventRefreshButtonState::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
@ -178,7 +178,7 @@ class MedtronicFragment : DaggerFragment() {
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
disposable.clear() disposable.clear()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
} }
@Synchronized @Synchronized

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash
import android.content.Context import android.content.Context
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.HandlerThread
import android.text.format.DateFormat import android.text.format.DateFormat
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.activities.ErrorHelperActivity.Companion.runAlarm import info.nightscout.androidaps.activities.ErrorHelperActivity.Companion.runAlarm
@ -58,7 +58,6 @@ import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
import org.json.JSONObject import org.json.JSONObject
import java.lang.Exception
import java.time.Duration import java.time.Duration
import java.time.ZonedDateTime import java.time.ZonedDateTime
import java.util.* import java.util.*
@ -91,7 +90,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
@Volatile var bolusCanceled = false @Volatile var bolusCanceled = false
@Volatile var bolusDeliveryInProgress = false @Volatile var bolusDeliveryInProgress = false
private val handler: Handler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var statusChecker: Runnable private lateinit var statusChecker: Runnable
private var nextPodWarningCheck: Long = 0 private var nextPodWarningCheck: Long = 0
@Volatile var stopConnecting: CountDownLatch? = null @Volatile var stopConnecting: CountDownLatch? = null

View file

@ -4,7 +4,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.os.HandlerThread
import android.os.SystemClock import android.os.SystemClock
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
@ -70,6 +70,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
companion object { companion object {
private const val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds private const val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds
private const val PLACEHOLDER = "-" private const val PLACEHOLDER = "-"
private const val MAX_TIME_DEVIATION_MINUTES = 10L private const val MAX_TIME_DEVIATION_MINUTES = 10L
@ -77,13 +78,13 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
private var disposables: CompositeDisposable = CompositeDisposable() private var disposables: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler(Looper.getMainLooper()) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
activity?.runOnUiThread { updateUi() } activity?.runOnUiThread { updateUi() }
loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
} }
} }
@ -180,7 +181,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
disposables += rxBus disposables += rxBus
.toObservable(EventOmnipodDashPumpValuesChanged::class.java) .toObservable(EventOmnipodDashPumpValuesChanged::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
@ -227,7 +228,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
disposables.clear() disposables.clear()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
} }
@Synchronized @Synchronized
@ -247,7 +248,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
} }
private fun updateBluetoothConnectionStatus(event: EventPumpStatusChanged) { private fun updateBluetoothConnectionStatus(event: EventPumpStatusChanged) {
var status = event.getStatus(rh) val status = event.getStatus(rh)
bluetoothStatusBinding.omnipodDashBluetoothStatus.text = status bluetoothStatusBinding.omnipodDashBluetoothStatus.text = status
} }

View file

@ -56,7 +56,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() {
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
private var disposables: CompositeDisposable = CompositeDisposable() private var disposables: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var binding: OmnipodErosPodManagementBinding private lateinit var binding: OmnipodErosPodManagementBinding
@ -100,7 +100,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() {
binding.buttonResetRileylinkConfig.setOnClickListener { binding.buttonResetRileylinkConfig.setOnClickListener {
// TODO improvement: properly disable button until task is finished // TODO improvement: properly disable button until task is finished
loopHandler.post { serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector)) } handler.post { serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector)) }
} }
binding.buttonPlayTestBeep.setOnClickListener { binding.buttonPlayTestBeep.setOnClickListener {

View file

@ -24,9 +24,9 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData
import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewButtonsBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewButtonsBinding
import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewPodInfoBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewPodInfoBinding
import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSilenceAlerts
import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandHandleTimeChange import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandHandleTimeChange
import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandResumeDelivery import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandResumeDelivery
import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSilenceAlerts
import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSuspendDelivery import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSuspendDelivery
import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin
import info.nightscout.androidaps.plugins.pump.omnipod.eros.R import info.nightscout.androidaps.plugins.pump.omnipod.eros.R
@ -86,13 +86,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
private var disposables: CompositeDisposable = CompositeDisposable() private var disposables: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
init { init {
refreshLoop = Runnable { refreshLoop = Runnable {
activity?.runOnUiThread { updateUi() } activity?.runOnUiThread { updateUi() }
loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
} }
} }
@ -136,14 +136,18 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
buttonBinding.buttonResumeDelivery.setOnClickListener { buttonBinding.buttonResumeDelivery.setOnClickListener {
disablePodActionButtons() disablePodActionButtons()
commandQueue.customCommand(CommandResumeDelivery(), commandQueue.customCommand(
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed))) CommandResumeDelivery(),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed))
)
} }
buttonBinding.buttonRefreshStatus.setOnClickListener { buttonBinding.buttonRefreshStatus.setOnClickListener {
disablePodActionButtons() disablePodActionButtons()
commandQueue.customCommand(CommandGetPodStatus(), commandQueue.customCommand(
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)) CommandGetPodStatus(),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)
)
} }
buttonBinding.buttonSilenceAlerts.setOnClickListener { buttonBinding.buttonSilenceAlerts.setOnClickListener {
@ -157,22 +161,26 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
buttonBinding.buttonSuspendDelivery.setOnClickListener { buttonBinding.buttonSuspendDelivery.setOnClickListener {
disablePodActionButtons() disablePodActionButtons()
commandQueue.customCommand(CommandSuspendDelivery(), commandQueue.customCommand(
CommandSuspendDelivery(),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true) DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true)
.messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_suspended_delivery))) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_suspended_delivery))
)
} }
buttonBinding.buttonSetTime.setOnClickListener { buttonBinding.buttonSetTime.setOnClickListener {
disablePodActionButtons() disablePodActionButtons()
commandQueue.customCommand(CommandHandleTimeChange(true), commandQueue.customCommand(
CommandHandleTimeChange(true),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_set_time), true) DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_set_time), true)
.messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated))) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated))
)
} }
} }
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
disposables += rxBus disposables += rxBus
.toObservable(EventRileyLinkDeviceStatusChange::class.java) .toObservable(EventRileyLinkDeviceStatusChange::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
@ -206,7 +214,7 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
disposables.clear() disposables.clear()
loopHandler.removeCallbacks(refreshLoop) handler.removeCallbacks(refreshLoop)
} }
@Synchronized @Synchronized
@ -278,22 +286,26 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
podInfoBinding.firmwareVersion.text = rh.gs(R.string.omnipod_eros_overview_firmware_version_value, podStateManager.pmVersion.toString(), podStateManager.piVersion.toString()) podInfoBinding.firmwareVersion.text = rh.gs(R.string.omnipod_eros_overview_firmware_version_value, podStateManager.pmVersion.toString(), podStateManager.piVersion.toString())
podInfoBinding.timeOnPod.text = readableZonedTime(podStateManager.time) podInfoBinding.timeOnPod.text = readableZonedTime(podStateManager.time)
podInfoBinding.timeOnPod.setTextColor(if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) { podInfoBinding.timeOnPod.setTextColor(
if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) {
Color.RED Color.RED
} else { } else {
Color.WHITE Color.WHITE
}) }
)
val expiresAt = podStateManager.expiresAt val expiresAt = podStateManager.expiresAt
if (expiresAt == null) { if (expiresAt == null) {
podInfoBinding.podExpiryDate.text = PLACEHOLDER podInfoBinding.podExpiryDate.text = PLACEHOLDER
podInfoBinding.podExpiryDate.setTextColor(Color.WHITE) podInfoBinding.podExpiryDate.setTextColor(Color.WHITE)
} else { } else {
podInfoBinding.podExpiryDate.text = readableZonedTime(expiresAt) podInfoBinding.podExpiryDate.text = readableZonedTime(expiresAt)
podInfoBinding.podExpiryDate.setTextColor(if (DateTime.now().isAfter(expiresAt)) { podInfoBinding.podExpiryDate.setTextColor(
if (DateTime.now().isAfter(expiresAt)) {
Color.RED Color.RED
} else { } else {
Color.WHITE Color.WHITE
}) }
)
} }
if (podStateManager.isPodFaulted) { if (podStateManager.isPodFaulted) {
@ -324,11 +336,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble()
podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.reservoirLevel) podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.reservoirLevel)
podInfoBinding.reservoir.setTextColor(if (podStateManager.reservoirLevel < lowReservoirThreshold) { podInfoBinding.reservoir.setTextColor(
if (podStateManager.reservoirLevel < lowReservoirThreshold) {
Color.RED Color.RED
} else { } else {
Color.WHITE Color.WHITE
}) }
)
} }
podInfoBinding.podActiveAlerts.text = if (podStateManager.hasActiveAlerts()) { podInfoBinding.podActiveAlerts.text = if (podStateManager.hasActiveAlerts()) {
@ -402,7 +416,8 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
} }
} }
val podStatusColor = if (!podStateManager.isPodActivationCompleted || podStateManager.isPodDead || podStateManager.isSuspended || (podStateManager.isPodRunning && !podStateManager.isBasalCertain)) { val podStatusColor =
if (!podStateManager.isPodActivationCompleted || podStateManager.isPodDead || podStateManager.isSuspended || (podStateManager.isPodRunning && !podStateManager.isBasalCertain)) {
Color.RED Color.RED
} else { } else {
Color.WHITE Color.WHITE
@ -412,7 +427,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
private fun updateLastBolus() { private fun updateLastBolus() {
if (podStateManager.isPodActivationCompleted && podStateManager.hasLastBolus()) { if (podStateManager.isPodActivationCompleted && podStateManager.hasLastBolus()) {
var text = rh.gs(R.string.omnipod_common_overview_last_bolus_value, omnipodErosPumpPlugin.model().determineCorrectBolusSize(podStateManager.lastBolusAmount), rh.gs(R.string.insulin_unit_shortname), readableDuration(podStateManager.lastBolusStartTime)) var text =
rh.gs(
R.string.omnipod_common_overview_last_bolus_value,
omnipodErosPumpPlugin.model().determineCorrectBolusSize(podStateManager.lastBolusAmount),
rh.gs(R.string.insulin_unit_shortname),
readableDuration(podStateManager.lastBolusStartTime)
)
val textColor: Int val textColor: Int
if (podStateManager.isLastBolusCertain) { if (podStateManager.isLastBolusCertain) {
@ -515,7 +536,9 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
private fun updateSilenceAlertsButton() { private fun updateSilenceAlertsButton() {
if (!omnipodManager.isAutomaticallyAcknowledgeAlertsEnabled && podStateManager.isPodRunning && (podStateManager.hasActiveAlerts() || commandQueue.isCustomCommandInQueue( if (!omnipodManager.isAutomaticallyAcknowledgeAlertsEnabled && podStateManager.isPodRunning && (podStateManager.hasActiveAlerts() || commandQueue.isCustomCommandInQueue(
CommandSilenceAlerts::class.java))) { CommandSilenceAlerts::class.java
))
) {
buttonBinding.buttonSilenceAlerts.visibility = View.VISIBLE buttonBinding.buttonSilenceAlerts.visibility = View.VISIBLE
buttonBinding.buttonSilenceAlerts.isEnabled = rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() buttonBinding.buttonSilenceAlerts.isEnabled = rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty()
} else { } else {
@ -545,8 +568,10 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
private fun displayNotConfiguredDialog() { private fun displayNotConfiguredDialog() {
context?.let { context?.let {
UIRunnable { UIRunnable {
OKDialog.show(it, rh.gs(R.string.omnipod_common_warning), OKDialog.show(
rh.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null) it, rh.gs(R.string.omnipod_common_warning),
rh.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null
)
}.run() }.run()
} }
} }
@ -599,8 +624,10 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
seconds < 24 * 60 * 60 -> { // < 1 day seconds < 24 * 60 * 60 -> { // < 1 day
val minutesLeft = minutes % 60 val minutesLeft = minutes % 60
if (minutesLeft > 0) if (minutesLeft > 0)
return rh.gs(R.string.omnipod_common_time_ago, return rh.gs(
rh.gs(R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_hours, hours, hours), rh.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft))) R.string.omnipod_common_time_ago,
rh.gs(R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_hours, hours, hours), rh.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft))
)
return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_hours, hours, hours)) return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_hours, hours, hours))
} }
@ -608,8 +635,10 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
val days = hours / 24 val days = hours / 24
val hoursLeft = hours % 24 val hoursLeft = hours % 24
if (hoursLeft > 0) if (hoursLeft > 0)
return rh.gs(R.string.omnipod_common_time_ago, return rh.gs(
rh.gs(R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_days, days, days), rh.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft))) R.string.omnipod_common_time_ago,
rh.gs(R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_days, days, days), rh.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft))
)
return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_days, days, days)) return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_days, days, days))
} }
} }

View file

@ -28,7 +28,8 @@ class OrangeLinkImpl @Inject constructor(
var aapsLogger: AAPSLogger, var aapsLogger: AAPSLogger,
var rileyLinkServiceData: RileyLinkServiceData, var rileyLinkServiceData: RileyLinkServiceData,
var rileyLinkUtil: RileyLinkUtil, var rileyLinkUtil: RileyLinkUtil,
var sp: SP) { var sp: SP
) {
lateinit var rileyLinkBLE: RileyLinkBLE lateinit var rileyLinkBLE: RileyLinkBLE
@ -36,8 +37,10 @@ class OrangeLinkImpl @Inject constructor(
if (characteristic.uuid.toString() == GattAttributes.CHARA_NOTIFICATION_ORANGE) { if (characteristic.uuid.toString() == GattAttributes.CHARA_NOTIFICATION_ORANGE) {
val data = characteristic.value val data = characteristic.value
val first = 0xff and data[0].toInt() val first = 0xff and data[0].toInt()
aapsLogger.info(LTag.PUMPBTCOMM, aapsLogger.info(
"OrangeLinkImpl: onCharacteristicChanged " + ByteUtil.shortHexString(characteristic.value) + "=====" + first) LTag.PUMPBTCOMM,
"OrangeLinkImpl: onCharacteristicChanged " + ByteUtil.shortHexString(characteristic.value) + "=====" + first
)
val fv = data[3].toString() + "." + data[4] val fv = data[3].toString() + "." + data[4]
val hv = data[5].toString() + "." + data[6] val hv = data[5].toString() + "." + data[6]
rileyLinkServiceData.versionOrangeFirmware = fv rileyLinkServiceData.versionOrangeFirmware = fv
@ -47,7 +50,6 @@ class OrangeLinkImpl @Inject constructor(
} }
} }
fun resetOrangeLinkData() { fun resetOrangeLinkData() {
rileyLinkServiceData.isOrange = false rileyLinkServiceData.isOrange = false
rileyLinkServiceData.versionOrangeFirmware = null rileyLinkServiceData.versionOrangeFirmware = null
@ -63,7 +65,6 @@ class OrangeLinkImpl @Inject constructor(
} }
} }
fun enableNotifications(): Boolean { fun enableNotifications(): Boolean {
aapsLogger.info(LTag.PUMPBTCOMM, "OrangeLinkImpl::enableNotifications") aapsLogger.info(LTag.PUMPBTCOMM, "OrangeLinkImpl::enableNotifications")
val result: BLECommOperationResult = rileyLinkBLE.setNotification_blocking( val result: BLECommOperationResult = rileyLinkBLE.setNotification_blocking(
@ -78,7 +79,6 @@ class OrangeLinkImpl @Inject constructor(
return true return true
} }
private fun buildScanFilters(): List<ScanFilter> { private fun buildScanFilters(): List<ScanFilter> {
val scanFilterList: MutableList<ScanFilter> = mutableListOf() //ArrayList<*> = ArrayList<Any>() val scanFilterList: MutableList<ScanFilter> = mutableListOf() //ArrayList<*> = ArrayList<Any>()
val scanFilterBuilder = ScanFilter.Builder() val scanFilterBuilder = ScanFilter.Builder()
@ -135,7 +135,7 @@ class OrangeLinkImpl @Inject constructor(
} }
} }
/* /*
private val mLeScanCallback = LeScanCallback { device, _, _ -> private val mLeScanCallback = LeScanCallback { device, _, _ ->
if (rileyLinkServiceData.rileyLinkAddress.equals(device.address)) { if (rileyLinkServiceData.rileyLinkAddress.equals(device.address)) {
stopScan() stopScan()
@ -143,8 +143,8 @@ class OrangeLinkImpl @Inject constructor(
rileyLinkBLE.connectGattInternal() rileyLinkBLE.connectGattInternal()
} }
} }
*/ */
private val handler: Handler = object : Handler(HandlerThread(OrangeLinkImpl::class.java.simpleName + "Handler").also { it.start() }.looper) { private val handler: Handler = object : Handler(HandlerThread(this::class.java.simpleName + "Handler").also { it.start() }.looper) {
override fun handleMessage(msg: Message) { override fun handleMessage(msg: Message) {
super.handleMessage(msg) super.handleMessage(msg)
when (msg.what) { when (msg.what) {
@ -189,6 +189,7 @@ class OrangeLinkImpl @Inject constructor(
} }
companion object { companion object {
const val TIME_OUT = 90 * 1000 const val TIME_OUT = 90 * 1000
const val TIME_OUT_WHAT = 0x12 const val TIME_OUT_WHAT = 0x12
} }

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.interaction.utils; package info.nightscout.androidaps.interaction.utils;
import android.os.Handler; import android.os.Handler;
import android.os.Looper;
import android.os.Message; import android.os.Message;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.MotionEvent; import android.view.MotionEvent;
@ -82,7 +83,7 @@ public class PlusMinusEditText implements View.OnKeyListener,
this.allowZero = allowZero; this.allowZero = allowZero;
this.roundRobin = roundRobin; this.roundRobin = roundRobin;
mHandler = new Handler() { mHandler = new Handler(Looper.getMainLooper()) {
@Override @Override
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
switch (msg.what) { switch (msg.what) {