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.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.HandlerThread
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
@ -15,29 +15,30 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.database.AppRepository
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.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.transactions.CancelCurrentOfflineEventIfAnyTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentOfflineEventTransaction
import info.nightscout.androidaps.databinding.DialogLoopBinding
import info.nightscout.androidaps.events.EventPreferenceChange
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.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBus
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.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
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.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
@ -65,7 +66,7 @@ class LoopDialog : DaggerDialogFragment() {
private var showOkCancel: Boolean = true
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
// This property is only valid between onCreateView and
@ -87,8 +88,10 @@ class LoopDialog : DaggerDialogFragment() {
savedInstanceState.putInt("showOkCancel", if (showOkCancel) 1 else 0)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
showOkCancel = bundle.getInt("showOkCancel", 1) == 1
@ -126,35 +129,22 @@ class LoopDialog : DaggerDialogFragment() {
binding.cancel.setOnClickListener { dismiss() }
refreshDialog = Runnable {
scheduleUpdateGUI()
loopHandler.postDelayed(refreshDialog, 15 * 1000L)
runOnUiThread { updateGUI("refreshDialog") }
handler.postDelayed(refreshDialog, 15 * 1000L)
}
loopHandler.postDelayed(refreshDialog, 15 * 1000L)
handler.postDelayed(refreshDialog, 15 * 1000L)
}
@Synchronized
override fun onDestroyView() {
super.onDestroyView()
_binding = null
loopHandler.removeCallbacksAndMessages(null)
handler.removeCallbacksAndMessages(null)
disposable.clear()
}
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
fun updateGUI(from: String) {
if (_binding == null) return
@ -190,7 +180,7 @@ class LoopDialog : DaggerDialogFragment() {
binding.overviewReconnect.visibility = View.VISIBLE
}
!loopPlugin.isEnabled() -> {
!loopPlugin.isEnabled() -> {
binding.overviewLoop.visibility = View.VISIBLE
binding.overviewEnable.visibility = View.VISIBLE
binding.overviewDisable.visibility = View.GONE
@ -219,19 +209,20 @@ class LoopDialog : DaggerDialogFragment() {
binding.overviewOpenloop.visibility = View.VISIBLE
}
apsMode == "lgs" -> {
apsMode == "lgs" -> {
binding.overviewCloseloop.visibility = closedLoopAllowed.value().toVisibility() //show Close loop button only if Close loop allowed
binding.overviewLgsloop.visibility = View.GONE
binding.overviewOpenloop.visibility = View.VISIBLE
}
apsMode == "open" -> {
binding.overviewCloseloop.visibility = closedLoopAllowed2.toVisibility() //show CloseLoop button only if Objective 6 is completed (closedLoopAllowed always false in open loop mode)
apsMode == "open" -> {
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.overviewOpenloop.visibility = View.GONE
}
else -> {
else -> {
binding.overviewCloseloop.visibility = View.GONE
binding.overviewLgsloop.visibility = View.GONE
binding.overviewOpenloop.visibility = View.GONE
@ -317,11 +308,11 @@ class LoopDialog : DaggerDialogFragment() {
})
disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.days(365).msecs(), OfflineEvent.Reason.DISABLE_LOOP))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
return true
}
@ -333,10 +324,10 @@ class LoopDialog : DaggerDialogFragment() {
rxBus.send(EventRefreshOverview("suspend_menu"))
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
return true
}
@ -344,10 +335,10 @@ class LoopDialog : DaggerDialogFragment() {
uel.log(if (v.id == R.id.overview_resume) Action.RESUME else Action.RECONNECT, Sources.LoopDialog)
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
rxBus.send(EventRefreshOverview("suspend_menu"))
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.constraints.objectives
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.SystemClock
import android.view.Gravity
@ -59,7 +60,7 @@ class ObjectivesFragment : DaggerFragment() {
@Inject lateinit var uel: UserEntryLogger
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()

View file

@ -56,19 +56,22 @@ class NSClientPlugin @Inject constructor(
private val nsClientReceiverDelegate: NsClientReceiverDelegate,
private val config: Config,
private val buildHelper: BuildHelper
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(NSClientFragment::class.java.name)
.pluginIcon(R.drawable.ic_nightscout_syncs)
.pluginName(R.string.nsclientinternal)
.shortName(R.string.nsclientinternal_shortname)
.preferencesId(R.xml.pref_nsclientinternal)
.description(R.string.description_ns_client),
) : PluginBase(
PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(NSClientFragment::class.java.name)
.pluginIcon(R.drawable.ic_nightscout_syncs)
.pluginName(R.string.nsclientinternal)
.shortName(R.string.nsclientinternal_shortname)
.preferencesId(R.xml.pref_nsclientinternal)
.alwaysEnabled(config.NSCLIENT)
.visibleByDefault(config.NSCLIENT)
.description(R.string.description_ns_client),
aapsLogger, rh, injector
) {
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()
var textLog = fromHtml("")
var paused = false
@ -78,17 +81,6 @@ class NSClientPlugin @Inject constructor(
val isAllowed: Boolean
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() {
paused = sp.getBoolean(R.string.key_nsclientinternal_paused, false)
autoscroll = sp.getBoolean(R.string.key_nsclientinternal_autoscroll, true)
@ -96,46 +88,53 @@ class NSClientPlugin @Inject constructor(
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
super.onStart()
nsClientReceiverDelegate.grabReceiversState()
disposable.add(rxBus
.toObservable(EventNSClientStatus::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientStatus ->
status = event.getStatus(rh)
rxBus.send(EventNSClientUpdateGUI())
}, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventNSClientStatus::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientStatus ->
status = event.getStatus(rh)
rxBus.send(EventNSClientUpdateGUI())
}, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventNetworkChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventNetworkChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ if (nsClientService != null) context.unbindService(mConnection) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ if (nsClientService != null) context.unbindService(mConnection) }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventNSClientNewLog::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientNewLog ->
addToLog(event)
aapsLogger.debug(LTag.NSCLIENT, event.action + " " + event.logText)
}, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventNSClientNewLog::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientNewLog ->
addToLog(event)
aapsLogger.debug(LTag.NSCLIENT, event.action + " " + event.logText)
}, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventChargingState::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventChargingState::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ev -> nsClientReceiverDelegate.onStatusEvent(ev) }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventNSClientResend::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event -> resend(event.reason) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventNSClientResend::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event -> resend(event.reason) }, fabricPrivacy::logException)
)
}
@ -177,14 +176,14 @@ class NSClientPlugin @Inject constructor(
}
@Synchronized fun clearLog() {
handler?.post {
handler.post {
synchronized(listLog) { listLog.clear() }
rxBus.send(EventNSClientUpdateGUI())
}
}
@Synchronized private fun addToLog(ev: EventNSClientNewLog) {
handler?.post {
handler.post {
synchronized(listLog) {
listLog.add(ev)
// 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 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 dataCounter = 0
private var connectCounter = 0
@ -114,61 +114,69 @@ class NSClientService : DaggerService() {
wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService")
wakeLock?.acquire()
initialize()
disposable.add(rxBus
.toObservable(EventConfigBuilderChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
if (nsEnabled != nsClientPlugin.isEnabled()) {
latestDateInReceivedData = 0
destroy()
initialize()
}
}, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventConfigBuilderChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
if (nsEnabled != nsClientPlugin.isEnabled()) {
latestDateInReceivedData = 0
destroy()
initialize()
}
}, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange ->
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_paused)) {
latestDateInReceivedData = 0
destroy()
initialize()
}
}, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange ->
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_paused)
) {
latestDateInReceivedData = 0
destroy()
initialize()
}
}, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
aapsLogger.debug(LTag.NSCLIENT, "EventAppExit received")
destroy()
stopSelf()
}, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
aapsLogger.debug(LTag.NSCLIENT, "EventAppExit received")
destroy()
stopSelf()
}, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventNSClientRestart::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
latestDateInReceivedData = 0
restart()
}, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(EventNSClientRestart::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
latestDateInReceivedData = 0
restart()
}, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(NSAuthAck::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ack -> processAuthAck(ack) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(NSAuthAck::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ack -> processAuthAck(ack) }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(NSUpdateAck::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ack -> processUpdateAck(ack) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(NSUpdateAck::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ack -> processUpdateAck(ack) }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(NSAddAck::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ack -> processAddAck(ack) }, fabricPrivacy::logException)
disposable.add(
rxBus
.toObservable(NSAddAck::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ ack -> processAddAck(ack) }, fabricPrivacy::logException)
)
}
@ -183,7 +191,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientAddAckWorker::class.java)
.setInputData(dataWorker.storeInputData(ack, null))
.build())
.build()
)
}
private fun processUpdateAck(ack: NSUpdateAck) {
@ -191,7 +200,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientUpdateRemoveAckWorker::class.java)
.setInputData(dataWorker.storeInputData(ack, null))
.build())
.build()
)
}
private fun processAuthAck(ack: NSAuthAck) {
@ -448,7 +458,7 @@ class NSClientService : DaggerService() {
}
}
private val onDataUpdate = Emitter.Listener { args ->
handler?.post {
handler.post {
// val powerManager = getSystemService(POWER_SERVICE) as PowerManager
// val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
// "AndroidAPS:NSClientService_onDataUpdate")
@ -474,7 +484,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue(
OneTimeWorkRequest.Builder(LocalProfilePlugin.NSProfileWorker::class.java)
.setInputData(dataWorker.storeInputData(profileStoreJson, null))
.build())
.build()
)
xDripBroadcast.sendProfile(profileStoreJson)
}
}
@ -492,7 +503,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientAddUpdateWorker::class.java)
.setInputData(dataWorker.storeInputData(addedOrUpdatedTreatments, null))
.build())
.build()
)
xDripBroadcast.sendTreatments(addedOrUpdatedTreatments)
}
}
@ -509,7 +521,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue(
OneTimeWorkRequest.Builder(FoodWorker::class.java)
.setInputData(dataWorker.storeInputData(foods, null))
.build())
.build()
)
}
if (data.has("mbgs")) {
val mbgArray = data.getJSONArray("mbgs")
@ -517,7 +530,8 @@ class NSClientService : DaggerService() {
dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientMbgWorker::class.java)
.setInputData(dataWorker.storeInputData(mbgArray, null))
.build())
.build()
)
}
if (data.has("cals")) {
val cals = data.getJSONArray("cals")
@ -527,9 +541,11 @@ class NSClientService : DaggerService() {
if (data.has("sgvs")) {
val sgvs = data.getJSONArray("sgvs")
if (sgvs.length() > 0) rxBus.send(EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"))
dataWorker.enqueue(OneTimeWorkRequest.Builder(NSClientSourceWorker::class.java)
.setInputData(dataWorker.storeInputData(sgvs, null))
.build())
dataWorker.enqueue(
OneTimeWorkRequest.Builder(NSClientSourceWorker::class.java)
.setInputData(dataWorker.storeInputData(sgvs, null))
.build()
)
xDripBroadcast.sendSgvs(sgvs)
}
rxBus.send(EventNSClientNewLog("LAST", dateUtil.dateAndTimeString(latestDateInReceivedData)))
@ -552,8 +568,12 @@ class NSClientService : DaggerService() {
message.put("_id", _id)
message.put("data", data)
socket?.emit("dbUpdate", message, NSUpdateAck("dbUpdate", _id, aapsLogger, rxBus, originalObject))
rxBus.send(EventNSClientNewLog("DBUPDATE $collection", "Sent " + originalObject.javaClass.simpleName + " " +
"" + _id + " " + data + progress))
rxBus.send(
EventNSClientNewLog(
"DBUPDATE $collection", "Sent " + originalObject.javaClass.simpleName + " " +
"" + _id + " " + data + progress
)
)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
@ -580,7 +600,7 @@ class NSClientService : DaggerService() {
fun resend(reason: String) {
if (!isConnected || !hasWriteAuth) return
handler?.post {
handler.post {
if (socket?.connected() != true) return@post
if (lastAckTime > System.currentTimeMillis() - 10 * 1000L) {
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())
}
}
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.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
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 var axisWidth: Int = 0
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 secondaryGraphsLabel = ArrayList<TextView>()
@ -158,7 +158,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
// pre-process landscape mode
val screenWidth = dm.widthPixels

View file

@ -39,7 +39,7 @@ class VirtualPumpFragment : DaggerFragment() {
private val disposable = CompositeDisposable()
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
@ -54,9 +54,9 @@ class VirtualPumpFragment : DaggerFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
}
@Synchronized
@Synchronized
override fun onResume() {
super.onResume()
disposable += rxBus

View file

@ -50,7 +50,7 @@ class GlunovoPlugin @Inject constructor(
aapsLogger, resourceHelper, injector
), 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 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 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() {
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() {
super.onStop()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
disposable.clear()
}

View file

@ -45,7 +45,7 @@ class RandomBgPlugin @Inject constructor(
aapsLogger, rh, injector
), 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
companion object {
@ -58,7 +58,7 @@ class RandomBgPlugin @Inject constructor(
init {
refreshLoop = Runnable {
loopHandler.postDelayed(refreshLoop, T.mins(interval).msecs())
handler.postDelayed(refreshLoop, T.mins(interval).msecs())
handleNewData()
}
}
@ -74,13 +74,13 @@ class RandomBgPlugin @Inject constructor(
override fun onStart() {
super.onStart()
loopHandler.postDelayed(refreshLoop, T.mins(interval).msecs())
handler.postDelayed(refreshLoop, T.mins(interval).msecs())
disposable.clear()
}
override fun onStop() {
super.onStop()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
}
override fun specialEnableCondition(): Boolean {

View file

@ -77,7 +77,7 @@ class AutomationPlugin @Inject constructor(
var executionLog: MutableList<String> = 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
companion object {
@ -89,7 +89,7 @@ class AutomationPlugin @Inject constructor(
init {
refreshLoop = Runnable {
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()
loadFromSP()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus
.toObservable(EventPreferenceChange::class.java)
@ -148,7 +148,7 @@ class AutomationPlugin @Inject constructor(
override fun onStop() {
disposable.clear()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
locationServiceHelper.stopService(context)
super.onStop()
}

View file

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

View file

@ -4,7 +4,7 @@ import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.HandlerThread
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
@ -62,7 +62,7 @@ class DanaFragment : DaggerFragment() {
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 var pumpStatus = ""
private var pumpStatusIcon = "{fa-bluetooth-b}"
@ -76,7 +76,7 @@ class DanaFragment : DaggerFragment() {
init {
refreshLoop = Runnable {
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
override fun onResume() {
super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus
.toObservable(EventInitializationChanged::class.java)
.observeOn(aapsSchedulers.main)
@ -182,7 +182,7 @@ class DanaFragment : DaggerFragment() {
override fun onPause() {
super.onPause()
disposable.clear()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
pumpStatus = ""
pumpStatusIcon = "{fa-bluetooth-b}"
}

View file

@ -4,7 +4,7 @@ import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.HandlerThread
import android.view.LayoutInflater
import android.view.View
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.T
import info.nightscout.androidaps.utils.WarnColors
import io.reactivex.rxkotlin.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
class DiaconnG8Fragment : DaggerFragment() {
@ -51,7 +51,7 @@ class DiaconnG8Fragment : DaggerFragment() {
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 var _binding: DiaconnG8FragmentBinding? = null
@ -63,7 +63,7 @@ class DiaconnG8Fragment : DaggerFragment() {
init {
refreshLoop = Runnable {
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
override fun onResume() {
super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus
.toObservable(EventInitializationChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
@ -140,7 +140,7 @@ class DiaconnG8Fragment : DaggerFragment() {
override fun onPause() {
super.onPause()
disposable.clear()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
}
@Synchronized

View file

@ -5,7 +5,7 @@ import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.HandlerThread
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
@ -68,13 +68,13 @@ class MedtronicFragment : DaggerFragment() {
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
init {
refreshLoop = Runnable {
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
override fun onResume() {
super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
handler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += rxBus
.toObservable(EventRefreshButtonState::class.java)
.observeOn(aapsSchedulers.main)
@ -178,7 +178,7 @@ class MedtronicFragment : DaggerFragment() {
override fun onPause() {
super.onPause()
disposable.clear()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
}
@Synchronized

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.HandlerThread
import android.text.format.DateFormat
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.activities.ErrorHelperActivity.Companion.runAlarm
@ -58,7 +58,6 @@ import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.json.JSONObject
import java.lang.Exception
import java.time.Duration
import java.time.ZonedDateTime
import java.util.*
@ -91,7 +90,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
@Volatile var bolusCanceled = 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 var nextPodWarningCheck: Long = 0
@Volatile var stopConnecting: CountDownLatch? = null

View file

@ -4,7 +4,7 @@ import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.HandlerThread
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
@ -70,6 +70,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
@Inject lateinit var buildHelper: BuildHelper
companion object {
private const val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds
private const val PLACEHOLDER = "-"
private const val MAX_TIME_DEVIATION_MINUTES = 10L
@ -77,13 +78,13 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
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
init {
refreshLoop = Runnable {
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() {
super.onResume()
loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
disposables += rxBus
.toObservable(EventOmnipodDashPumpValuesChanged::class.java)
.observeOn(aapsSchedulers.main)
@ -227,7 +228,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
override fun onPause() {
super.onPause()
disposables.clear()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
}
@Synchronized
@ -247,7 +248,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
}
private fun updateBluetoothConnectionStatus(event: EventPumpStatusChanged) {
var status = event.getStatus(rh)
val status = event.getStatus(rh)
bluetoothStatusBinding.omnipodDashBluetoothStatus.text = status
}
@ -266,7 +267,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
Color.RED
connectionSuccessPercentage < 90 && podStateManager.successfulConnectionAttemptsAfterRetries > 50 ->
Color.YELLOW
else ->
else ->
Color.WHITE
}
bluetoothStatusBinding.omnipodDashBluetoothConnectionQuality.setTextColor(connectionStatsColor)
@ -332,9 +333,9 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
when {
!podStateManager.sameTimeZone ->
Color.MAGENTA
timeDeviationTooBig ->
timeDeviationTooBig ->
Color.YELLOW
else ->
else ->
Color.WHITE
}
)
@ -347,11 +348,11 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
?: PLACEHOLDER
podInfoBinding.podExpiryDate.setTextColor(
when {
expiresAt != null && ZonedDateTime.now().isAfter(expiresAt) ->
expiresAt != null && ZonedDateTime.now().isAfter(expiresAt) ->
Color.RED
expiresAt != null && ZonedDateTime.now().isAfter(expiresAt.minusHours(4)) ->
Color.YELLOW
else ->
else ->
Color.WHITE
}
)
@ -429,21 +430,21 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
private fun translatedActiveAlert(alert: AlertType): String {
val id = when (alert) {
AlertType.LOW_RESERVOIR ->
AlertType.LOW_RESERVOIR ->
R.string.omnipod_common_alert_low_reservoir
AlertType.EXPIRATION ->
AlertType.EXPIRATION ->
R.string.omnipod_common_alert_expiration_advisory
AlertType.EXPIRATION_IMMINENT ->
R.string.omnipod_common_alert_expiration
AlertType.USER_SET_EXPIRATION ->
R.string.omnipod_common_alert_expiration_advisory
AlertType.AUTO_OFF ->
AlertType.AUTO_OFF ->
R.string.omnipod_common_alert_shutdown_imminent
AlertType.SUSPEND_IN_PROGRESS ->
R.string.omnipod_common_alert_delivery_suspended
AlertType.SUSPEND_ENDED ->
AlertType.SUSPEND_ENDED ->
R.string.omnipod_common_alert_delivery_suspended
else ->
else ->
R.string.omnipod_common_alert_unknown_alert
}
return rh.gs(id)
@ -456,7 +457,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
System.currentTimeMillis() -
podStateManager.lastUpdatedSystem,
)
)
)
val lastConnectionColor =
if (omnipodDashPumpPlugin.isUnreachableAlertTimeoutExceeded(getPumpUnreachableTimeout().toMillis())) {
@ -505,9 +506,9 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
val podStatusColor = when {
!podStateManager.isActivationCompleted || podStateManager.isPodKaput || podStateManager.isSuspended ->
Color.RED
podStateManager.activeCommand != null ->
podStateManager.activeCommand != null ->
Color.YELLOW
else ->
else ->
Color.WHITE
}
podInfoBinding.podStatus.setTextColor(podStatusColor)
@ -602,7 +603,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
private fun updateRefreshStatusButton() {
buttonBinding.buttonRefreshStatus.isEnabled =
podStateManager.isUniqueIdSet &&
isQueueEmpty()
isQueueEmpty()
}
private fun updateResumeDeliveryButton() {
@ -669,15 +670,15 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
val minutes = duration.toMinutes().toInt()
val seconds = duration.seconds
when {
seconds < 10 -> {
seconds < 10 -> {
return rh.gs(R.string.omnipod_common_moments_ago)
}
seconds < 60 -> {
seconds < 60 -> {
return rh.gs(R.string.omnipod_common_less_than_a_minute_ago)
}
seconds < 60 * 60 -> { // < 1 hour
seconds < 60 * 60 -> { // < 1 hour
return rh.gs(
R.string.omnipod_common_time_ago,
rh.gq(R.plurals.omnipod_common_minutes, minutes, minutes)
@ -701,7 +702,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() {
)
}
else -> {
else -> {
val days = hours / 24
val hoursLeft = hours % 24
if (hoursLeft > 0)

View file

@ -56,7 +56,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() {
@Inject lateinit var aapsSchedulers: AapsSchedulers
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
@ -100,7 +100,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() {
binding.buttonResetRileylinkConfig.setOnClickListener {
// TODO improvement: properly disable button until task is finished
loopHandler.post { serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector)) }
handler.post { serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector)) }
}
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.omnipod.common.databinding.OmnipodCommonOverviewButtonsBinding
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.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.eros.OmnipodErosPumpPlugin
import info.nightscout.androidaps.plugins.pump.omnipod.eros.R
@ -86,13 +86,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
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
init {
refreshLoop = Runnable {
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 {
disablePodActionButtons()
commandQueue.customCommand(CommandResumeDelivery(),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed)))
commandQueue.customCommand(
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 {
disablePodActionButtons()
commandQueue.customCommand(CommandGetPodStatus(),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false))
commandQueue.customCommand(
CommandGetPodStatus(),
DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)
)
}
buttonBinding.buttonSilenceAlerts.setOnClickListener {
@ -157,56 +161,60 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
buttonBinding.buttonSuspendDelivery.setOnClickListener {
disablePodActionButtons()
commandQueue.customCommand(CommandSuspendDelivery(),
commandQueue.customCommand(
CommandSuspendDelivery(),
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 {
disablePodActionButtons()
commandQueue.customCommand(CommandHandleTimeChange(true),
commandQueue.customCommand(
CommandHandleTimeChange(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() {
super.onResume()
loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS)
disposables += rxBus
.toObservable(EventRileyLinkDeviceStatusChange::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({
updateRileyLinkStatus()
updatePodActionButtons()
}, fabricPrivacy::logException)
updateRileyLinkStatus()
updatePodActionButtons()
}, fabricPrivacy::logException)
disposables += rxBus
.toObservable(EventOmnipodErosPumpValuesChanged::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({
updateOmnipodStatus()
updatePodActionButtons()
}, fabricPrivacy::logException)
updateOmnipodStatus()
updatePodActionButtons()
}, fabricPrivacy::logException)
disposables += rxBus
.toObservable(EventQueueChanged::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({
updateQueueStatus()
updatePodActionButtons()
}, fabricPrivacy::logException)
updateQueueStatus()
updatePodActionButtons()
}, fabricPrivacy::logException)
disposables += rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({
updatePodActionButtons()
}, fabricPrivacy::logException)
updatePodActionButtons()
}, fabricPrivacy::logException)
updateUi()
}
override fun onPause() {
super.onPause()
disposables.clear()
loopHandler.removeCallbacks(refreshLoop)
handler.removeCallbacks(refreshLoop)
}
@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.timeOnPod.text = readableZonedTime(podStateManager.time)
podInfoBinding.timeOnPod.setTextColor(if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) {
Color.RED
} else {
Color.WHITE
})
podInfoBinding.timeOnPod.setTextColor(
if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) {
Color.RED
} else {
Color.WHITE
}
)
val expiresAt = podStateManager.expiresAt
if (expiresAt == null) {
podInfoBinding.podExpiryDate.text = PLACEHOLDER
podInfoBinding.podExpiryDate.setTextColor(Color.WHITE)
} else {
podInfoBinding.podExpiryDate.text = readableZonedTime(expiresAt)
podInfoBinding.podExpiryDate.setTextColor(if (DateTime.now().isAfter(expiresAt)) {
Color.RED
} else {
Color.WHITE
})
podInfoBinding.podExpiryDate.setTextColor(
if (DateTime.now().isAfter(expiresAt)) {
Color.RED
} else {
Color.WHITE
}
)
}
if (podStateManager.isPodFaulted) {
@ -324,11 +336,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble()
podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.reservoirLevel)
podInfoBinding.reservoir.setTextColor(if (podStateManager.reservoirLevel < lowReservoirThreshold) {
Color.RED
} else {
Color.WHITE
})
podInfoBinding.reservoir.setTextColor(
if (podStateManager.reservoirLevel < lowReservoirThreshold) {
Color.RED
} else {
Color.WHITE
}
)
}
podInfoBinding.podActiveAlerts.text = if (podStateManager.hasActiveAlerts()) {
@ -402,17 +416,24 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
}
}
val podStatusColor = if (!podStateManager.isPodActivationCompleted || podStateManager.isPodDead || podStateManager.isSuspended || (podStateManager.isPodRunning && !podStateManager.isBasalCertain)) {
Color.RED
} else {
Color.WHITE
}
val podStatusColor =
if (!podStateManager.isPodActivationCompleted || podStateManager.isPodDead || podStateManager.isSuspended || (podStateManager.isPodRunning && !podStateManager.isBasalCertain)) {
Color.RED
} else {
Color.WHITE
}
podInfoBinding.podStatus.setTextColor(podStatusColor)
}
private fun updateLastBolus() {
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
if (podStateManager.isLastBolusCertain) {
@ -515,7 +536,9 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
private fun updateSilenceAlertsButton() {
if (!omnipodManager.isAutomaticallyAcknowledgeAlertsEnabled && podStateManager.isPodRunning && (podStateManager.hasActiveAlerts() || commandQueue.isCustomCommandInQueue(
CommandSilenceAlerts::class.java))) {
CommandSilenceAlerts::class.java
))
) {
buttonBinding.buttonSilenceAlerts.visibility = View.VISIBLE
buttonBinding.buttonSilenceAlerts.isEnabled = rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty()
} else {
@ -545,8 +568,10 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
private fun displayNotConfiguredDialog() {
context?.let {
UIRunnable {
OKDialog.show(it, rh.gs(R.string.omnipod_common_warning),
rh.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null)
OKDialog.show(
it, rh.gs(R.string.omnipod_common_warning),
rh.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null
)
}.run()
}
}
@ -599,8 +624,10 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
seconds < 24 * 60 * 60 -> { // < 1 day
val minutesLeft = minutes % 60
if (minutesLeft > 0)
return rh.gs(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.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))
}
@ -608,8 +635,10 @@ class OmnipodErosOverviewFragment : DaggerFragment() {
val days = hours / 24
val hoursLeft = hours % 24
if (hoursLeft > 0)
return rh.gs(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.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))
}
}

View file

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

View file

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