Search in sources :

Example 1 with CaratSampleDB

use of edu.berkeley.cs.amplab.carat.android.storage.CaratSampleDB in project carat by amplab.

the class SamplerService method takeSampleIfBatteryLevelChanged.

/**
     * Some phones receive the batteryChanged very very often. We are interested 
     * only in changes of the battery level
     * @param intent  The parent intent (the one passed from the Sampler)
	 *				  (with one extra field set, called 'distance')
	 *				  This intent should be the intent which is passed by the Android system to your 
	 *                broadcast receiver (which is registered with the BATTERY_CHANGED action).
	 *                In our case, this broadcast receiver is 'Sampler'.                 
     * @param context
     */
private void takeSampleIfBatteryLevelChanged(Intent intent, Context context) {
    distance = intent.getDoubleExtra("distance", 0);
    // Make sure our new sample doesn't have a zero value as its current battery level
    if (SamplingLibrary.getCurrentBatteryLevel() > 0) {
        CaratSampleDB sampleDB = CaratSampleDB.getInstance(context);
        Sample lastSample = sampleDB.getLastSample(context);
        if (lastSample != null) {
            SamplingLibrary.setLastBatteryLevel(lastSample.getBatteryLevel());
        } else if (SamplingLibrary.getLastBatteryLevel(context) == 0) {
            Log.i(TAG, "The last sample is null (all samples have been uploaded and deleted " + "from the local DB) , and the last battery level is not set yet " + "(the first ever sample). About to take a new sample. " + "currentBatteryLevel=" + SamplingLibrary.getCurrentBatteryLevel());
            // before taking the first sample in a batch, first record the battery level
            SamplingLibrary.setLastBatteryLevel(SamplingLibrary.getCurrentBatteryLevel());
            // take a sample and store it in the database
            this.getSample(context, intent, lastSample, sampleDB);
            notify(context);
        }
        /*
			 * Read the battery levels again, they are now changed. We just
			 * changed the last battery level (in the previous block of code).
			 * The current battery level might also have been changed while the
			 * device has been taking a sample.
			 */
        boolean batteryLevelChanged = SamplingLibrary.getLastBatteryLevel(context) != SamplingLibrary.getCurrentBatteryLevel();
        if (batteryLevelChanged) {
            /* among all occurrence of the event BATTERY_CHANGED, only take a sample 
				 * whenever a battery PERCENTAGE CHANGE happens 
				 * (BATTERY_CHANGED happens whenever the battery temperature or voltage of other parameters change)
				 */
            Log.i(TAG, "The battery percentage changed. About to take a new sample " + "(currentBatteryLevel=" + SamplingLibrary.getCurrentBatteryLevel() + ", lastBatteryLevel=" + SamplingLibrary.getLastBatteryLevel(context) + ")");
            // take a sample and store it in the database
            this.getSample(context, intent, lastSample, sampleDB);
            notify(context);
        } else {
            Log.d(TAG, "NO battery percentage change. currentBatteryLevel=" + SamplingLibrary.getCurrentBatteryLevel());
        }
    } else {
        Log.d(TAG, "current battery level = 0");
    }
}
Also used : Sample(edu.berkeley.cs.amplab.carat.thrift.Sample) CaratSampleDB(edu.berkeley.cs.amplab.carat.android.storage.CaratSampleDB)

Example 2 with CaratSampleDB

use of edu.berkeley.cs.amplab.carat.android.storage.CaratSampleDB in project carat by amplab.

the class SampleSender method sendSamples.

