InicialCommit

Cordova Projetct - Platforms: Android and FirefoxOs
Esse commit está contido em:
Guilherme Costa Berghauser
2014-03-16 21:02:21 -03:00
commit 74447379ee
241 arquivos alterados com 39294 adições e 0 exclusões
+19
Ver Arquivo
@@ -0,0 +1,19 @@
{
"prepare_queue": {
"installed": [],
"uninstalled": []
},
"config_munge": {
"res/xml/config.xml": {
"/*": {
"<feature name=\"Accelerometer\"><param name=\"android-package\" value=\"org.apache.cordova.devicemotion.AccelListener\" /></feature>": 1
}
}
},
"installed_plugins": {
"org.apache.cordova.device-motion": {
"PACKAGE_NAME": "br.edu.utfpr.dronecontroller"
}
},
"dependent_plugins": {}
}
+19
Ver Arquivo
@@ -0,0 +1,19 @@
{
"prepare_queue": {
"installed": [],
"uninstalled": []
},
"config_munge": {
"config.xml": {
"/*": {
"<feature name=\"Accelerometer\"><param name=\"firefoxos-package\" value=\"Accelerometer\" /></feature>": 3
}
}
},
"installed_plugins": {
"org.apache.cordova.device-motion": {
"PACKAGE_NAME": "br.edu.utfpr.dronecontroller"
}
},
"dependent_plugins": {}
}
@@ -0,0 +1 @@
{"source":{"type":"local","path":"C:\\Users\\Torto\\AppData\\Local\\Temp\\org.apache.cordova.device-motion\\package"}}
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,22 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# org.apache.cordova.device-motion
Plugin documentation: [doc/index.md](doc/index.md)
@@ -0,0 +1,57 @@
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Release Notes
### 0.2.2 (Sept 25, 2013)
* CB-4889 bumping&resetting version
* [windows8] commandProxy was moved
* CB-4889
* CB-4889 renaming core inside windows8
* CB-4889 renaming org.apache.cordova.core.device-motion to org.apache.cordova.device-motion
* Rename CHANGELOG.md -> RELEASENOTES.md
* [CB-4752] Incremented plugin version on dev branch.
### 0.2.3 (Oct 28, 2013)
* tweak scoping
* fixed the scope
* properly stop watching...
* adding timestamp to the response
* fix acceleromter for firefox os
* update firefoxos integration
* fixed callbacks
* accelerometer registers, but is not responding
* fxos added, not working
* CB-5128: added repo + issue tag to plugin.xml for device motion
* CB-5012 ensure result is returned
* [CB-4825] Add CoreMotion.framework to plugin.xml
* [CB-4825] avoid retain cycle in update block
* [CB-4825] use CoreMotion framework for accelerometer
* [CB-4915] Incremented plugin version on dev branch.
### 0.2.4 (Dec 4, 2013)
* add ubuntu platform
* 1. Added amazon-fireos platform. 2. Change to use amazon-fireos as the platform if the user agent string contains 'cordova-amazon-fireos'
### 0.2.5 (Jan 02, 2014)
* CB-5658 Add doc/index.md for Device Motion plugin
### 0.2.6 (Feb 05, 2014)
* Add Tizen support
@@ -0,0 +1,156 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# org.apache.cordova.device-motion
This plugin provides access to the device's accelerometer. The accelerometer is
a motion sensor that detects the change (_delta_) in movement relative to the
current device orientation, in three dimensions along the _x_, _y_, and _z_
axis.
## Installation
cordova plugin add org.apache.cordova.device-motion
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
## Methods
- navigator.accelerometer.getCurrentAcceleration
- navigator.accelerometer.watchAcceleration
- navigator.accelerometer.clearWatch
## Objects
- Acceleration
## navigator.accelerometer.getCurrentAcceleration
Get the current acceleration along the _x_, _y_, and _z_ axes.
These acceleration values are returned to the `accelerometerSuccess`
callback function.
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
### Example
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
};
function onError() {
alert('onError!');
};
navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
### iOS Quirks
- iOS doesn't recognize the concept of getting the current acceleration at any given point.
- You must watch the acceleration and capture the data at given time intervals.
- Thus, the `getCurrentAcceleration` function yields the last value reported from a `watchAccelerometer` call.
## navigator.accelerometer.watchAcceleration
Retrieves the device's current `Acceleration` at a regular interval, executing
the `accelerometerSuccess` callback function each time. Specify the interval in
milliseconds via the `acceleratorOptions` object's `frequency` parameter.
The returned watch ID references the accelerometer's watch interval,
and can be used with `navigator.accelerometer.clearWatch` to stop watching the
accelerometer.
var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess,
accelerometerError,
[accelerometerOptions]);
- __accelerometerOptions__: An object with the following optional keys:
- __frequency__: How often to retrieve the `Acceleration` in milliseconds. _(Number)_ (Default: 10000)
### Example
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
};
function onError() {
alert('onError!');
};
var options = { frequency: 3000 }; // Update every 3 seconds
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
### iOS Quirks
The API calls the success callback function at the interval requested,
but restricts the range of requests to the device between 40ms and
1000ms. For example, if you request an interval of 3 seconds,
(3000ms), the API requests data from the device every 1 second, but
only executes the success callback every 3 seconds.
## navigator.accelerometer.clearWatch
Stop watching the `Acceleration` referenced by the `watchID` parameter.
navigator.accelerometer.clearWatch(watchID);
- __watchID__: The ID returned by `navigator.accelerometer.watchAcceleration`.
### Example
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
// ... later on ...
navigator.accelerometer.clearWatch(watchID);
## Acceleration
Contains `Accelerometer` data captured at a specific point in time.
Acceleration values include the effect of gravity (9.81 m/s^2), so that when a
device lies flat and facing up, _x_, _y_, and _z_ values returned should be
`0`, `0`, and `9.81`.
### Properties
- __x__: Amount of acceleration on the x-axis. (in m/s^2) _(Number)_
- __y__: Amount of acceleration on the y-axis. (in m/s^2) _(Number)_
- __z__: Amount of acceleration on the z-axis. (in m/s^2) _(Number)_
- __timestamp__: Creation timestamp in milliseconds. _(DOMTimeStamp)_
@@ -0,0 +1,15 @@
{
"version": "0.2.6",
"name": "org.apache.cordova.device-motion",
"cordova_name": "Device Motion",
"description": "Cordova Device Motion Plugin",
"license": "Apache 2.0",
"repo": "https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git",
"issue": "https://issues.apache.org/jira/browse/CB/component/12320636",
"keywords": [
"cordova",
"device",
"motion"
],
"engines": []
}
@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="org.apache.cordova.device-motion"
version="0.2.6">
<name>Device Motion</name>
<description>Cordova Device Motion Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,device,motion</keywords>
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git</repo>
<issue>https://issues.apache.org/jira/browse/CB/component/12320636</issue>
<js-module src="www/Acceleration.js" name="Acceleration">
<clobbers target="Acceleration" />
</js-module>
<js-module src="www/accelerometer.js" name="accelerometer">
<clobbers target="navigator.accelerometer" />
</js-module>
<!-- firefoxos -->
<platform name="firefoxos">
<config-file target="config.xml" parent="/*">
<feature name="Accelerometer">
<param name="firefoxos-package" value="Accelerometer" />
</feature>
</config-file>
<js-module src="src/firefoxos/accelerometer.js" name="accelerometer-impl">
<runs />
</js-module>
</platform>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Accelerometer">
<param name="android-package" value="org.apache.cordova.devicemotion.AccelListener"/>
</feature>
</config-file>
<source-file src="src/android/AccelListener.java" target-dir="src/org/apache/cordova/devicemotion" />
</platform>
<!-- amazon-fireos -->
<platform name="amazon-fireos">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Accelerometer">
<param name="android-package" value="org.apache.cordova.devicemotion.AccelListener"/>
</feature>
</config-file>
<source-file src="src/android/AccelListener.java" target-dir="src/org/apache/cordova/devicemotion" />
</platform>
<!-- ubuntu -->
<platform name="ubuntu">
<header-file src="src/ubuntu/accelerometer.h" />
<source-file src="src/ubuntu/accelerometer.cpp" />
</platform>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Accelerometer">
<param name="ios-package" value="CDVAccelerometer"/>
</feature>
</config-file>
<header-file src="src/ios/CDVAccelerometer.h" />
<source-file src="src/ios/CDVAccelerometer.m" />
<framework src="CoreMotion.framework" />
</platform>
<!-- blackberry10 -->
<platform name="blackberry10">
<config-file target="www/config.xml" parent="/widget">
<feature name="Accelerometer" value="Accelerometer"/>
</config-file>
<source-file src="src/blackberry10/index.js" target-dir="Accelerometer" />
</platform>
<!-- wp7 -->
<platform name="wp7">
<config-file target="config.xml" parent="/*">
<feature name="Accelerometer">
<param name="wp-package" value="Accelerometer"/>
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_SENSORS" />
</config-file>
<source-file src="src/wp/Accelerometer.cs" />
</platform>
<!-- wp8 -->
<platform name="wp8">
<config-file target="config.xml" parent="/*">
<feature name="Accelerometer">
<param name="wp-package" value="Accelerometer"/>
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_SENSORS" />
</config-file>
<source-file src="src/wp/Accelerometer.cs" />
</platform>
<!-- windows8 -->
<platform name="windows8">
<js-module src="src/windows8/AccelerometerProxy.js" name="AccelerometerProxy">
<merges target="" />
</js-module>
</platform>
<!-- tizen -->
<platform name="tizen">
<js-module src="src/tizen/AccelerometerProxy.js" name="AccelerometerProxy">
<runs/>
</js-module>
</platform>
</plugin>
@@ -0,0 +1,295 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.devicemotion;
import java.util.List;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
/**
* This class listens to the accelerometer sensor and stores the latest
* acceleration values x,y,z.
*/
public class AccelListener extends CordovaPlugin implements SensorEventListener {
public static int STOPPED = 0;
public static int STARTING = 1;
public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3;
private float x,y,z; // most recent acceleration values
private long timestamp; // time of most recent value
private int status; // status of listener
private int accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE;
private SensorManager sensorManager; // Sensor manager
private Sensor mSensor; // Acceleration sensor returned by sensor manager
private CallbackContext callbackContext; // Keeps track of the JS callback context.
private Handler mainHandler=null;
private Runnable mainRunnable =new Runnable() {
public void run() {
AccelListener.this.timeout();
}
};
/**
* Create an accelerometer listener.
*/
public AccelListener() {
this.x = 0;
this.y = 0;
this.z = 0;
this.timestamp = 0;
this.setStatus(AccelListener.STOPPED);
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The associated CordovaWebView.
*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
}
/**
* Executes the request.
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackId The callback id used when calling back into JavaScript.
* @return Whether the action was valid.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("start")) {
this.callbackContext = callbackContext;
if (this.status != AccelListener.RUNNING) {
// If not running, then this is an async call, so don't worry about waiting
// We drop the callback onto our stack, call start, and let start and the sensor callback fire off the callback down the road
this.start();
}
}
else if (action.equals("stop")) {
if (this.status == AccelListener.RUNNING) {
this.stop();
}
} else {
// Unsupported action
return false;
}
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT, "");
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
return true;
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
this.stop();
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
//
/**
* Start listening for acceleration sensor.
*
* @return status of listener
*/
private int start() {
// If already starting or running, then just return
if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
return this.status;
}
this.setStatus(AccelListener.STARTING);
// Get accelerometer from sensor manager
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
// If found, then register as listener
if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
this.setStatus(AccelListener.STARTING);
} else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to.");
return this.status;
}
// Set a timeout callback on the main thread.
stopTimeout();
mainHandler = new Handler(Looper.getMainLooper());
mainHandler.postDelayed(mainRunnable, 2000);
return this.status;
}
private void stopTimeout() {
if(mainHandler!=null){
mainHandler.removeCallbacks(mainRunnable);
}
}
/**
* Stop listening to acceleration sensor.
*/
private void stop() {
stopTimeout();
if (this.status != AccelListener.STOPPED) {
this.sensorManager.unregisterListener(this);
}
this.setStatus(AccelListener.STOPPED);
this.accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE;
}
/**
* Returns an error if the sensor hasn't started.
*
* Called two seconds after starting the listener.
*/
private void timeout() {
if (this.status == AccelListener.STARTING) {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "Accelerometer could not be started.");
}
}
/**
* Called when the accuracy of the sensor has changed.
*
* @param sensor
* @param accuracy
*/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Only look at accelerometer events
if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
// If not running, then just return
if (this.status == AccelListener.STOPPED) {
return;
}
this.accuracy = accuracy;
}
/**
* Sensor listener event.
*
* @param SensorEvent event
*/
public void onSensorChanged(SensorEvent event) {
// Only look at accelerometer events
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
// If not running, then just return
if (this.status == AccelListener.STOPPED) {
return;
}
this.setStatus(AccelListener.RUNNING);
if (this.accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM) {
// Save time that event was received
this.timestamp = System.currentTimeMillis();
this.x = event.values[0];
this.y = event.values[1];
this.z = event.values[2];
this.win();
}
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
if (this.status == AccelListener.RUNNING) {
this.stop();
}
}
// Sends an error back to JS
private void fail(int code, String message) {
// Error object
JSONObject errorObj = new JSONObject();
try {
errorObj.put("code", code);
errorObj.put("message", message);
} catch (JSONException e) {
e.printStackTrace();
}
PluginResult err = new PluginResult(PluginResult.Status.ERROR, errorObj);
err.setKeepCallback(true);
callbackContext.sendPluginResult(err);
}
private void win() {
// Success return object
PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON());
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
private void setStatus(int status) {
this.status = status;
}
private JSONObject getAccelerationJSON() {
JSONObject r = new JSONObject();
try {
r.put("x", this.x);
r.put("y", this.y);
r.put("z", this.z);
r.put("timestamp", this.timestamp);
} catch (JSONException e) {
e.printStackTrace();
}
return r;
}
}
@@ -0,0 +1,45 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var callback;
module.exports = {
start: function (success, fail, args, env) {
var result = new PluginResult(args, env);
window.removeEventListener("devicemotion", callback);
callback = function (motion) {
var info = {
x: motion.accelerationIncludingGravity.x,
y: motion.accelerationIncludingGravity.y,
z: motion.accelerationIncludingGravity.z,
timestamp: motion.timestamp
};
result.callbackOk(info, true);
};
window.addEventListener("devicemotion", callback);
result.noResult(true);
},
stop: function (success, fail, args, env) {
var result = new PluginResult(args, env);
window.removeEventListener("devicemotion", callback);
result.ok("removed");
}
};
@@ -0,0 +1,21 @@
function listener(success, ev) {
var acc = ev.accelerationIncludingGravity;
acc.timestamp = new Date().getTime();
success(acc);
}
var Accelerometer = {
start: function start(success, error) {
return window.addEventListener('devicemotion', function(ev) {
listener(success, ev);
}, false);
},
stop: function stop() {
window.removeEventListener('devicemotion', listener, false);
}
};
module.exports = Accelerometer;
require('cordova/firefoxos/commandProxy').add('Accelerometer', Accelerometer);
@@ -0,0 +1,39 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <UIKit/UIKit.h>
#import <Cordova/CDVPlugin.h>
@interface CDVAccelerometer : CDVPlugin
{
double x;
double y;
double z;
NSTimeInterval timestamp;
}
@property (readonly, assign) BOOL isRunning;
@property (nonatomic, strong) NSString* callbackId;
- (CDVAccelerometer*)init;
- (void)start:(CDVInvokedUrlCommand*)command;
- (void)stop:(CDVInvokedUrlCommand*)command;
@end
@@ -0,0 +1,138 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <CoreMotion/CoreMotion.h>
#import "CDVAccelerometer.h"
@interface CDVAccelerometer () {}
@property (readwrite, assign) BOOL isRunning;
@property (readwrite, assign) BOOL haveReturnedResult;
@property (readwrite, strong) CMMotionManager* motionManager;
@end
@implementation CDVAccelerometer
@synthesize callbackId, isRunning;
// defaults to 10 msec
#define kAccelerometerInterval 10
// g constant: -9.81 m/s^2
#define kGravitationalConstant -9.81
- (CDVAccelerometer*)init
{
self = [super init];
if (self) {
x = 0;
y = 0;
z = 0;
timestamp = 0;
self.callbackId = nil;
self.isRunning = NO;
self.haveReturnedResult = YES;
self.motionManager = nil;
}
return self;
}
- (void)dealloc
{
[self stop:nil];
}
- (void)start:(CDVInvokedUrlCommand*)command
{
self.haveReturnedResult = NO;
self.callbackId = command.callbackId;
if (!self.motionManager)
{
self.motionManager = [[CMMotionManager alloc] init];
}
if ([self.motionManager isAccelerometerAvailable] == YES) {
// Assign the update interval to the motion manager and start updates
[self.motionManager setAccelerometerUpdateInterval:kAccelerometerInterval/1000]; // expected in seconds
__weak CDVAccelerometer* weakSelf = self;
[self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
x = accelerometerData.acceleration.x;
y = accelerometerData.acceleration.y;
z = accelerometerData.acceleration.z;
timestamp = ([[NSDate date] timeIntervalSince1970] * 1000);
[weakSelf returnAccelInfo];
}];
if (!self.isRunning) {
self.isRunning = YES;
}
}
}
- (void)onReset
{
[self stop:nil];
}
- (void)stop:(CDVInvokedUrlCommand*)command
{
if ([self.motionManager isAccelerometerAvailable] == YES) {
if (self.haveReturnedResult == NO){
// block has not fired before stop was called, return whatever result we currently have
[self returnAccelInfo];
}
[self.motionManager stopAccelerometerUpdates];
}
self.isRunning = NO;
}
- (void)returnAccelInfo
{
// Create an acceleration object
NSMutableDictionary* accelProps = [NSMutableDictionary dictionaryWithCapacity:4];
[accelProps setValue:[NSNumber numberWithDouble:x * kGravitationalConstant] forKey:@"x"];
[accelProps setValue:[NSNumber numberWithDouble:y * kGravitationalConstant] forKey:@"y"];
[accelProps setValue:[NSNumber numberWithDouble:z * kGravitationalConstant] forKey:@"z"];
[accelProps setValue:[NSNumber numberWithDouble:timestamp] forKey:@"timestamp"];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:accelProps];
[result setKeepCallback:[NSNumber numberWithBool:YES]];
[self.commandDelegate sendPluginResult:result callbackId:self.callbackId];
self.haveReturnedResult = YES;
}
// TODO: Consider using filtering to isolate instantaneous data vs. gravity data -jm
/*
#define kFilteringFactor 0.1
// Use a basic low-pass filter to keep only the gravity component of each axis.
grav_accelX = (acceleration.x * kFilteringFactor) + ( grav_accelX * (1.0 - kFilteringFactor));
grav_accelY = (acceleration.y * kFilteringFactor) + ( grav_accelY * (1.0 - kFilteringFactor));
grav_accelZ = (acceleration.z * kFilteringFactor) + ( grav_accelZ * (1.0 - kFilteringFactor));
// Subtract the low-pass value from the current value to get a simplified high-pass filter
instant_accelX = acceleration.x - ( (acceleration.x * kFilteringFactor) + (instant_accelX * (1.0 - kFilteringFactor)) );
instant_accelY = acceleration.y - ( (acceleration.y * kFilteringFactor) + (instant_accelY * (1.0 - kFilteringFactor)) );
instant_accelZ = acceleration.z - ( (acceleration.z * kFilteringFactor) + (instant_accelZ * (1.0 - kFilteringFactor)) );
*/
@end
@@ -0,0 +1,30 @@
(function(win) {
var cordova = require('cordova'),
Acceleration = require('org.apache.cordova.device-motion.Acceleration'),
accelerometerCallback = null;
module.exports = {
start: function (successCallback, errorCallback) {
if (accelerometerCallback) {
win.removeEventListener("devicemotion", accelerometerCallback, true);
}
accelerometerCallback = function (motion) {
successCallback({
x: motion.accelerationIncludingGravity.x,
y: motion.accelerationIncludingGravity.y,
z: motion.accelerationIncludingGravity.z,
timestamp: new Date().getTime()
});
};
win.addEventListener("devicemotion", accelerometerCallback, true);
},
stop: function (successCallback, errorCallback) {
win.removeEventListener("devicemotion", accelerometerCallback, true);
accelerometerCallback = null;
}
};
require("cordova/tizen/commandProxy").add("Accelerometer", module.exports);
}(window));
@@ -0,0 +1,58 @@
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include <cassert>
#include "accelerometer.h"
DeviceMotion::DeviceMotion(Cordova *cordova): CPlugin(cordova), _scId(0), _ecId(0) {
_accelerometerSource = QSharedPointer<QAccelerometer>(new QAccelerometer());
_sensorAvaliable = _accelerometerSource->start();
connect(_accelerometerSource.data(), SIGNAL(readingChanged()), SLOT(updateSensor()));
}
void DeviceMotion::start(int scId, int ecId) {
assert(_ecId == 0);
assert(_scId == 0);
_ecId = ecId;
_scId = scId;
if (!_sensorAvaliable) {
this->cb(ecId);
return;
}
}
void DeviceMotion::stop(int, int) {
_scId = 0;
_ecId = 0;
}
void DeviceMotion::updateSensor() {
QAccelerometerReading *accelerometer = _accelerometerSource->reading();
QVariantMap obj;
obj.insert("x", accelerometer->x());
obj.insert("y", accelerometer->y());
obj.insert("z", accelerometer->z());
// accelerometer->timestamp() is not sutiable.
// Timestamps values are microseconds since _a_ fixed point(depend on backend).
obj.insert("timestamp", QDateTime::currentDateTime().toMSecsSinceEpoch());
if (_scId)
this->cb(_scId, obj);
}
@@ -0,0 +1,55 @@
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#ifndef ACCELEROMETER_H
#define ACCELEROMETER_H
#include <cplugin.h>
#include <QAccelerometer>
#include <QtCore>
class DeviceMotion: public CPlugin {
Q_OBJECT
public:
explicit DeviceMotion(Cordova *cordova);
virtual const QString fullName() override {
return DeviceMotion::fullID();
}
virtual const QString shortName() override {
return "Accelerometer";
}
static const QString fullID() {
return "Accelerometer";
}
public slots:
void start(int scId, int ecId);
void stop(int scId, int ecId);
protected slots:
void updateSensor();
private:
int _scId, _ecId;
bool _sensorAvaliable;
QSharedPointer<QAccelerometer> _accelerometerSource;
};
#endif
@@ -0,0 +1,70 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/*global Windows:true */
var cordova = require('cordova'),
Acceleration = require('org.apache.cordova.device-motion.Acceleration');
/* This is the actual implementation part that returns the result on Windows 8
*/
module.exports = {
onDataChanged:null,
start:function(win,lose){
var accel = Windows.Devices.Sensors.Accelerometer.getDefault();
if(!accel) {
lose && lose("No accelerometer found");
}
else {
var self = this;
accel.reportInterval = Math.max(16,accel.minimumReportInterval);
// store our bound function
this.onDataChanged = function(e) {
var a = e.reading;
win(new Acceleration(a.accelerationX,a.accelerationY,a.accelerationZ));
};
accel.addEventListener("readingchanged",this.onDataChanged);
setTimeout(function(){
var a = accel.getCurrentReading();
win(new Acceleration(a.accelerationX,a.accelerationY,a.accelerationZ));
},0); // async do later
}
},
stop:function(win,lose){
win = win || function(){};
var accel = Windows.Devices.Sensors.Accelerometer.getDefault();
if(!accel) {
lose && lose("No accelerometer found");
}
else {
accel.removeEventListener("readingchanged",this.onDataChanged);
this.onDataChanged = null;
accel.reportInterval = 0; // back to the default
win();
}
}
};
require("cordova/windows8/commandProxy").add("Accelerometer",module.exports);
@@ -0,0 +1,196 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
using Microsoft.Devices.Sensors;
using System.Globalization;
using System.Diagnostics;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Captures device motion in the x, y, and z direction.
/// </summary>
public class Accelerometer : BaseCommand
{
#region AccelerometerOptions class
/// <summary>
/// Represents Accelerometer options.
/// </summary>
[DataContract]
public class AccelerometerOptions
{
/// <summary>
/// How often to retrieve the Acceleration in milliseconds
/// </summary>
[DataMember(IsRequired = false, Name = "frequency")]
public int Frequency { get; set; }
/// <summary>
/// Watcher id
/// </summary>
[DataMember(IsRequired = false, Name = "id")]
public string Id { get; set; }
/// <summary>
/// Creates options object with default parameters
/// </summary>
public AccelerometerOptions()
{
this.SetDefaultValues(new StreamingContext());
}
/// <summary>
/// Initializes default values for class fields.
/// Implemented in separate method because default constructor is not invoked during deserialization.
/// </summary>
/// <param name="context"></param>
[OnDeserializing()]
public void SetDefaultValues(StreamingContext context)
{
this.Frequency = 10000;
}
}
#endregion
#region Status codes and Constants
public const int Stopped = 0;
public const int Starting = 1;
public const int Running = 2;
public const int ErrorFailedToStart = 3;
public const double gConstant = -9.81;
#endregion
#region Static members
/// <summary>
/// Status of listener
/// </summary>
private static int currentStatus;
/// <summary>
/// Accelerometer
/// </summary>
private static Microsoft.Devices.Sensors.Accelerometer accelerometer = new Microsoft.Devices.Sensors.Accelerometer();
private static DateTime StartOfEpoch = new DateTime(1970, 1, 1, 0, 0, 0);
#endregion
/// <summary>
/// Sensor listener event
/// </summary>
private void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
this.SetStatus(Running);
PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentAccelerationFormatted());
result.KeepCallback = true;
DispatchCommandResult(result);
}
/// <summary>
/// Starts listening for acceleration sensor
/// </summary>
/// <returns>status of listener</returns>
public void start(string options)
{
if ((currentStatus == Running) || (currentStatus == Starting))
{
return;
}
try
{
lock (accelerometer)
{
accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged;
accelerometer.Start();
this.SetStatus(Starting);
}
long timeout = 2000;
while ((currentStatus == Starting) && (timeout > 0))
{
timeout = timeout - 100;
Thread.Sleep(100);
}
if (currentStatus != Running)
{
this.SetStatus(ErrorFailedToStart);
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart));
return;
}
}
catch (Exception)
{
this.SetStatus(ErrorFailedToStart);
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart));
return;
}
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.KeepCallback = true;
DispatchCommandResult(result);
}
public void stop(string options)
{
if (currentStatus == Running)
{
lock (accelerometer)
{
accelerometer.CurrentValueChanged -= accelerometer_CurrentValueChanged;
accelerometer.Stop();
this.SetStatus(Stopped);
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
/// <summary>
/// Formats current coordinates into JSON format
/// </summary>
/// <returns>Coordinates in JSON format</returns>
private string GetCurrentAccelerationFormatted()
{
// convert to unix timestamp
// long timestamp = ((accelerometer.CurrentValue.Timestamp.DateTime - StartOfEpoch).Ticks) / 10000;
// Note: Removed timestamp, to let the JS side create it using (new Date().getTime()) -jm
// this resolves an issue with inconsistencies between JS dates and Native DateTime
string resultCoordinates = String.Format("\"x\":{0},\"y\":{1},\"z\":{2}",
(accelerometer.CurrentValue.Acceleration.X * gConstant).ToString("0.00000", CultureInfo.InvariantCulture),
(accelerometer.CurrentValue.Acceleration.Y * gConstant).ToString("0.00000", CultureInfo.InvariantCulture),
(accelerometer.CurrentValue.Acceleration.Z * gConstant).ToString("0.00000", CultureInfo.InvariantCulture));
return "{" + resultCoordinates + "}";
}
/// <summary>
/// Sets current status
/// </summary>
/// <param name="status">current status</param>
private void SetStatus(int status)
{
currentStatus = status;
}
}
}
@@ -0,0 +1,29 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var Acceleration = function(x, y, z, timestamp) {
this.x = x;
this.y = y;
this.z = z;
this.timestamp = timestamp || (new Date()).getTime();
};
module.exports = Acceleration;
@@ -0,0 +1,169 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/**
* This class provides access to device accelerometer data.
* @constructor
*/
var argscheck = require('cordova/argscheck'),
utils = require("cordova/utils"),
exec = require("cordova/exec"),
Acceleration = require('./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 acquires the current acceleration.
*
* @param {Function} successCallback The function to call when the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
*/
getCurrentAcceleration: function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'accelerometer.getCurrentAcceleration', arguments);
var p;
var win = function(a) {
removeListeners(p);
successCallback(a);
};
var fail = function(e) {
removeListeners(p);
errorCallback && errorCallback(e);
};
p = createCallbackPair(win, fail);
listeners.push(p);
if (!running) {
start();
}
},
/**
* Asynchronously acquires the acceleration repeatedly at a given interval.
*
* @param {Function} successCallback The function to call each time the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
watchAcceleration: function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'accelerometer.watchAcceleration', arguments);
// Default interval (10 sec)
var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000;
// Keep reference to watch id, and report accel readings as often as defined in frequency
var id = utils.createUUID();
var p = createCallbackPair(function(){}, function(e) {
removeListeners(p);
errorCallback && errorCallback(e);
});
listeners.push(p);
timers[id] = {
timer:window.setInterval(function() {
if (accel) {
successCallback(accel);
}
}, frequency),
listeners:p
};
if (running) {
// If we're already running then immediately invoke the success callback
// but only if we have retrieved a value, sample code does not check for null ...
if (accel) {
successCallback(accel);
}
} else {
start();
}
return id;
},
/**
* Clears the specified accelerometer watch.
*
* @param {String} id The id of the watch returned from #watchAcceleration.
*/
clearWatch: function(id) {
// Stop javascript timer & remove from timer list
if (id && timers[id]) {
window.clearInterval(timers[id].timer);
removeListeners(timers[id].listeners);
delete timers[id];
}
}
};
module.exports = accelerometer;