Search in sources :

Example 1 with AndroidPreferences

use of com.nightscout.android.preferences.AndroidPreferences in project android-uploader by nightscout.

the class SyncingService method handleActionSync.

/**
     * Handle action Sync in the provided background thread with the provided
     * parameters.
     */
protected void handleActionSync(int numOfPages, Context context, DeviceTransport serialDriver) {
    boolean broadcastSent = false;
    AndroidPreferences preferences = new AndroidPreferences(context);
    Tracker tracker = ((Nightscout) context).getTracker();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NSDownload");
    wl.acquire();
    if (serialDriver != null) {
        AbstractUploaderDevice uploaderDevice = AndroidUploaderDevice.getUploaderDevice(context);
        AbstractDevice device = new DexcomG4(serialDriver, preferences, uploaderDevice);
        ((DexcomG4) device).setNumOfPages(numOfPages);
        ((CdcAcmSerialDriver) serialDriver).setPowerManagementEnabled(preferences.isRootEnabled());
        try {
            DownloadResults results = device.download();
            G4Download download = results.getDownload();
            Uploader uploader = new Uploader(context, preferences);
            boolean uploadStatus;
            if (numOfPages < 20) {
                uploadStatus = uploader.upload(results, 1);
            } else {
                uploadStatus = uploader.upload(results);
            }
            EGVRecord recentEGV;
            if (download.download_status == DownloadStatus.SUCCESS) {
                recentEGV = new EGVRecord(download.sgv.get(download.sgv.size() - 1));
            } else {
                recentEGV = new EGVRecord(-1, TrendArrow.NONE, new Date(), new Date(), G4Noise.NOISE_NONE);
            }
            broadcastSGVToUI(recentEGV, uploadStatus, results.getNextUploadTime() + TIME_SYNC_OFFSET, results.getDisplayTime(), results.getResultArray(), download.receiver_battery);
            broadcastSent = true;
        } catch (ArrayIndexOutOfBoundsException e) {
            Log.wtf("Unable to read from the dexcom, maybe it will work next time", e);
            tracker.send(new HitBuilders.ExceptionBuilder().setDescription("Array Index out of bounds").setFatal(false).build());
        } catch (NegativeArraySizeException e) {
            Log.wtf("Negative array exception from receiver", e);
            tracker.send(new HitBuilders.ExceptionBuilder().setDescription("Negative Array size").setFatal(false).build());
        } catch (IndexOutOfBoundsException e) {
            Log.wtf("IndexOutOfBounds exception from receiver", e);
            tracker.send(new HitBuilders.ExceptionBuilder().setDescription("IndexOutOfBoundsException").setFatal(false).build());
        } catch (CRCFailError e) {
            // FIXME: may consider localizing this catch at a lower level (like ReadData) so that
            // if the CRC check fails on one type of record we can capture the values if it
            // doesn't fail on other types of records. This means we'd need to broadcast back
            // partial results to the UI. Adding it to a lower level could make the ReadData class
            // more difficult to maintain - needs discussion.
            Log.wtf("CRC failed", e);
            tracker.send(new HitBuilders.ExceptionBuilder().setDescription("CRC Failed").setFatal(false).build());
        } catch (Exception e) {
            Log.wtf("Unhandled exception caught", e);
            tracker.send(new HitBuilders.ExceptionBuilder().setDescription("Catch all exception in handleActionSync").setFatal(false).build());
        }
    }
    if (!broadcastSent)
        broadcastSGVToUI();
    wl.release();
}
Also used : AndroidPreferences(com.nightscout.android.preferences.AndroidPreferences) Tracker(com.google.android.gms.analytics.Tracker) HitBuilders(com.google.android.gms.analytics.HitBuilders) DownloadResults(com.nightscout.core.model.DownloadResults) DexcomG4(com.nightscout.core.drivers.DexcomG4) CdcAcmSerialDriver(com.nightscout.android.drivers.USB.CdcAcmSerialDriver) AbstractUploaderDevice(com.nightscout.core.drivers.AbstractUploaderDevice) CRCFailError(com.nightscout.core.dexcom.CRCFailError) EGVRecord(com.nightscout.core.dexcom.records.EGVRecord) Date(java.util.Date) G4Download(com.nightscout.core.model.G4Download) PowerManager(android.os.PowerManager) AbstractDevice(com.nightscout.core.drivers.AbstractDevice) Uploader(com.nightscout.android.upload.Uploader)

Example 2 with AndroidPreferences