public static void sendSamples(CaratApplication app) {
    synchronized (sendLock) {
        Context c = app.getApplicationContext();
        String networkStatus = SamplingLibrary.getNetworkStatus(c);
        String networkType = SamplingLibrary.getNetworkType(c);
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(c);
        final boolean useWifiOnly = p.getBoolean(Constants.WIFI_ONLY_PREFERENCE_KEY, false);
        Log.i("wifi-preference-SampleSender", String.valueOf(useWifiOnly));
        boolean connected = (!useWifiOnly && networkStatus == SamplingLibrary.NETWORKSTATUS_CONNECTED) || networkType.equals("WIFI");
        if (connected) {
            CaratSampleDB db = CaratSampleDB.getInstance(c);
            int samples = db.countSamples();
            /* Click Tracking: Track sample sending. */
            String uuId = p.getString(CaratApplication.getRegisteredUuid(), "UNKNOWN");
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("count", samples + "");
            ClickTracking.track(uuId, "sendingsamples", options, c);
            /* End Click Tracking: Track sample sending. */
            int successSum = 0;
            for (int batches = 0; batches < Constants.COMMS_MAX_BATCHES && batches < samples / Constants.COMMS_MAX_UPLOAD_BATCH + 1; batches++) {
                SortedMap<Long, Sample> map = CaratSampleDB.getInstance(c).queryOldestSamples(Constants.COMMS_MAX_UPLOAD_BATCH);
                if (map.size() > 0) {
                    int progress = (int) (successSum * 1.0 / samples * 100.0);
                    CaratApplication.setActionProgress(progress, successSum + "/" + samples + " " + app.getString(R.string.samplesreported), false);
                    if (app.commManager != null) {
                        int tries = 0;
                        while (tries < 2) {
                            try {
                                int success = app.commManager.uploadSamples(map.values());
                                tries = 2;
                                // FlurryAgent.logEvent("UploadSamples");
                                Log.d(TAG, "Uploaded " + success + " samples out of " + map.size());
                                if (success > 0)
                                    CaratApplication.storage.samplesReported(success);
                                Sample last = map.get(map.lastKey());
                                /*
									 * converting (to human readable date-time format) 
									 * the "timestamp" of the last sample (which is
									 * uploaded now, and should be deleted along the other 
									 * uploaded samples). The "timestamp" is computed this way:
									 * CurrentTimeMillis / 1000 
									 * (see getSample() in SamplingLibrary)
									 */
                                // in currentTimeMillis
                                long lastSampleTime = (long) last.getTimestamp() * 1000;
                                SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
                                Date resultdate = new Date(lastSampleTime);
                                Log.d(TAG, "Deleting " + success + " samples older than " + sdf.format(resultdate));
                                /*
                                     * Log.i(TAG, "Sent samples:"); for (Sample k:
                                     * map.values()){ Log.i(TAG, k.getTimestamp() +
                                     * " " + k.getBatteryLevel()); }
                                     */
                                SortedSet<Long> uploaded = new TreeSet<Long>();
                                int i = 0;
                                for (Long s : map.keySet()) {
                                    if (i < success)
                                        uploaded.add(s);
                                    i += 1;
                                }
                                int deleted = CaratSampleDB.getInstance(c).deleteSamples(uploaded);
                                // Log.d(TAG, "Deleted " + deleted + " samples.");
                                successSum += success;
                            } catch (Throwable th) {
                                // Any sort of malformed response, too short
                                // string, etc...
                                Log.w(TAG, "Failed to refresh reports: " + th + (tries < 1 ? "Trying again now" : TRY_AGAIN), th);
                                tries++;
                            }
                        }
                    } else {
                        Log.w(TAG, "CommunicationManager is not ready yet." + TRY_AGAIN);
                    }
                } else {
                    Log.w(TAG, "No samples to send." + TRY_AGAIN);
                }
            }
            /* Click Tracking: Track sample sending. */
            options.put("count", successSum + "");
            ClickTracking.track(uuId, "sentsamples", options, c);
        /* End Click Tracking: Track sample sending. */
        }
    /* else if (networkStatus
                    .equals(SamplingLibrary.NETWORKSTATUS_CONNECTING)) {
                Log.w(TAG, "Network status: " + networkStatus
                        + ", trying again in 10s.");
                connecting = true;
            } else {
                Log.w(TAG, "Network status: " + networkStatus + TRY_AGAIN);
                connecting = false;
            }
            if (connecting) {
                // wait for wifi to come up
                try {
                    Thread.sleep(CaratApplication.COMMS_WIFI_WAIT);
                } catch (InterruptedException e1) {
                    // ignore
                }
                connecting = false;
            } else {
                try {
                    Thread.sleep(CaratApplication.COMMS_INTERVAL);
                } catch (InterruptedException e) {
                    // wait for wifi to come up
                    try {
                        Thread.sleep(CaratApplication.COMMS_WIFI_WAIT);
                    } catch (InterruptedException e1) {
                        // ignore
                    }
                }
            }*/
    }
}
Also used : Context(android.content.Context) SharedPreferences(android.content.SharedPreferences) HashMap(java.util.HashMap) Sample(edu.berkeley.cs.amplab.carat.thrift.Sample) CaratSampleDB(edu.berkeley.cs.amplab.carat.android.storage.CaratSampleDB) Date(java.util.Date) TreeSet(java.util.TreeSet) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

CaratSampleDB (edu.berkeley.cs.amplab.carat.android.storage.CaratSampleDB)2 Sample (edu.berkeley.cs.amplab.carat.thrift.Sample)2 Context (android.content.Context)1 SharedPreferences (android.content.SharedPreferences)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 TreeSet (java.util.TreeSet)1