NetworkChangeReceiver refactor

This commit is contained in:
Milos Kozak 2020-03-31 09:20:58 +02:00
parent 969f713914
commit 2aea486409
15 changed files with 207 additions and 156 deletions

View file

@ -4,6 +4,7 @@ import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver
import info.nightscout.androidaps.receivers.KeepAliveReceiver import info.nightscout.androidaps.receivers.KeepAliveReceiver
import info.nightscout.androidaps.receivers.NetworkChangeReceiver
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver
@Module @Module
@ -11,6 +12,7 @@ import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver
abstract class ReceiversModule { abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver @ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver
@ContributesAndroidInjector abstract fun contributesNetworkChangeReceiver(): NetworkChangeReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
} }

View file

@ -6,9 +6,11 @@ class EventNetworkChange : Event() {
var mobileConnected = false var mobileConnected = false
var wifiConnected = false var wifiConnected = false
var vpnConnected = false
var ssid = "" var ssid = ""
var roaming = false var roaming = false
var metered = false
fun connectedSsid(): String { fun connectedSsid(): String {
return StringUtils.removeSurroundingQuotes(ssid) return StringUtils.removeSurroundingQuotes(ssid)

View file

@ -15,17 +15,7 @@ class EventPreferenceChange : Event {
changedKey = resourceHelper.gs(resourceID) changedKey = resourceHelper.gs(resourceID)
} }
@Deprecated("use injected version")
constructor(resources: Resources, id: Int) {
changedKey == resources.getString(id)
}
fun isChanged(resourceHelper: ResourceHelper, id: Int): Boolean { fun isChanged(resourceHelper: ResourceHelper, id: Int): Boolean {
return changedKey == resourceHelper.gs(id) return changedKey == resourceHelper.gs(id)
} }
@Deprecated("use injected version")
fun isChanged(resources: Resources, id: Int): Boolean {
return changedKey == resources.getString(id)
}
} }

View file