use of com.nightscout.android.preferences.AndroidPreferences in project android-uploader by nightscout.

the class SyncingService method startActionSingleSync.

/**
     * Starts this service to perform action Single Sync with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
public static void startActionSingleSync(Context context, int numOfPages) {
    NightscoutPreferences preferences = new AndroidPreferences(context);
    // Exit if the user hasn't selected "I understand"
    if (!preferences.getIUnderstand()) {
        Toast.makeText(context, R.string.message_user_not_understand, Toast.LENGTH_LONG).show();
        return;
    }
    Intent intent = new Intent(context, SyncingService.class);
    intent.setAction(ACTION_SYNC);
    intent.putExtra(SYNC_PERIOD, numOfPages);
    context.startService(intent);
}
Also used : AndroidPreferences(com.nightscout.android.preferences.AndroidPreferences) NightscoutPreferences(com.nightscout.core.preferences.NightscoutPreferences) Intent(android.content.Intent)

Example 3 with AndroidPreferences

use of com.nightscout.android.preferences.AndroidPreferences in project android-uploader by nightscout.

the class SyncingServiceTest method setUp.

@Before
public void setUp() {
    activity = Robolectric.buildActivity(MainActivity.class).create().get();
    prefs = new AndroidPreferences(activity.getApplicationContext());
    shadowActivity = Robolectric.shadowOf(activity);
    mockSyncingService = mock(SyncingService.class);
}
Also used : AndroidPreferences(com.nightscout.android.preferences.AndroidPreferences) Before(org.junit.Before)

Example 4 with AndroidPreferences

use of com.nightscout.android.preferences.AndroidPreferences in project android-uploader by nightscout.

the class SettingsActivity method onActivityResult.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    NightscoutPreferences prefs = new AndroidPreferences(this);
    if (scanResult != null && scanResult.getContents() != null) {
        NSBarcodeConfig barcode = new NSBarcodeConfig(scanResult.getContents());
        if (barcode.hasMongoConfig()) {
            prefs.setMongoUploadEnabled(true);
            if (barcode.getMongoUri().isPresent()) {
                prefs.setMongoClientUri(barcode.getMongoUri().get());
                prefs.setMongoCollection(barcode.getMongoCollection().orNull());
                prefs.setMongoDeviceStatusCollection(barcode.getMongoDeviceStatusCollection().orNull());
            }
        } else {
            prefs.setMongoUploadEnabled(false);
        }
        if (barcode.hasApiConfig()) {
            prefs.setRestApiEnabled(true);
            prefs.setRestApiBaseUris(barcode.getApiUris());
        } else {
            prefs.setRestApiEnabled(false);
        }
        refreshFragments();
    }
}
Also used : AndroidPreferences(com.nightscout.android.preferences.AndroidPreferences) IntentResult(com.google.zxing.integration.android.IntentResult) NightscoutPreferences(com.nightscout.core.preferences.NightscoutPreferences) NSBarcodeConfig(com.nightscout.core.barcode.NSBarcodeConfig)

Example 5 with AndroidPreferences

use of com.nightscout.android.preferences.AndroidPreferences in project android-uploader by nightscout.

the class MainActivity method onCreate.

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "OnCreate called.");
    preferences = new AndroidPreferences(getApplicationContext());
    migrateToNewStyleRestUris();
    ensureSavedUrisAreValid();
    ensureIUnderstandDialogDisplayed();
    // Add timezone ID to ACRA report
    ACRA.getErrorReporter().putCustomData("timezone", TimeZone.getDefault().getID());
    mTracker = ((Nightscout) getApplicationContext()).getTracker();
    mContext = getApplicationContext();
    // Register USB attached/detached and battery changes intents
    IntentFilter deviceStatusFilter = new IntentFilter();
    deviceStatusFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    deviceStatusFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    deviceStatusFilter.addAction(ACTION_POLL);
    registerReceiver(mDeviceStatusReceiver, deviceStatusFilter);
    // Register Broadcast Receiver for response messages from mSyncingServiceIntent service
    mCGMStatusReceiver = new CGMStatusReceiver();
    IntentFilter filter = new IntentFilter(CGMStatusReceiver.PROCESS_RESPONSE);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    registerReceiver(mCGMStatusReceiver, filter);
    toastReceiver = new ToastReceiver();
    IntentFilter toastFilter = new IntentFilter(ToastReceiver.ACTION_SEND_NOTIFICATION);
    toastFilter.addCategory(Intent.CATEGORY_DEFAULT);
    registerReceiver(toastReceiver, toastFilter);
    // Setup UI components
    setContentView(R.layout.activity_main);
    mTextSGV = (TextView) findViewById(R.id.sgValue);
    mTextSGV.setTag(R.string.display_sgv, -1);
    mTextSGV.setTag(R.string.display_trend, 0);
    mTextTimestamp = (TextView) findViewById(R.id.timeAgo);
    mWebView = (WebView) findViewById(R.id.webView);
    mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    webSettings.setUseWideViewPort(false);
    mWebView.setVerticalScrollBarEnabled(false);
    mWebView.setHorizontalScrollBarEnabled(false);
    mWebView.setBackgroundColor(0);
    mWebView.loadUrl("file:///android_asset/index.html");
    statusBarIcons = new StatusBarIcons();
    // If app started due to android.hardware.usb.action.USB_DEVICE_ATTACHED intent, start syncing
    Intent startIntent = getIntent();
    String action = startIntent.getAction();
    if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action) || SyncingService.isG4Connected(getApplicationContext())) {
        statusBarIcons.setUSB(true);
        Log.d(TAG, "Starting syncing in OnCreate...");
        SyncingService.startActionSingleSync(mContext, SyncingService.MIN_SYNC_PAGES);
    } else {
        // reset the top icons to their default state
        statusBarIcons.setDefaults();
    }
    // Check (only once) to see if they have opted in to shared data for research
    if (!preferences.hasAskedForData()) {
        // Prompt user to ask to donate data to research
        AlertDialog.Builder dataDialog = new AlertDialog.Builder(this).setCancelable(false).setTitle(R.string.donate_dialog_title).setMessage(R.string.donate_dialog_summary).setPositiveButton(R.string.donate_dialog_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                mTracker.send(new HitBuilders.EventBuilder("DataDonateQuery", "Yes").build());
                preferences.setDataDonateEnabled(true);
            }
        }).setNegativeButton(R.string.donate_dialog_no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                mTracker.send(new HitBuilders.EventBuilder("DataDonateQuery", "No").build());
                preferences.setDataDonateEnabled(true);
            }
        }).setIcon(R.drawable.ic_launcher);
        dataDialog.show();
        preferences.setAskedForData(true);
    }
    // Report API vs mongo stats once per session
    reportUploadMethods(mTracker);
    pebble = new Pebble(getApplicationContext());
    pebble.setUnits(preferences.getPreferredUnits());
    pebble.setPwdName(preferences.getPwdName());
    uploaderDevice = AndroidUploaderDevice.getUploaderDevice(getApplicationContext());
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent syncIntent = new Intent(MainActivity.ACTION_POLL);
    syncManager = PendingIntent.getBroadcast(getApplicationContext(), 1, syncIntent, 0);
}
Also used : AndroidPreferences(com.nightscout.android.preferences.AndroidPreferences) AlertDialog(android.app.AlertDialog) IntentFilter(android.content.IntentFilter) HitBuilders(com.google.android.gms.analytics.HitBuilders) DialogInterface(android.content.DialogInterface) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) SuppressLint(android.annotation.SuppressLint) Pebble(com.nightscout.android.wearables.Pebble) WebSettings(android.webkit.WebSettings) SuppressLint(android.annotation.SuppressLint)

Aggregations

AndroidPreferences (com.nightscout.android.preferences.AndroidPreferences)7 Before (org.junit.Before)3 Intent (android.content.Intent)2 HitBuilders (com.google.android.gms.analytics.HitBuilders)2 NightscoutPreferences (com.nightscout.core.preferences.NightscoutPreferences)2 SuppressLint (android.annotation.SuppressLint)1 AlertDialog (android.app.AlertDialog)1 PendingIntent (android.app.PendingIntent)1 DialogInterface (android.content.DialogInterface)1 IntentFilter (android.content.IntentFilter)1 PowerManager (android.os.PowerManager)1 WebSettings (android.webkit.WebSettings)1 Tracker (com.google.android.gms.analytics.Tracker)1 IntentResult (com.google.zxing.integration.android.IntentResult)1 CdcAcmSerialDriver (com.nightscout.android.drivers.USB.CdcAcmSerialDriver)1 SettingsActivity (com.nightscout.android.settings.SettingsActivity)1 Uploader (com.nightscout.android.upload.Uploader)1 Pebble (com.nightscout.android.wearables.Pebble)1 NSBarcodeConfig (com.nightscout.core.barcode.NSBarcodeConfig)1 CRCFailError (com.nightscout.core.dexcom.CRCFailError)1