<commit_before>package info.nightscout.androidaps.receivers;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.LocalAlertUtils;


/**
 * Created by mike on 07.07.2016.
 */
public class KeepAliveReceiver extends BroadcastReceiver {
    private static Logger log = LoggerFactory.getLogger(L.CORE);
    public static final long STATUS_UPDATE_FREQUENCY = 15 * 60 * 1000L;

    public static void cancelAlarm(Context context) {
        Intent intent = new Intent(context, KeepAliveReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }

    @Override
    public void onReceive(Context context, Intent rIntent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        LocalAlertUtils.shortenSnoozeInterval();
        LocalAlertUtils.checkStaleBGAlert();
        checkPump();
        FabricPrivacy.uploadDailyStats();

        if (L.isEnabled(L.CORE))
            log.debug("KeepAlive received");
        wl.release();
    }

    private void checkPump() {
        final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
        final Profile profile = ProfileFunctions.getInstance().getProfile();
        if (pump != null && profile != null) {
            Date lastConnection = pump.lastDataTime();
            boolean isStatusOutdated = lastConnection.getTime() + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis();
            boolean isBasalOutdated = Math.abs(profile.getBasal() - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep;

            if (L.isEnabled(L.CORE))
                log.debug("Last connection: " + DateUtil.dateAndTimeString(lastConnection));
            LocalAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated);

            if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
                MainApp.bus().post(new EventProfileSwitchChange());
            } else if (isStatusOutdated && !pump.isBusy()) {
                ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Status outdated.", null);
            } else if (isBasalOutdated && !pump.isBusy()) {
                ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Basal outdated.", null);
            }
        }
    }

    //called by MainApp at first app start<commit_msg>false pump unreachable alert workaround<commit_after>package info.nightscout.androidaps.receivers;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;

import com.crashlytics.android.answers.CustomEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.LocalAlertUtils;
import info.nightscout.utils.T;


/**
 * Created by mike on 07.07.2016.
 */
public class KeepAliveReceiver extends BroadcastReceiver {
    private static Logger log = LoggerFactory.getLogger(L.CORE);
    public static final long STATUS_UPDATE_FREQUENCY = T.mins(15).msecs();
    private static long lastReadStatus = 0;
    private static long lastRun = 0;

    public static void cancelAlarm(Context context) {
        Intent intent = new Intent(context, KeepAliveReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }

    @Override
    public void onReceive(Context context, Intent rIntent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        LocalAlertUtils.shortenSnoozeInterval();
        LocalAlertUtils.checkStaleBGAlert();
        checkPump();
        FabricPrivacy.uploadDailyStats();

        if (L.isEnabled(L.CORE))
            log.debug("KeepAlive received");
        wl.release();
    }

    private void checkPump() {
        final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
        final Profile profile = ProfileFunctions.getInstance().getProfile();
        if (pump != null && profile != null) {
            Date lastConnection = pump.lastDataTime();
            boolean isStatusOutdated = lastConnection.getTime() + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis();
            boolean isBasalOutdated = Math.abs(profile.getBasal() - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep;

            if (L.isEnabled(L.CORE))
                log.debug("Last connection: " + DateUtil.dateAndTimeString(lastConnection));
            // sometimes keepalive broadcast stops
            // as as workaround test if readStatus was requested before an alarm is generated
            if (lastReadStatus != 0 && lastReadStatus > System.currentTimeMillis() - T.mins(5).msecs()) {
                LocalAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated);
            }

            if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
                MainApp.bus().post(new EventProfileSwitchChange());
            } else if (isStatusOutdated && !pump.isBusy()) {
                lastReadStatus = System.currentTimeMillis();
                ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Status outdated.", null);
            } else if (isBasalOutdated && !pump.isBusy()) {
                lastReadStatus = System.currentTimeMillis();
                ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Basal outdated.", null);
            }
        }
        if (lastRun != 0 && System.currentTimeMillis() - lastRun > T.mins(10).msecs()) {
            log.error("KeepAlive fail");
            FabricPrivacy.getInstance().logCustom(new CustomEvent("KeepAliveFail"));
        }
        lastRun = System.currentTimeMillis();
    }

    //called by MainApp at first app start
{'fraction_non_alphanumeric': 0.10227996433575341, 'fraction_numerical': 0.005222264679658643, 'mean_word_length': 3.6489046773238605, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4156691', 'n_tokens_mistral': 2252, 'n_tokens_neox': 2187, 'n_words': 406}