@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProg
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask
import info.nightscout.androidaps.receivers.NetworkChangeReceiver import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.setupwizard.events.EventSWUpdate
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
@ -48,6 +48,7 @@ class ObjectivesFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var objectivesPlugin: ObjectivesPlugin
@Inject lateinit var receiverStatusStore: ReceiverStatusStore
private val objectivesAdapter = ObjectivesAdapter() private val objectivesAdapter = ObjectivesAdapter()
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
@ -223,7 +224,7 @@ class ObjectivesFragment : DaggerFragment() {
holder.accomplished.text = resourceHelper.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn)) holder.accomplished.text = resourceHelper.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn))
holder.accomplished.setTextColor(-0x3e3e3f) holder.accomplished.setTextColor(-0x3e3e3f)
holder.verify.setOnClickListener { holder.verify.setOnClickListener {
NetworkChangeReceiver.grabNetworkStatus(context) receiverStatusStore.updateNetworkStatus()
if (objectives_fake.isChecked) { if (objectives_fake.isChecked) {
objective.accomplishedOn = DateUtil.now() objective.accomplishedOn = DateUtil.now()
scrollToCurrentObjective() scrollToCurrentObjective()
@ -257,12 +258,12 @@ class ObjectivesFragment : DaggerFragment() {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99))
} }
} }
}, NetworkChangeReceiver.isConnected()) }, receiverStatusStore.isConnected)
}.start() }.start()
} }
} }
holder.start.setOnClickListener { holder.start.setOnClickListener {
NetworkChangeReceiver.grabNetworkStatus(context) receiverStatusStore.updateNetworkStatus()
if (objectives_fake.isChecked) { if (objectives_fake.isChecked) {
objective.startedOn = DateUtil.now() objective.startedOn = DateUtil.now()
scrollToCurrentObjective() scrollToCurrentObjective()
@ -292,7 +293,7 @@ class ObjectivesFragment : DaggerFragment() {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99))
} }
} }
}, NetworkChangeReceiver.isConnected()) }, receiverStatusStore.isConnected)
}.start() }.start()
} }
holder.unStart.setOnClickListener { holder.unStart.setOnClickListener {

View file

@ -11,10 +11,14 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithE
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel
import info.nightscout.androidaps.receivers.NetworkChangeReceiver import info.nightscout.androidaps.receivers.NetworkChangeReceiver
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONObject import org.json.JSONObject
import javax.inject.Inject
class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) { class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) {
@Inject lateinit var receiverStatusStore: ReceiverStatusStore
var ssid = InputString(injector) var ssid = InputString(injector)
var comparator = Comparator(injector) var comparator = Comparator(injector)
@ -39,7 +43,7 @@ class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val eventNetworkChange = NetworkChangeReceiver.getLastEvent() ?: return false val eventNetworkChange = receiverStatusStore.lastNetworkEvent ?: return false
if (!eventNetworkChange.wifiConnected && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { if (!eventNetworkChange.wifiConnected && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true return true

View file

@ -71,7 +71,7 @@ public class NSClientPlugin extends PluginBase {
public NSClientService nsClientService = null; public NSClientService nsClientService = null;
private NsClientReceiverDelegate nsClientReceiverDelegate = new NsClientReceiverDelegate(); private NsClientReceiverDelegate nsClientReceiverDelegate;
@Inject @Inject
public NSClientPlugin( public NSClientPlugin(
@ -80,7 +80,8 @@ public class NSClientPlugin extends PluginBase {
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
Context context, Context context,
SP sp SP sp,
NsClientReceiverDelegate nsClientReceiverDelegate
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
@ -97,6 +98,7 @@ public class NSClientPlugin extends PluginBase {
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.context = context; this.context = context;
this.sp = sp; this.sp = sp;
this.nsClientReceiverDelegate = nsClientReceiverDelegate;
if (Config.NSCLIENT) { if (Config.NSCLIENT) {
getPluginDescription().alwaysEnabled(true).visibleByDefault(true); getPluginDescription().alwaysEnabled(true).visibleByDefault(true);

View file

@ -1,50 +1,71 @@
package info.nightscout.androidaps.plugins.general.nsclient; package info.nightscout.androidaps.plugins.general.nsclient;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import info.nightscout.androidaps.MainApp; import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventChargingState; import info.nightscout.androidaps.events.EventChargingState;
import info.nightscout.androidaps.events.EventNetworkChange; import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.receivers.ChargingStateReceiver; import info.nightscout.androidaps.receivers.ChargingStateReceiver;
import info.nightscout.androidaps.receivers.NetworkChangeReceiver; import info.nightscout.androidaps.receivers.NetworkChangeReceiver;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.receivers.ReceiverStatusStore;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton
class NsClientReceiverDelegate { class NsClientReceiverDelegate {
private boolean allowedChargingState = true; private boolean allowedChargingState = true;
private boolean allowedNetworkState = true; private boolean allowedNetworkState = true;
boolean allowed = true; boolean allowed = true;
void grabReceiversState() { private AAPSLogger aapsLogger;
Context context = MainApp.instance().getApplicationContext(); private Context context;
private RxBusWrapper rxBus;
private ResourceHelper resourceHelper;
private SP sp;
private ReceiverStatusStore receiverStatusStore;
EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(context); @Inject
if (event != null) RxBus.Companion.getINSTANCE().send(event); public NsClientReceiverDelegate(
AAPSLogger aapsLogger,
Context context,
RxBusWrapper rxBus,
ResourceHelper resourceHelper,
SP sp,
ReceiverStatusStore receiverStatusStore
) {
this.aapsLogger = aapsLogger;
this.context = context;
this.rxBus = rxBus;
this.resourceHelper = resourceHelper;
this.sp = sp;
this.receiverStatusStore = receiverStatusStore;
}
void grabReceiversState() {
receiverStatusStore.updateNetworkStatus();
EventChargingState eventChargingState = ChargingStateReceiver.grabChargingState(context); EventChargingState eventChargingState = ChargingStateReceiver.grabChargingState(context);
if (eventChargingState != null) RxBus.Companion.getINSTANCE().send(eventChargingState); rxBus.send(eventChargingState);
} }
void onStatusEvent(EventPreferenceChange ev) { void onStatusEvent(EventPreferenceChange ev) {
if (ev.isChanged(MainApp.resources(), R.string.key_ns_wifionly) || if (ev.isChanged(resourceHelper, R.string.key_ns_wifionly) ||
ev.isChanged(MainApp.resources(), R.string.key_ns_wifi_ssids) || ev.isChanged(resourceHelper, R.string.key_ns_wifi_ssids) ||
ev.isChanged(MainApp.resources(), R.string.key_ns_allowroaming) ev.isChanged(resourceHelper, R.string.key_ns_allowroaming)
) { ) {
EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext()); receiverStatusStore.updateNetworkStatus();
if (event != null) } else if (ev.isChanged(resourceHelper, R.string.key_ns_chargingonly)) {
RxBus.Companion.getINSTANCE().send(event); EventChargingState event = ChargingStateReceiver.grabChargingState(context);
} else if (ev.isChanged(MainApp.resources(), R.string.key_ns_chargingonly)) { rxBus.send(event);
EventChargingState event = ChargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext());
if (event != null)
RxBus.Companion.getINSTANCE().send(event);
} }
} }
@ -70,12 +91,12 @@ class NsClientReceiverDelegate {
boolean newAllowedState = allowedChargingState && allowedNetworkState; boolean newAllowedState = allowedChargingState && allowedNetworkState;
if (newAllowedState != allowed) { if (newAllowedState != allowed) {
allowed = newAllowedState; allowed = newAllowedState;
RxBus.Companion.getINSTANCE().send(new EventPreferenceChange(MainApp.gs(R.string.key_nsclientinternal_paused))); rxBus.send(new EventPreferenceChange(resourceHelper.gs(R.string.key_nsclientinternal_paused)));
} }
} }
boolean calculateStatus(final EventChargingState ev) { boolean calculateStatus(final EventChargingState ev) {
boolean chargingOnly = SP.getBoolean(R.string.key_ns_chargingonly, false); boolean chargingOnly = sp.getBoolean(R.string.key_ns_chargingonly, false);
boolean newAllowedState = true; boolean newAllowedState = true;
if (!ev.isCharging() && chargingOnly) { if (!ev.isCharging() && chargingOnly) {
@ -86,9 +107,9 @@ class NsClientReceiverDelegate {
} }
boolean calculateStatus(final EventNetworkChange ev) { boolean calculateStatus(final EventNetworkChange ev) {
boolean wifiOnly = SP.getBoolean(R.string.key_ns_wifionly, false); boolean wifiOnly = sp.getBoolean(R.string.key_ns_wifionly, false);
String allowedSSIDs = SP.getString(R.string.key_ns_wifi_ssids, ""); String allowedSSIDs = sp.getString(R.string.key_ns_wifi_ssids, "");
boolean allowRoaming = SP.getBoolean(R.string.key_ns_allowroaming, true); boolean allowRoaming = sp.getBoolean(R.string.key_ns_allowroaming, true);
boolean newAllowedState = true; boolean newAllowedState = true;

View file

@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolS
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolUpdateGUI import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolUpdateGUI
import info.nightscout.androidaps.plugins.general.tidepool.utils.RateLimit import info.nightscout.androidaps.plugins.general.tidepool.utils.RateLimit
import info.nightscout.androidaps.receivers.ChargingStateReceiver import info.nightscout.androidaps.receivers.ChargingStateReceiver
import info.nightscout.androidaps.receivers.NetworkChangeReceiver import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
@ -51,7 +51,8 @@ class TidepoolPlugin @Inject constructor(
private val tidepoolUploader: TidepoolUploader, private val tidepoolUploader: TidepoolUploader,
private val uploadChunk: UploadChunk, private val uploadChunk: UploadChunk,
private val sp: SP, private val sp: SP,
private val rateLimit: RateLimit private val rateLimit: RateLimit,
private val receiverStatusStore: ReceiverStatusStore
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.pluginName(R.string.tidepool) .pluginName(R.string.tidepool)
@ -103,7 +104,7 @@ class TidepoolPlugin @Inject constructor(
uploadChunk.setLastEnd(bgReading.date) uploadChunk.setLastEnd(bgReading.date)
if (isEnabled(PluginType.GENERAL) if (isEnabled(PluginType.GENERAL)
&& (!sp.getBoolean(R.string.key_tidepool_only_while_charging, false) || ChargingStateReceiver.isCharging()) && (!sp.getBoolean(R.string.key_tidepool_only_while_charging, false) || ChargingStateReceiver.isCharging())
&& (!sp.getBoolean(R.string.key_tidepool_only_while_unmetered, false) || NetworkChangeReceiver.isWifiConnected()) && (!sp.getBoolean(R.string.key_tidepool_only_while_unmetered, false) || receiverStatusStore.isWifiConnected)
&& rateLimit.rateLimit("tidepool-new-data-upload", T.mins(4).secs().toInt())) && rateLimit.rateLimit("tidepool-new-data-upload", T.mins(4).secs().toInt()))
doUpload() doUpload()
}, { }, {

View file

@ -1,83 +0,0 @@
package info.nightscout.androidaps.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import androidx.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
public class NetworkChangeReceiver extends BroadcastReceiver {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.CORE);
private static EventNetworkChange lastEvent = null;
@Override
public void onReceive(final Context context, final Intent intent) {
EventNetworkChange event = grabNetworkStatus(context);
if (event != null)
RxBus.Companion.getINSTANCE().send(event);
}
@Nullable
public static EventNetworkChange grabNetworkStatus(final Context context) {
EventNetworkChange event = new EventNetworkChange();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) return null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
event.setWifiConnected(true);
WifiManager wifiManager = (WifiManager) MainApp.instance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
event.setSsid(wifiInfo.getSSID());
}
if (L.isEnabled(L.CORE))
log.debug("NETCHANGE: Wifi connected. SSID: " + event.connectedSsid());
}
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
event.setMobileConnected(true);
event.setRoaming(activeNetwork.isRoaming());
if (L.isEnabled(L.CORE))
log.debug("NETCHANGE: Mobile connected. Roaming: " + event.getRoaming());
}
} else {
if (L.isEnabled(L.CORE))
log.debug("NETCHANGE: Disconnected.");
}
lastEvent = event;
return event;
}
public static boolean isWifiConnected() {
return lastEvent != null && lastEvent.getWifiConnected();
}
public static boolean isConnected() {
return lastEvent != null && (lastEvent.getWifiConnected() || lastEvent.getMobileConnected());
}
public static EventNetworkChange getLastEvent() {
return lastEvent;
}
}

View file

@ -0,0 +1,59 @@
package info.nightscout.androidaps.receivers
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.wifi.SupplicantState
import android.net.wifi.WifiManager
import dagger.android.DaggerBroadcastReceiver
import info.nightscout.androidaps.events.EventNetworkChange
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import javax.inject.Inject
class NetworkChangeReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var receiverStatusStore: ReceiverStatusStore
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
rxBus.send(grabNetworkStatus(context, aapsLogger))
}
fun grabNetworkStatus(context: Context, aapsLogger: AAPSLogger): EventNetworkChange {
val event = EventNetworkChange()
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networks: Array<Network> = cm.allNetworks
networks.forEach {
val capabilities = cm.getNetworkCapabilities(it)
event.wifiConnected = event.wifiConnected || (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
event.mobileConnected = event.mobileConnected || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
event.vpnConnected = event.vpnConnected || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
// if (event.vpnConnected) aapsLogger.debug(LTag.CORE, "NETCHANGE: VPN connected.")
if (event.wifiConnected) {
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiInfo = wifiManager.connectionInfo
if (wifiInfo.supplicantState == SupplicantState.COMPLETED) {
event.ssid = wifiInfo.ssid
// aapsLogger.debug(LTag.CORE, "NETCHANGE: Wifi connected. SSID: ${event.connectedSsid()}")
}
}
if (event.mobileConnected) {
event.mobileConnected = true
event.roaming = event.roaming || !capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)
event.metered = event.metered || !capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
aapsLogger.debug(LTag.CORE, "NETCHANGE: Mobile connected. Roaming: ${event.roaming} Metered: ${event.metered}")
}
// aapsLogger.info(LTag.CORE, "Network: $it")
}
aapsLogger.debug(LTag.CORE, event.toString())
receiverStatusStore.lastNetworkEvent = event
return event
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.receivers
import android.content.Context
import android.content.Intent
import info.nightscout.androidaps.events.EventNetworkChange
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ReceiverStatusStore @Inject constructor(val context: Context) {
var lastNetworkEvent: EventNetworkChange? = null
val isWifiConnected: Boolean
get() = lastNetworkEvent?.wifiConnected ?: false
val isConnected: Boolean
get() = lastNetworkEvent?.wifiConnected ?: false || lastNetworkEvent?.mobileConnected ?: false
fun updateNetworkStatus() {
context.sendBroadcast(Intent(context, NetworkChangeReceiver::class.java))
}
}

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.receivers; package info.nightscout.androidaps.receivers
/** /**
* Forward received SMS intents. This is a separate class, because unlike local broadcasts handled by DataReceiver, * Forward received SMS intents. This is a separate class, because unlike local broadcasts handled by DataReceiver,
* receiving SMS requires a special permission in the manifest, which necessitates a separate receiver. * receiving SMS requires a special permission in the manifest, which necessitates a separate receiver.
*/ */
public class SmsReceiver extends DataReceiver {} class SmsReceiver : DataReceiver()

View file

@ -1,9 +1,11 @@
package info.nightscout.androidaps.plugins.general.automation.triggers package info.nightscout.androidaps.plugins.general.automation.triggers
import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.events.EventNetworkChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -13,9 +15,11 @@ import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabe
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.services.LastLocationDataContainer import info.nightscout.androidaps.services.LastLocationDataContainer
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 org.junit.Before
import org.mockito.Mock import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
@ -27,6 +31,14 @@ open class TriggerTestBase : TestBaseWithProfile() {
@Mock lateinit var locationDataContainer: LastLocationDataContainer @Mock lateinit var locationDataContainer: LastLocationDataContainer
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Mock lateinit var context: Context
lateinit var receiverStatusStore: ReceiverStatusStore
@Before
fun prepareMock1() {
receiverStatusStore = ReceiverStatusStore(context)
}
var injector: HasAndroidInjector = HasAndroidInjector { var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -44,6 +56,9 @@ open class TriggerTestBase : TestBaseWithProfile() {
if (it is TriggerBg) { if (it is TriggerBg) {
it.profileFunction = profileFunction it.profileFunction = profileFunction
} }
if (it is TriggerWifiSsid) {
it.receiverStatusStore = receiverStatusStore
}
if (it is InputBg) { if (it is InputBg) {
it.profileFunction = profileFunction it.profileFunction = profileFunction
} }

View file

@ -30,7 +30,7 @@ class TriggerWifiSsidTest : TriggerTestBase() {
@Test fun shouldRunTest() { @Test fun shouldRunTest() {
val e = EventNetworkChange() val e = EventNetworkChange()
PowerMockito.`when`(NetworkChangeReceiver.getLastEvent()).thenReturn(e) receiverStatusStore.lastNetworkEvent = e
var t: TriggerWifiSsid = TriggerWifiSsid(injector).setValue("aSSID").comparator(Comparator.Compare.IS_EQUAL) var t: TriggerWifiSsid = TriggerWifiSsid(injector).setValue("aSSID").comparator(Comparator.Compare.IS_EQUAL)
e.wifiConnected = false e.wifiConnected = false
Assert.assertFalse(t.shouldRun()) Assert.assertFalse(t.shouldRun())
@ -45,7 +45,7 @@ class TriggerWifiSsidTest : TriggerTestBase() {
Assert.assertTrue(t.shouldRun()) Assert.assertTrue(t.shouldRun())
// no network data // no network data
PowerMockito.`when`(NetworkChangeReceiver.getLastEvent()).thenReturn(null) receiverStatusStore.lastNetworkEvent = null
Assert.assertFalse(t.shouldRun()) Assert.assertFalse(t.shouldRun())
} }

View file

@ -6,7 +6,11 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.events.EventChargingState import info.nightscout.androidaps.events.EventChargingState
import info.nightscout.androidaps.events.EventNetworkChange import info.nightscout.androidaps.events.EventNetworkChange
import info.nightscout.androidaps.utils.SP import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert import org.junit.Assert
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
@ -16,6 +20,7 @@ import org.mockito.ArgumentMatchers.anyBoolean
import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyLong import org.mockito.ArgumentMatchers.anyLong
import org.mockito.ArgumentMatchers.anyString import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock import org.mockito.Mockito.mock
@ -27,30 +32,39 @@ import org.powermock.modules.junit4.PowerMockRunner
@PrepareForTest(MainApp::class, SP::class, Context::class) @PrepareForTest(MainApp::class, SP::class, Context::class)
class NsClientReceiverDelegateTest : TestBase() { class NsClientReceiverDelegateTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger
@Mock lateinit var context: Context
@Mock lateinit var sp: SP
@Mock lateinit var resourceHelper: ResourceHelper
lateinit var receiverStatusStore : ReceiverStatusStore
val rxBus: RxBusWrapper = RxBusWrapper()
private var sut: NsClientReceiverDelegate? = null private var sut: NsClientReceiverDelegate? = null
@Before fun prepare() { @Before fun prepare() {
receiverStatusStore = ReceiverStatusStore(context)
System.setProperty("disableFirebase", "true") System.setProperty("disableFirebase", "true")
PowerMockito.mockStatic(MainApp::class.java) PowerMockito.mockStatic(MainApp::class.java)
val mainApp: MainApp = mock(MainApp::class.java) val mainApp: MainApp = mock(MainApp::class.java)
`when`(MainApp.instance()).thenReturn(mainApp) `when`(MainApp.instance()).thenReturn(mainApp)
PowerMockito.mockStatic(SP::class.java) PowerMockito.mockStatic(SP::class.java)
`when`(SP.getLong(anyInt(), anyLong())).thenReturn(0L) `when`(sp.getLong(anyInt(), anyLong())).thenReturn(0L)
`when`(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false) `when`(sp.getBoolean(anyInt(), anyBoolean())).thenReturn(false)
`when`(SP.getInt(anyInt(), anyInt())).thenReturn(0) `when`(sp.getInt(anyInt(), anyInt())).thenReturn(0)
`when`(SP.getString(anyInt(), anyString())).thenReturn("") `when`(sp.getString(anyInt(), anyString())).thenReturn("")
sut = NsClientReceiverDelegate() sut = NsClientReceiverDelegate(aapsLogger, context, rxBus, resourceHelper, sp, receiverStatusStore)
} }
@Test fun testCalculateStatusChargingState() { @Test fun testCalculateStatusChargingState() {
PowerMockito.mockStatic(SP::class.java) PowerMockito.mockStatic(SP::class.java)
Mockito.`when`(SP.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(false) Mockito.`when`(sp.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(false)
var ev = EventChargingState(true) var ev = EventChargingState(true)
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
ev = EventChargingState(false) ev = EventChargingState(false)
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
Mockito.`when`(SP.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(true) Mockito.`when`(sp.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(true)
ev = EventChargingState(true) ev = EventChargingState(true)
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
ev = EventChargingState(false) ev = EventChargingState(false)
@ -61,15 +75,15 @@ class NsClientReceiverDelegateTest : TestBase() {
PowerMockito.mockStatic(SP::class.java) PowerMockito.mockStatic(SP::class.java)
// wifiOnly = false // wifiOnly = false
// allowRoaming = false as well // allowRoaming = false as well
Mockito.`when`(SP.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(false) Mockito.`when`(sp.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(false)
Mockito.`when`(SP.getString(ArgumentMatchers.anyInt(), ArgumentMatchers.anyString())).thenReturn("") Mockito.`when`(sp.getString(ArgumentMatchers.anyInt(), ArgumentMatchers.anyString())).thenReturn("")
val ev = EventNetworkChange() val ev = EventNetworkChange()
ev.ssid = "<unknown ssid>" ev.ssid = "<unknown ssid>"
ev.mobileConnected = true ev.mobileConnected = true
ev.wifiConnected = true ev.wifiConnected = true
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
ev.ssid = "test" ev.ssid = "test"
Mockito.`when`(SP.getString(ArgumentMatchers.anyInt(), ArgumentMatchers.anyString())).thenReturn("\"test\"") Mockito.`when`(sp.getString(ArgumentMatchers.anyInt(), ArgumentMatchers.anyString())).thenReturn("\"test\"")
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
ev.ssid = "\"test\"" ev.ssid = "\"test\""
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
@ -78,7 +92,7 @@ class NsClientReceiverDelegateTest : TestBase() {
// wifiOnly = true // wifiOnly = true
// allowRoaming = true as well // allowRoaming = true as well
Mockito.`when`(SP.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(true) Mockito.`when`(sp.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(true)
ev.wifiConnected = true ev.wifiConnected = true
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
ev.wifiConnected = false ev.wifiConnected = false
@ -86,39 +100,39 @@ class NsClientReceiverDelegateTest : TestBase() {
// wifiOnly = false // wifiOnly = false
// allowRoaming = false as well // allowRoaming = false as well
Mockito.`when`(SP.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(false) Mockito.`when`(sp.getBoolean(ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean())).thenReturn(false)
ev.wifiConnected = false ev.wifiConnected = false
ev.roaming = true ev.roaming = true
Assert.assertTrue(!sut!!.calculateStatus(ev)) Assert.assertTrue(!sut!!.calculateStatus(ev))
// wifiOnly = false // wifiOnly = false
// allowRoaming = true // allowRoaming = true
Mockito.`when`(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false) Mockito.`when`(sp.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false)
Mockito.`when`(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true) Mockito.`when`(sp.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true)
ev.wifiConnected = false ev.wifiConnected = false
ev.roaming = true ev.roaming = true
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
// wifiOnly = true // wifiOnly = true
// allowRoaming = true // allowRoaming = true
Mockito.`when`(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true) Mockito.`when`(sp.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true)
Mockito.`when`(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true) Mockito.`when`(sp.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true)
ev.wifiConnected = false ev.wifiConnected = false
ev.roaming = true ev.roaming = true
Assert.assertTrue(!sut!!.calculateStatus(ev)) Assert.assertTrue(!sut!!.calculateStatus(ev))
// wifiOnly = true // wifiOnly = true
// allowRoaming = true // allowRoaming = true
Mockito.`when`(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true) Mockito.`when`(sp.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true)
Mockito.`when`(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true) Mockito.`when`(sp.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true)
ev.wifiConnected = true ev.wifiConnected = true
ev.roaming = true ev.roaming = true
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))
// wifiOnly = false // wifiOnly = false
// allowRoaming = false // allowRoaming = false
Mockito.`when`(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false) Mockito.`when`(sp.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false)
Mockito.`when`(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(false) Mockito.`when`(sp.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(false)
ev.wifiConnected = true ev.wifiConnected = true
ev.roaming = true ev.roaming = true
Assert.assertTrue(sut!!.calculateStatus(ev)) Assert.assertTrue(sut!!.calculateStatus(ev))