Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Advantages and limitations of PhoneGap for sensor processing

My Droidcon Tunis 2013 presentation about the effect of the web application model to the battery consumption.

  • Be the first to comment

Advantages and limitations of PhoneGap for sensor processing

  1. 1. Advantages and limitations of PhoneGapfor sensor processingGabor Pallergaborpaller@gmail.comSfonge Ltd.
  2. 2. Alternative application models forAndroid● Basic Android application model → Java-based● Well-hidden in the Android Native DevelopmentKit (NDK) → there is a native application modeltoo● Application models based on other languageshave been proposed but have been rarelydeployed
  3. 3. Browser as mobile applicationruntime● Browser is already acting as mobile application runtime● Just check out the zillions of “how to optimize your website formobile” articles● There were some efforts to make the web applicationmodel the main application model on other platforms→ Bada, Tizen (both very silent recently)→ Firefox OS is making headlines now.● Meanwhile, a modest tool adopted the web model widelyand is in production: PhoneGap
  4. 4. From the helicopter● With PhoneGap, you create traditional, installable applications● PhoneGap does not change the operating system in any way, it acts likea library embedded into the application● A PhoneGap application is implemented mainly in web technologies:HTML, JavaScript, JQuery● Promises:● Lower the cost of mobile development by employing millions of web programmers● Improve the portability of applications by making the web model the greatestcommon denominator (which it is for web sites)
  5. 5. Test programs mentioned in this presentation are available here: paper that this presentation is based on is available here: require free registration to Sfonge site)
  6. 6. PhoneGap projectDisplayed firstThis directory is our playgroundPhoneGap library
  7. 7. index.htmlMain stylesheet incss subdirectoryMain page starts hereLoads PhoneGapLoads application-specificcodeInvokes application-specificinitialization
  8. 8. index.js● Application initialization:var app = {initialize: function() {...},● First listen to onDeviceReady events:var self = this;document.addEventListener(deviceready, self.onDeviceReady, false);● Start invoking PhoneGap functions after the onDeviceReadyevent was fired:onDeviceReady: function() {...},
  9. 9. index.js (2)●In onDeviceReady, initialize your UI ...var shakes = document.getElementById("shakes");app.shakeCounter = 0;shakes.innerHTML = app.shakeCounter.toString();● … start listening for lifecycle events ...document.addEventListener(pause, app.onPause, false);document.addEventListener(resume, app.onResume, false);● … and device events (sensor, in our case)this.accelerometerWatchID = navigator.accelerometer.watchAcceleration(this.onSuccess,this.onError,{ frequency: 50 });
  10. 10. index.js (3)● And then you can handle sensor events:onSuccess: function(acceleration) {var currentTimeStamp = acceleration.timestamp;var x = acceleration.x;var y = acceleration.y;var z = acceleration.z;…}
  11. 11. Brief interlude on context-aware applications
  12. 12. Context-aware applications● Context-aware applications are characterizedby their capability of adapting to changes intheir environment.● More precisely:● Capture environmental changes● Decide whether the change is relevant enough toadapt● Adapt the behavior if the change is relevant
  13. 13. Architecture: sensor adapters● Sensor adapters● Process the input from probes in the environment● Simple: listener to operating system events● Complicated: signal-processing algorithm for a built-in gyroscope sensor
  14. 14. Architecture: decision logic● Decision logic● Rule engine that works on sensor adapter outputsand produces application adaptation decisions● Simple: a set of “if” statements● Complicated: rule inference engine.
  15. 15. Architecture: adaptation logic● Adaptation logic● Makes sure that the high-level context variablesproduced by the decision logic affect the applicationlogic in an application-specific way.● Simple: set of “if” statements built into theapplication logic● Complicated: dynamic component system
  16. 16. Consequence of the applicationmodel● If the sensor adapter processing is offloaded tospecialized co-processors or native code, theapplication model has no impact (no specialprocessing requirements)● If the application code includes sensor adapterprocessing then the application model betterprovide efficient execution because sensorprocessing may be CPU-intensive
  17. 17. Example application● Very simple shake detector● Based on the accelerometer input● High-pass filtering to remove effects of slowmotions, e.g. walking● Peak detector to extract shake signal● “Application adaptation”: simply count
  18. 18. Recap: gravity and motionacceleration
  19. 19. Recap: Absolute value● x, y, z: acceleration vector components● g – value of the gravity acceleration (can beapproximated as 10)a=√x2+ y2+ z2−g
  20. 20. 5 shakesMovementstarts:acceleratingDirection reversesFinal deceleration
  21. 21. Recap: Separating movements inthe frequency domainHzWalking ShakingWalkingWalking+shaking64-point Fast Fourier Transform performed at samples 50 and 200
  22. 22. Applying the filter4 shakes can be reliably recognized
  23. 23. Filter in our example● 6th-order IIR filter(N=6, 12 additionsand 12 multiplicationsper sample)yn=∑i=0Nai xn−i−∑i=1Nbi yn−i
  24. 24. Measurement● Two implementations: Java and webtechnology (PhoneGap).● Measurement:● Phone is restarted● Nexus S, about 50 Hz sampling rate● App is started, sampling is started● Wait 10 sec● Connect with “adb shell” and launch the “top”command● Record the CPU% column
  25. 25. Results:● CPU consumption:● Java implementation: 1%● PhoneGap implementation: 9%● Battery consumption:● PhoneGap : 0.1218%/min → 7.3 %/hour → about 13hours of battery life● Java: 0.072%/min →4.32%/hour → about 23 hours ofbattery life● 60% more consumption, 40% less battery life
  26. 26. PhoneGap “plugins”● PhoneGap is built on the plugin concept● Its own services are also built as plugins andyou can define your own● Plugins are implemented as whatever is “native”in the environment, in case of Android in Java
  27. 27. PhoneGap plugin● Plugin class:public class SamplingServiceAdapter extends CordovaPlugin {…}● Plugin commands:public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {if (action.equals("start")) {…}● Register your plugin in res/xml/config.xml<plugin name="Shake" value="aexp.simpleshakejsplugin.SamplingServiceAdapter"/>
  28. 28. Callbacks● Use CallbackContext to initiate a callback:PluginResult result = new PluginResult(PluginResult.Status.OK,this.getStepCountJSON(count));result.setKeepCallback(true);callbackContext.sendPluginResult(result);● The result must be in JSON:JSONObject r = new JSONObject();r.put("count", count);● Which conforms in JSON to:{ count: 2 }
  29. 29. From the JS side● Sending a command from JS:cordova.exec(this.onShake,this.onError,"Shake","start",[]);● Receiving a callback from native:onShake: function(s) {var count = s.count; // Remember the JSON format we generate!…}
  30. 30. Plugin result● With plugin implementation, the CPU load iscomparable to native implementation (about1%, within measurement error)● No surprise here: if you check the code, you willsee that “CPU-intensive” tasks are implementedsimilarly to the Java version.
  31. 31. So what about the “web model”?● Web model is great for some types of applications (ifyou have the competence)● These are typically UI-intensive applications when somedata is presented to the user and we are then expectinguser interaction● Try to handle moderately “CPU-intensive” tasks inthe web model and you will be in for an unpleasantsurprise● CPU load is directly translated to battery life and I haventeven talked about memory footprint
  32. 32. My advice● If you are an experienced web developer, go forthe web model and implement your apps in theweb model, you will have quick success● Always consider, whether you have “CPU-intensive” tasks – those that happen often andrequire non-trivial calculations● When you are considering a web applicationplatform, always look for native extensionpossibility, just in case. If there is none, beware.
  33. 33. Questions?