incubator-callback-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From fil...@apache.org
Subject webworks commit: [CB-465] Simplified accel plugin (still based on Drews implementation) to just start/stop actions.
Date Fri, 18 May 2012 22:01:19 GMT
Updated Branches:
  refs/heads/465 b28459c1a -> 9590c2069


[CB-465] Simplified accel plugin (still based on Drews implementation) to just start/stop
actions.


Project: http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/commit/9590c206
Tree: http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/tree/9590c206
Diff: http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/diff/9590c206

Branch: refs/heads/465
Commit: 9590c20690abb4eb06176cdf99d6f88b0f925739
Parents: b28459c
Author: Fil Maj <maj.fil@gmail.com>
Authored: Fri May 18 15:04:47 2012 -0700
Committer: Fil Maj <maj.fil@gmail.com>
Committed: Fri May 18 15:04:47 2012 -0700

----------------------------------------------------------------------
 .../cordova/accelerometer/Accelerometer.java       |  176 +++------------
 javascript/cordova.blackberry.js                   |  101 +++++++--
 2 files changed, 106 insertions(+), 171 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/9590c206/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java b/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
index 09e6aef..2088122 100644
--- a/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
+++ b/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
@@ -37,9 +37,8 @@ import org.apache.cordova.util.Logger;
 public class Accelerometer extends Plugin implements AccelerometerListener {
     private static final String LOG_TAG = "Accelerometer: ";
 
-    private static final String ACTION_GET_ACCELERATION = "getAcceleration";
-    private static final String ACTION_ADD_WATCH = "addWatch";
-    private static final String ACTION_CLEAR_WATCH = "clearWatch";
+    private static final String ACTION_START = "start";
+    private static final String ACTION_STOP = "stop";
 
     private static final int STOPPED = 0;
     private static final int STARTING = 1;
@@ -58,58 +57,29 @@ public class Accelerometer extends Plugin implements AccelerometerListener
{
     private long initTime = 0;
 
     /**
-     * Hash of all the listeners created, keyed on callback ids.
+     * Reference to single start callbackid
      */
-    private final Vector callbackIds = new Vector();
-    private final Hashtable watchIds = new Hashtable();
+    private String callbackId;
 
     public PluginResult execute(String action, JSONArray args, String callbackId) {
         PluginResult result;
-        try {
-            if (!AccelerometerSensor.isSupported()) {
-                result = new PluginResult(
-                        PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION,
-                        "Accelerometer sensor not supported");
-            } else if (ACTION_GET_ACCELERATION.equals(action)) {
-                result = getAcceleration(callbackId);
-            } else if (ACTION_ADD_WATCH.equals(action)) {
-                String watchId = args.getString(0);
-                result = addWatch(watchId, callbackId);
-            } else if (ACTION_CLEAR_WATCH.equals(action)) {
-                String watchId = args.getString(0);
-                result = clearWatch(watchId);
-            } else {
-                result = new PluginResult(PluginResult.Status.INVALID_ACTION,
-                        "Accelerometer: Invalid action:" + action);
-            }
-        } catch (JSONException e) {
-            result = new PluginResult(PluginResult.Status.JSON_EXCEPTION,
-                    e.getMessage());
+        if (!AccelerometerSensor.isSupported()) {
+            result = new PluginResult(
+                    PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION,
+                    "Accelerometer sensor not supported");
+        } else if (ACTION_START.equals(action)) {
+            result = start(callbackId);
+        } else if (ACTION_STOP.equals(action)) {
+            result = stop();
+        } else {
+            result = new PluginResult(PluginResult.Status.INVALID_ACTION,
+                    "Accelerometer: Invalid action:" + action);
         }
 
         return result;
     }
 
     /**
-     * Identifies if action to be executed returns a value and should be run
-     * synchronously.
-     *
-     * @param action
-     *            The action to execute
-     * @return T=returns value
-     */
-    public boolean isSynch(String action) {
-        if (ACTION_GET_ACCELERATION.equals(action) && state == RUNNING) {
-            return true;
-        } else if (ACTION_ADD_WATCH.equals(action) && state == RUNNING) {
-            return true;
-        } else if (ACTION_CLEAR_WATCH.equals(action)) {
-            return true;
-        }
-        return false;
-    }
-
-    /**
      * Implements the AccelerometerListener method. We listen for the purpose of
      * closing the application's accelerometer sensor channel after timeout has
      * been exceeded.
@@ -161,15 +131,15 @@ public class Accelerometer extends Plugin implements AccelerometerListener
{
      * Called when Plugin is destroyed.
      */
     public void onDestroy() {
-        // Close out the call back IDs and stop.
-        sendResult(true, new PluginResult(PluginResult.Status.NO_RESULT), false);
+        stop();
     }
 
     /**
      * Adds a SystemListener to listen for changes to the battery state. The
      * listener is only registered if one has not already been added.
      */
-    private int addListener() {
+    private PluginResult start(String callbackId) {
+        this.callbackId = callbackId;
         if (_rawDataChannel == null || !_rawDataChannel.isOpen()) {
             _rawDataChannel = AccelerometerSensor
                     .openRawDataChannel(Application.getApplication());
@@ -181,75 +151,8 @@ public class Accelerometer extends Plugin implements AccelerometerListener
{
             Logger.log(LOG_TAG + "sensor listener added");
         }
 
-        return state;
-    }
-
-    /**
-     * Track the specified watch ID and start the accelerometer channel if it
-     * hasn't been started.
-     *
-     * @param watchId
-     * @param callbackId
-     * @return
-     */
-    private synchronized PluginResult addWatch(String watchId, String callbackId) {
-        watchIds.put(watchId, callbackId);
-        addListener();
-        PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT,
-                "");
+        PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
         result.setKeepCallback(true);
-
-        return result;
-    }
-
-    /**
-     * Removes the specified watch ID and stops the accelerometer channel if
-     * this it was the last active listener.
-     *
-     * @param watchId
-     * @return
-     */
-    private synchronized PluginResult clearWatch(String watchId) {
-        if (watchIds.containsKey(watchId)) {
-            watchIds.remove(watchId);
-            if (watchIds.size() == 0 && callbackIds.size() == 0) {
-                stop();
-            }
-        }
-        return new PluginResult(PluginResult.Status.OK, "");
-    }
-
-    /**
-     * If the sensor is active, return the last acquired accelerometer data,
-     * otherwise start the sensor and listen for data.
-     *
-     * @return AccelerometerData with last acceleration data
-     */
-    private synchronized PluginResult getAcceleration(String callbackId) {
-        PluginResult result;
-
-        if (state != RUNNING) {
-            callbackIds.addElement(callbackId);
-            addListener();
-            result = new PluginResult(PluginResult.Status.NO_RESULT, "");
-            result.setKeepCallback(true);
-        } else {
-            // get the last acceleration
-            AccelerometerData accelData = _rawDataChannel
-                    .getAccelerometerData();
-            JSONObject accel = new JSONObject();
-            try {
-                accel.put("x", normalize(accelData.getLastXAcceleration()));
-                accel.put("y", normalize(accelData.getLastYAcceleration()));
-                accel.put("z", normalize(accelData.getLastZAcceleration()));
-                accel.put("timestamp", accelData.getLastTimestamp());
-                result = new PluginResult(PluginResult.Status.OK, accel);
-            } catch (JSONException e) {
-                result = new PluginResult(PluginResult.Status.JSON_EXCEPTION,
-                        "JSONException:" + e.getMessage());
-            }
-        }
-
         return result;
     }
 
@@ -279,7 +182,7 @@ public class Accelerometer extends Plugin implements AccelerometerListener
{
     }
 
     /**
-     * Helper function to send a PluginResult to the saved call back IDs.
+     * Helper function to send a PluginResult to the saved call back ID.
      *
      * @param issuccess
      *            true if this is a successful result, false otherwise.
@@ -296,45 +199,18 @@ public class Accelerometer extends Plugin implements AccelerometerListener
{
             // Must keep the call back active for future watch events.
             result.setKeepCallback(keepCallback);
 
-            // Iterate through the saved watch IDs.
-            for (Enumeration watches = watchIds.elements(); watches
-                    .hasMoreElements();) {
-                if (issuccess) {
-                    success(result, (String) watches.nextElement());
-                } else {
-                    error(result, (String) watches.nextElement());
-                }
-            }
-
-            // callbackIds are from getAcceleration() requests so they are
-            // one time and should not keep callback.
-            result.setKeepCallback(false);
-
-            // Iterate through the saved call back IDs.
-            for (Enumeration callbacks = callbackIds.elements(); callbacks
-                    .hasMoreElements();) {
-                if (issuccess) {
-                    success(result, (String) callbacks.nextElement());
-                } else {
-                    error(result, (String) callbacks.nextElement());
-                }
+            if (issuccess) {
+                success(result, this.callbackId);
+            } else {
+                error(result, this.callbackId);
             }
         }
-
-        if (!keepCallback) {
-            watchIds.clear();
-        }
-        callbackIds.removeAllElements();
-
-        if (watchIds.size() == 0) {
-            stop();
-        }
     }
 
     /**
      * Stops accelerometer listener and closes the sensor channel.
      */
-    private synchronized void stop() {
+    private synchronized PluginResult stop() {
         if (_rawDataChannel != null && _rawDataChannel.isOpen()) {
 
             // Remove the battery listener.
@@ -346,5 +222,7 @@ public class Accelerometer extends Plugin implements AccelerometerListener
{
         }
 
         state = STOPPED;
+
+        return new PluginResult(PluginResult.Status.OK);
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/9590c206/javascript/cordova.blackberry.js
----------------------------------------------------------------------
diff --git a/javascript/cordova.blackberry.js b/javascript/cordova.blackberry.js
index fa272c8..2c01a63 100644
--- a/javascript/cordova.blackberry.js
+++ b/javascript/cordova.blackberry.js
@@ -1,6 +1,6 @@
-// commit 7b6ae77e5030060e8e99fe0b79ddcf9d698bf375
+// commit 4a4ba9985c920850fe3f229abc60de984e196ab5
 
-// File generated at :: Wed May 16 2012 10:03:30 GMT-0700 (PDT)
+// File generated at :: Fri May 18 2012 14:54:13 GMT-0700 (PDT)
 
 /*
  Licensed to the Apache Software Foundation (ASF) under one
@@ -3380,13 +3380,57 @@ var utils = require("cordova/utils"),
     exec = require("cordova/exec"),
     Acceleration = require('cordova/plugin/Acceleration');
 
+// Is the accel sensor running?
+var running = false;
 
 // Keeps reference to watchAcceleration calls.
 var timers = {};
 
+// Array of listeners; used to keep track of when we should call start and stop.
+var listeners = [];
+
 // Last returned acceleration object from native
 var accel = null;
 
+// Tells native to start.
+function start() {
+    exec(function(a) {
+        var tempListeners = listeners.slice(0);
+        accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
+        for (var i = 0, l = tempListeners.length; i < l; i++) {
+            tempListeners[i].win(accel);
+        }
+    }, function(e) {
+        var tempListeners = listeners.slice(0);
+        for (var i = 0, l = tempListeners.length; i < l; i++) {
+            tempListeners[i].fail(e);
+        }
+    }, "Accelerometer", "start", []);
+    running = true;
+}
+
+// Tells native to stop.
+function stop() {
+    exec(null, null, "Accelerometer", "stop", []);
+    running = false;
+}
+
+// Adds a callback pair to the listeners array
+function createCallbackPair(win, fail) {
+    return {win:win, fail:fail};
+}
+
+// Removes a win/fail listener pair from the listeners array
+function removeListeners(l) {
+    var idx = listeners.indexOf(l);
+    if (idx > -1) {
+        listeners.splice(idx, 1);
+        if (listeners.length === 0) {
+            stop();
+        }
+    }
+}
+
 var accelerometer = {
     /**
      * Asynchronously aquires the current acceleration.
@@ -3401,13 +3445,22 @@ var accelerometer = {
             throw "getCurrentAcceleration must be called with at least a success callback
function as first parameter.";
         }
 
+        var p;
         var win = function(a) {
-            accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
-            successCallback(accel);
+            successCallback(a);
+            removeListeners(p);
+        };
+        var fail = function(e) {
+            errorCallback(e);
+            removeListeners(p);
         };
 
-        // Get acceleration
-        exec(win, errorCallback, "Accelerometer", "getAcceleration", []);
+        p = createCallbackPair(win, fail);
+        listeners.push(p);
+
+        if (!running) {
+            start();
+        }
     },
 
     /**
@@ -3429,24 +3482,28 @@ var accelerometer = {
 
         // Keep reference to watch id, and report accel readings as often as defined in frequency
         var id = utils.createUUID();
-        timers[id] = window.setInterval(function() {
-            if (accel) {
-                successCallback(accel);
-            }
-        }, frequency);
 
-        // Success callback from native just updates the accel object.
-        var win = function(a) {
-            accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
-        };
+        var p = createCallbackPair(function(){}, function(e) {
+            errorCallback(e);
+            removeListeners(p);
+        });
+        listeners.push(p);
 
-        // Fail callback clears the watch and sends an error back.
-        var fail = function(err) {
-            accelerometer.clearWatch(id);
-            errorCallback(err);
+        timers[id] = {
+            timer:window.setInterval(function() {
+                if (accel) {
+                    successCallback(accel);
+                }
+            }, frequency),
+            listeners:p
         };
 
-        exec(win, fail, "Accelerometer", "addWatch", [id, frequency]);
+        if (running) {
+            // If we're already running then immediately invoke the success callback
+            successCallback(accel);
+        } else {
+            start();
+        }
 
         return id;
     },
@@ -3459,9 +3516,9 @@ var accelerometer = {
     clearWatch: function(id) {
         // Stop javascript timer & remove from timer list
         if (id && timers[id]) {
-            window.clearInterval(timers[id]);
+            window.clearInterval(timers[id].timer);
+            removeListeners(timers[id].listeners);
             delete timers[id];
-            exec(null, null, "Accelerometer", "clearWatch", [id]);
         }
     }
 };


Mime
View raw message