changeset 5:1ec9513a1f1b

Added bluetooth plugin
author Michal Kawalec <mkawalec@lavabit.com>
date Sat, 01 Jun 2013 18:35:08 +0200
parents 829280ac13bd
children 5fbee00dbb66 4dd13ff170dd
files assets/www/Bluetooth.js assets/www/index.html bin/build.prop bin/classes.dex bin/classes.dex.d bin/classes/com/phonegap/plugin/bluetooth/Bluetooth.class bin/classes/com/phonegap/plugin/bluetooth/BluetoothPlugin$1.class bin/classes/com/phonegap/plugin/bluetooth/BluetoothPlugin.class bin/partybuddy-debug-unaligned.apk bin/partybuddy-debug.apk bin/partybuddy.ap_ bin/partybuddy.ap_.d res/xml/config.xml src/com/phonegap/plugins/bluetooth/Bluetooth.java src/com/phonegap/plugins/bluetooth/BluetoothPlugin.java
diffstat 15 files changed, 593 insertions(+), 331 deletions(-) [+]
line wrap: on
line diff
--- a/assets/www/Bluetooth.js	Sat Jun 01 17:44:10 2013 +0200
+++ b/assets/www/Bluetooth.js	Sat Jun 01 18:35:08 2013 +0200
@@ -1,328 +1,115 @@
-/*
-   Copyright December, 2012 Hüseyin Kozan - http://huseyinkozan.com.tr
-   
-   Copyright 2012 Wolfgang Koller - http://www.gofg.at/
-   
-   Modified and improved December, 2012 Hüseyin Kozan http://huseyinkozan.com.tr
-
-   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.
+/* Copyright (c) 2011 - Andago
+*
+* author: Daniel Tizon
+*
+* 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.
 */
 
-cordova.define("cordova/plugin/bluetooth", function(require, exports, module) {
-  var exec = require('cordova/exec');
-  
-  var Bluetooth = function() {};
-  
-  /**
-   * Check if Bluetooth API is supported on this platform
-   *
-   * Example;
-   *     isSupported(
-   *           function(supported){if(supported) alert("supported"); else alert("not supported")},
-   *           function(error){alert(error);});
-   * 
-   * successCallback(supported) : function to be called when checking support was successful
-   * failureCallback(message) : function to be called when checking support was not possible / did fail
-   */
-  Bluetooth.prototype.isSupported = function(successCallback,failureCallback) {
-    return exec(successCallback, failureCallback, 'BluetoothPlugin', 'isSupported', []);
-  }
-  
-  /**
-   * Enable Bluetooth
-   *
-   * Example;
-   *     enable(
-   *           function(){alert("success");},
-   *           function(error){alert(error);});
-   * 
-   * successCallback() : function to be called when enabling of Bluetooth was successful
-   * failureCallback(message) : function to be called when enabling was not possible / did fail
-   */
-  Bluetooth.prototype.enable = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'enable', []);
-  }
-  
-  /**
-   * Disable Bluetooth
-   *
-   * Example;
-   *     disable(
-   *           function(){alert("success");},
-   *           function(error){alert(error);});
-   * 
-   * successCallback() : function to be called when disabling of Bluetooth was successful
-   * failureCallback(message) : function to be called when disabling was not possible / did fail
-   */
-  Bluetooth.prototype.disable = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'disable', []);
-  }
-  
-  /**
-   * Checks if Bluetooth is enabled
-   *
-   * Example;
-   *     isEnabled(
-   *           function(){alert("enabled");},
-   *           function(error){alert("disabled, error:"+error);});
-   * 
-   * successCallback() : function to be called after successful return.
-   * failureCallback(message) : function to be called due to failure
-   */
-  Bluetooth.prototype.isEnabled = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'isEnabled', []);
-  }
-  
-  /**
-   * Returns device address as string. For example, "00:11:22:AA:BB:CC".
-   *
-   * Example;
-   *     getAddress(
-   *           function(address){alert("Adapters address is : " + address);},
-   *           function(error){alert(error);});
-   * 
-   * successCallback(address) : function to be called when getting the adapter address.
-   * failureCallback(message) : function to be called due to failure
-   */
-  Bluetooth.prototype.getAddress = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'getAddress', []);
-  }
-  
-  /**
-   * Returns device name as string.
-   *
-   * Example;
-   *     getName(
-   *           function(name){alert("Adapters name is : " + name);},
-   *           function(error){alert(error);});
-   * 
-   * successCallback(name) : function to be called when getting the adapter's friendly name.
-   * failureCallback(message) : function to be called due to failure
-   */
-  Bluetooth.prototype.getName = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'getName', []);
-  }
-  
-  /**
-   * Request discoverable from user for given duration
-   *
-   * Example;
-   *     requestDiscoverable(
-   *           function(duration){alert("Discoverable duration is : " + duration);},
-   *           function(error){alert(error);},
-   *           200 );
-   * 
-   * successCallback(duration) : function to be called after user confirms request.
-   * failureCallback(message) : function to be called when there was a problem while requesting
-   * duration : default is 120, maximum is 300 seconds
-   */
-  Bluetooth.prototype.requestDiscoverable = function(successCallback,failureCallback, duration) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'requestDiscoverable', [duration]);
-  }
-  
-  /**
-   * Search for devices  and list them
-   *
-   * Example;
-   *     startDiscovery(
-   *           function(deviceJsonArray){
-   *             for(int i=0;i<deviceJsonArray.length;i++){
-   *               uuidJsonArray[i].name;
-   *               uuidJsonArray[i].address;
-   *               uuidJsonArray[i].isBonded;
-   *             }
-   *           },
-   *           function(error){alert(error);});
-   * 
-   * successCallback(deviceJsonArray) : function to be called when discovery of other devices has finished.
-   * failureCallback(message) : function to be called when there was a problem while discovering devices
-   */
-  Bluetooth.prototype.startDiscovery = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'startDiscovery', []);
-  }
-  
-  /**
-   * Cancels ongoing discovery
-   *
-   * Example;
-   *     cancelDiscovery(
-   *           function(){alert("success");},
-   *           function(error){alert(error);},
-   *           0 );
-   * 
-   * successCallback() : function to be called after successfully canceled.
-   * failureCallback(message) : function to be called due to failure
-   */
-  Bluetooth.prototype.cancelDiscovery = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'cancelDiscovery', []);
-  }
-  
-  /**
-   * Return bonded (paired) devices
-   * 
-   * Example;
-   *     getBondedDevices(
-   *           function(deviceJsonArray){
-   *             for(int i=0;i<deviceJsonArray.length;i++){
-   *               uuidJsonArray[i].name;
-   *               uuidJsonArray[i].address;
-   *               uuidJsonArray[i].isBonded;
-   *             }
-   *           },
-   *           function(error){alert(error);});
-   * 
-   * successCallback(deviceJsonArray) : function to be called after success.
-   * failureCallback(message) : function to be called due to failure
-   */
-  Bluetooth.prototype.getBondedDevices = function(successCallback,failureCallback) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'getBondedDevices', []);
-  }
-  
-  /**
-   * Return list of available UUIDs for a given device
-   * Needs minimum SDK API 15
-   * 
-   * Example;
-   *     fetchUUIDs(
-   *           function(uuidJsonArray){for(int i=0;i<uuidJsonArray.length;i++){uuidJsonArray[i];}},
-   *           function(error){alert(error);},
-   *           "00:11:22:AA:BB:CC");
-   * 
-   * successCallback(uuidJsonArray) : function to be called when listing of UUIDs has finished.
-   * failureCallback(message) : function to be called when there was a problem while listing UUIDs
-   * address : address string of the remote
-   */
-  Bluetooth.prototype.fetchUUIDs = function(successCallback,failureCallback,address) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'fetchUUIDs', [address]);
-  }
-  
-  /**
-   * Open an RFComm channel for a given device & uuid endpoint
-   * Insecure connection needs minimum SDK API 10
-   * 
-   * Example;
-   *     connect(
-   *           function(socketId){alert("Connected to : " + socketId)},
-   *           function(error){alert(error);},
-   *           "00:11:22:AA:BB:CC",
-   *           "fa87c0d0-afac-11de-8a39-0800200c9a66",
-   *           true);
-   * 
-   * successCallback(socketId) : function to be called when the connection was successful.
-   * failureCallback(message) :  function to be called when there was a problem while opening the connection
-   * address : Bluetooth device address string
-   * uuid : UUID string
-   * secure boolean if connection is secure or not
-   */
-  Bluetooth.prototype.connect = function(successCallback,failureCallback,address,uuid, secure) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'connect', [address, uuid, secure]);
-  }
-  
-  /**
-   * Close a RFComm channel for a given socket-id
-   * 
-   * Example;
-   *     disconnect(
-   *           function(){alert("success");},
-   *           function(error){alert(error);},
-   *           0 );
-   * 
-   * successCallback() : function to be called when the connection was closed successfully
-   * failureCallback(message) : function to be called when there was a problem while closing the connection
-   * socketId : socket id
-   */
-  Bluetooth.prototype.disconnect = function(successCallback,failureCallback,socketId) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'disconnect', [socketId]);
-  }
-  
-  
-  /**
-   * Listens incoming connections
-   * Insecure listening needs minimum SDK API 10
-   *
-   * Example;
-   *     listen(
-   *           function(socketId){alert("Connected to : " + socketId)},
-   *           function(error){alert(error);},
-   *           "BluetoothChatSecure",
-   *           "fa87c0d0-afac-11de-8a39-0800200c9a66",
-   *           true);
-   * 
-   * successCallback(socketid) : function to be called on every new connection establish
-   * failureCallback(message) : function to be called when there was a problem while listening
-   * name : Listening service name
-   * uuid : Listening service UUID
-   * secure : boolean if connection is secure or not
-   */
-  Bluetooth.prototype.listen = function(successCallback,failureCallback,name,uuid,secure) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'listen', [name,uuid,secure]);
-  }
-  
-  /**
-   * Cancels listening incoming connections
-   * 
-   * Example;
-   *     cancelListening(
-   *           function(){alert("success");},
-   *           function(error){alert(error);});
-   * 
-   * successCallback() : function to be called when stops listening successfully
-   * failureCallback(message) : function to be called when there was a problem \ 
-   *                            while stopping listening
-   */
-  Bluetooth.prototype.cancelListening = function(successCallback,failureCallback) {
-    return exec(successCallback, failureCallback, 'BluetoothPlugin', 'cancelListening', []);
-  }
-  
-  /**
-   * Registers a callback function which called after a successful read
-   * 
-   * Example;
-   *     read(
-   *           function(byteArray){for(int i=0;i<byteArray.length;i++){byteArray[i];}},
-   *           function(error){alert(error);},
-   *           0);
-   * 
-   * successCallback(byteArray) : function to be called after each successful read.
-   * failureCallback(message) : function to be called when there was a problem while \
-   *                            reading or after socket has been closed.
-   * socketId : connected socket id
-   * bufferSize : internal buffer size while reading, default is 1024
-   */
-  Bluetooth.prototype.read = function(successCallback,failureCallback,socketId,bufferSize) {
-	  bufferSize = typeof bufferSize !== 'undefined' ? bufferSize : 1024;
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'read', [socketId,bufferSize]);
-  }
-  
-  /**
-   * Write to a connected socket
-   * 
-   * Example;
-   *     write(
-   *           function(){alert("success");},
-   *           function(error){alert(error);},
-   *           0,
-   *           {10,20,30,40});
-   * 
-   * successCallback() : function to be called when writing was successful.
-   * failureCallback(message) : function to be called when there was a problem while writing
-   * socketId : socket id which already connected.
-   * jsonArray : data that wanted to send
-   */
-  Bluetooth.prototype.write = function(successCallback,failureCallback,socketId,jsonArray) {
-      return exec(successCallback, failureCallback, 'BluetoothPlugin', 'write', [socketId,jsonArray]);
-  }
-  
-  var bluetooth = new Bluetooth();
-  module.exports = bluetooth;
+cordova.define("cordova/plugin/bluetooth",
+  function(require, exports, module) {
+    var exec = require("cordova/exec");
+
+    var Bluetooth = function() {};
+
+    /**
+    * @param argument Argument that we are going to pass to the plugin - for this method no arguments are needed
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.listDevices = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'listDevices', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin - for this method no arguments are needed
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.isBTEnabled = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'isBTEnabled', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin - for this method no arguments are needed
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.enableBT = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'enableBT', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin - for this method no arguments are needed
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.disableBT = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'disableBT', [argument]);
+    };
+
+    /**
+    * @param argument Argument that we are going to pass to the plugin, you need pass the MAC address of the bluetooth device with wich you want to pair
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.pairBT = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'pairBT', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin, you need pass the MAC address of the bluetooth device that you want unpair
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.unPairBT = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'unPairBT', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin - for this method no arguments are needed
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.listBoundDevices = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'listBoundDevices', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin - for this method no arguments are needed
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.stopDiscovering = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'stopDiscovering', [argument]);
+    };
+    
+    /**
+    * @param argument Argument that we are going to pass to the plugin, you need pass the MAC address of the mobile that you want to know if it is bound
+    * @param successCallback The callback which will be called when listDevices is successful
+    * @param failureCallback The callback which will be called when listDevices encouters an error
+    */
+    Bluetooth.prototype.isBound = function(argument,successCallback, failureCallback) {
+        exec(successCallback, failureCallback, 'BluetoothPlugin', 'isBound', [argument]);
+    };
+
+    var bluetooth = new Bluetooth();
+    module.exports = bluetooth;
 });
+
+
+if (!window.plugins) {
+    window.plugins = {};
+}
+if (!window.plugins.bluetooth) {
+    window.plugins.bluetooth = cordova.require("cordova/plugin/bluetooth");
+}
--- a/assets/www/index.html	Sat Jun 01 17:44:10 2013 +0200
+++ b/assets/www/index.html	Sat Jun 01 18:35:08 2013 +0200
@@ -23,21 +23,28 @@
     <title>Acceleration Example</title>
 
     <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
+    <script type="text/javascript" charset="utf-8" src="Bluetooth.js"></script>
     <script type="text/javascript" charset="utf-8">
 
     // Wait for Cordova to load
     //
     document.addEventListener("deviceready", onDeviceReady, false);
+    console.log('in');
 
     // Cordova is ready
     //
     function onDeviceReady() {
-        navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
+        plugin = cordova.require('cordova/plugin/bluetooth');
+        plugin.listDevices(null,
+                function(r){console.log(r)},
+                function(e){console.log(e)}
+                );
     }
+        //navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
 
     // onSuccess: Get a snapshot of the current acceleration
     //
-    function onSuccess(acceleration) {
+    /*function onSuccess(acceleration) {
         alert('Acceleration X: ' + acceleration.x + '\n' +
               'Acceleration Y: ' + acceleration.y + '\n' +
               'Acceleration Z: ' + acceleration.z + '\n' +
@@ -48,12 +55,10 @@
     //
     function onError() {
         alert('onError!');
-    }
+    }*/
 
     </script>
   </head>
   <body>
-    <h1>Example</h1>
-    <p>getCurrentAcceleration</p>
   </body>
 </html>
--- a/bin/build.prop	Sat Jun 01 17:44:10 2013 +0200
+++ b/bin/build.prop	Sat Jun 01 18:35:08 2013 +0200
@@ -1,5 +1,5 @@
 #Last build type
-#Sat, 01 Jun 2013 17:27:47 +0200
+#Sat, 01 Jun 2013 18:33:53 +0200
 
 build.last.target=debug
 
Binary file bin/classes.dex has changed
--- a/bin/classes.dex.d	Sat Jun 01 17:44:10 2013 +0200
+++ b/bin/classes.dex.d	Sat Jun 01 18:35:08 2013 +0200
@@ -1,4 +1,7 @@
 /home/michal/build/party-buddy/bin/classes.dex : \
+/home/michal/build/party-buddy/bin/classes/com/phonegap/plugin/bluetooth/Bluetooth.class \
+/home/michal/build/party-buddy/bin/classes/com/phonegap/plugin/bluetooth/BluetoothPlugin$1.class \
+/home/michal/build/party-buddy/bin/classes/com/phonegap/plugin/bluetooth/BluetoothPlugin.class \
 /home/michal/build/party-buddy/bin/classes/com/nigmalabs/partybuddy/R$string.class \
 /home/michal/build/party-buddy/bin/classes/com/nigmalabs/partybuddy/partybuddy.class \
 /home/michal/build/party-buddy/bin/classes/com/nigmalabs/partybuddy/R.class \
Binary file bin/classes/com/phonegap/plugin/bluetooth/Bluetooth.class has changed
Binary file bin/classes/com/phonegap/plugin/bluetooth/BluetoothPlugin$1.class has changed
Binary file bin/classes/com/phonegap/plugin/bluetooth/BluetoothPlugin.class has changed
Binary file bin/partybuddy-debug-unaligned.apk has changed
Binary file bin/partybuddy-debug.apk has changed
Binary file bin/partybuddy.ap_ has changed
--- a/bin/partybuddy.ap_.d	Sat Jun 01 17:44:10 2013 +0200
+++ b/bin/partybuddy.ap_.d	Sat Jun 01 18:35:08 2013 +0200
@@ -30,6 +30,7 @@
 /home/michal/build/party-buddy/assets/www/spec \
 /home/michal/build/party-buddy/assets/www/main.js \
 /home/michal/build/party-buddy/assets/www/js \
+/home/michal/build/party-buddy/assets/www/Bluetooth.js \
 /home/michal/build/party-buddy/assets/www/css \
 /home/michal/build/party-buddy/assets/www/img/logo.png \
 /home/michal/build/party-buddy/assets/www/img/cordova.png \
--- a/res/xml/config.xml	Sat Jun 01 17:44:10 2013 +0200
+++ b/res/xml/config.xml	Sat Jun 01 18:35:08 2013 +0200
@@ -104,5 +104,6 @@
     <!-- Deprecated plugins element. Remove in 3.0 -->
     <plugins>
         <plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />
+        <plugin name="BluetoothPlugin" value="com.phonegap.plugin.bluetooth.BluetoothPlugin"/>
     </plugins>
 </widget>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/com/phonegap/plugins/bluetooth/Bluetooth.java	Sat Jun 01 18:35:08 2013 +0200
@@ -0,0 +1,13 @@
+package com.phonegap.plugin.bluetooth;
+
+import org.apache.cordova.DroidGap;
+import android.os.Bundle;
+
+public class Bluetooth extends DroidGap {
+    /** Called when the activity is first created. */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        super.loadUrl("file:///android_asset/www/index.html");
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/com/phonegap/plugins/bluetooth/BluetoothPlugin.java	Sat Jun 01 18:35:08 2013 +0200
@@ -0,0 +1,452 @@
+/* Copyright (c) 2011 - Andago
+ * 
+ * author: Daniel Tizon, Idoia Olalde, Iigo Gonzalez
+ * 
+ * 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.
+ */
+
+package com.phonegap.plugin.bluetooth;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Set;
+
+import org.apache.cordova.CordovaWebView;
+import org.apache.cordova.api.CallbackContext;
+import org.apache.cordova.api.CordovaInterface;
+import org.apache.cordova.api.CordovaPlugin;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.net.ConnectivityManager;
+import android.os.Looper;
+import android.util.Log;
+import org.apache.cordova.api.PluginResult;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+
+
+
+public class BluetoothPlugin extends CordovaPlugin {
+
+	private static final String LOG_TAG = "BluetoothPlugin";
+    public static final String ACTION_DISCOVER_DEVICES="listDevices";
+	public static final String ACTION_LIST_BOUND_DEVICES="listBoundDevices";
+	public static final String ACTION_IS_BT_ENABLED="isBTEnabled";
+	public static final String ACTION_ENABLE_BT="enableBT";
+	public static final String ACTION_DISABLE_BT="disableBT";
+	public static final String ACTION_PAIR_BT="pairBT";
+	public static final String ACTION_UNPAIR_BT="unPairBT";
+	public static final String ACTION_STOP_DISCOVERING_BT="stopDiscovering";
+	public static final String ACTION_IS_BOUND_BT="isBound";
+	private static BluetoothAdapter btadapter;	
+	private ArrayList<BluetoothDevice> found_devices;
+	private boolean discovering=false;
+	private Context context;
+	
+	/* (non-Javadoc)
+	 * @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String)
+	 */
+    private CallbackContext callbackContext;
+
+    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
+        super.initialize(cordova, webView);
+        context = this.cordova.getActivity().getBaseContext();
+        
+        // Register for broadcasts when a device is discovered
+        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
+        context.registerReceiver(mReceiver, filter);
+      
+        // Register for broadcasts when discovery starts
+        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
+        context.registerReceiver(mReceiver, filter);
+      
+        // Register for broadcasts when discovery has finished
+        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
+        context.registerReceiver(mReceiver, filter);  
+             
+        // Register for broadcasts when connectivity state changes
+        filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
+        context.registerReceiver(mReceiver, filter);  
+    }
+    
+    @Override
+    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
+		Log.d(LOG_TAG, "Plugin Called");
+		this.callbackContext = callbackContext;
+		PluginResult result = null;
+       
+		//Looper.prepare();
+		btadapter= BluetoothAdapter.getDefaultAdapter();
+		found_devices=new ArrayList<BluetoothDevice>(); 
+		
+		if (ACTION_DISCOVER_DEVICES.equals(action)) {
+			try {
+				
+				Log.d(LOG_TAG, "We're in "+ACTION_DISCOVER_DEVICES);
+				
+				found_devices.clear();
+				discovering=true;
+				
+		        if (btadapter.isDiscovering()) {
+		        	btadapter.cancelDiscovery();
+		        }
+		        
+                Log.i(LOG_TAG,"Discovering devices...");
+                btadapter.startDiscovery();     
+				
+				result = new PluginResult(PluginResult.Status.NO_RESULT);
+                result.setKeepCallback(true);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+			
+			
+		} else 	if (ACTION_IS_BT_ENABLED.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_IS_BT_ENABLED);
+				
+				boolean isEnabled = btadapter.isEnabled();
+				
+				Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Returning "+ "is Bluetooth Enabled? "+isEnabled);
+				result = new PluginResult(PluginResult.Status.OK, isEnabled);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_IS_BT_ENABLED, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+		
+			
+			
+			
+			
+		} else 	if (ACTION_ENABLE_BT.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_ENABLE_BT);
+				
+				boolean enabled = false;
+				
+				Log.d(LOG_TAG, "Enabling Bluetooth...");
+				
+				if (btadapter.isEnabled())
+				{
+				  enabled = true;
+				} else {
+				  enabled = btadapter.enable();
+				}
+
+				
+				Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Returning "+ "Result: "+enabled);
+				result = new PluginResult(PluginResult.Status.OK, enabled);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_ENABLE_BT, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+			
+			
+		} else 	if (ACTION_DISABLE_BT.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_DISABLE_BT);
+				
+				boolean disabled = false;
+				
+				Log.d(LOG_TAG, "Disabling Bluetooth...");
+				
+				if (btadapter.isEnabled())
+				{
+					disabled = btadapter.disable();
+				} else {
+					disabled = true;
+				}				
+								
+				Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Returning "+ "Result: "+disabled);
+				result = new PluginResult(PluginResult.Status.OK, disabled);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_DISABLE_BT, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+			
+						
+		} else 	if (ACTION_PAIR_BT.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_PAIR_BT);
+				
+				String addressDevice = args.getString(0);
+				
+				if (btadapter.isDiscovering()) {
+		        	btadapter.cancelDiscovery();
+		        }
+
+				BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
+				boolean paired = false;
+							
+				Log.d(LOG_TAG,"Pairing with Bluetooth device with name " + device.getName()+" and address "+device.getAddress());
+		          	
+				try {
+					Method m = device.getClass().getMethod("createBond");
+					paired = (Boolean) m.invoke(device);					
+				} catch (Exception e) 
+				{
+					e.printStackTrace();
+				}  
+				
+				
+				Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Returning "+ "Result: "+paired);
+				result = new PluginResult(PluginResult.Status.OK, paired);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_PAIR_BT, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+			
+						
+		} else 	if (ACTION_UNPAIR_BT.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_UNPAIR_BT);
+				
+				String addressDevice = args.getString(0);
+				
+				if (btadapter.isDiscovering()) {
+		        	btadapter.cancelDiscovery();
+		        }
+
+				BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
+				boolean unpaired = false;
+							
+				Log.d(LOG_TAG,"Unpairing Bluetooth device with " + device.getName()+" and address "+device.getAddress());
+		          	
+				try {
+					Method m = device.getClass().getMethod("removeBond");
+					unpaired = (Boolean) m.invoke(device);					
+				} catch (Exception e) 
+				{
+					e.printStackTrace();
+				}  
+				
+				
+				Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Returning "+ "Result: "+unpaired);
+				result = new PluginResult(PluginResult.Status.OK, unpaired);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_UNPAIR_BT, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+			
+						
+		} else 	if (ACTION_LIST_BOUND_DEVICES.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_LIST_BOUND_DEVICES);
+				
+				Log.d(LOG_TAG,"Getting paired devices...");
+				Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices();
+				int count =0;	
+				String resultBoundDevices="[ ";
+				if (pairedDevices.size() > 0) {					
+					for (BluetoothDevice device : pairedDevices) 
+					{						
+						Log.i(LOG_TAG,device.getName() + " "+device.getAddress()+" "+device.getBondState());
+						
+						if ((device.getName()!=null) && (device.getBluetoothClass()!=null)){
+							resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," +
+				   				"\"address\" : \"" + device.getAddress() + "\" ," +
+				   				"\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }";
+							 if (count<pairedDevices.size()-1) resultBoundDevices = resultBoundDevices + ",";					   
+						} else Log.i(LOG_TAG,device.getName() + " Problems retrieving attributes. Device not added ");
+						 count++;
+					 }			    
+					
+				}
+				
+				resultBoundDevices= resultBoundDevices + "] ";
+				
+				Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Returning "+ resultBoundDevices);
+				result = new PluginResult(PluginResult.Status.OK, resultBoundDevices);
+				
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_LIST_BOUND_DEVICES, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}	
+			
+			
+			
+			
+			
+		} else 	if (ACTION_STOP_DISCOVERING_BT.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_STOP_DISCOVERING_BT);
+				
+				boolean stopped = true;
+				
+				Log.d(LOG_TAG, "Stop Discovering Bluetooth Devices...");
+				
+				if (btadapter.isDiscovering())
+				{
+					Log.i(LOG_TAG,"Stop discovery...");	
+					stopped = btadapter.cancelDiscovery();
+		        	discovering=false;
+				}				
+				
+			
+				Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Returning "+ "Result: "+stopped);
+				result = new PluginResult(PluginResult.Status.OK, stopped);
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_STOP_DISCOVERING_BT, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+			
+			
+		} else 	if (ACTION_IS_BOUND_BT.equals(action)) {
+			try {							
+				Log.d(LOG_TAG, "We're in "+ACTION_IS_BOUND_BT);
+				String addressDevice = args.getString(0);
+				BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
+				Log.i(LOG_TAG,"BT Device in state "+device.getBondState());	
+				
+				boolean state = false;
+				
+				if (device!=null && device.getBondState()==12) 
+					state =  true;
+				else
+					state = false;
+				
+				Log.d(LOG_TAG,"Is Bound with " + device.getName()+" - address "+device.getAddress());
+		          				
+				
+				Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Returning "+ "Result: "+state);
+				result = new PluginResult(PluginResult.Status.OK, state);
+				
+				
+			} catch (Exception Ex) {
+				Log.d("BluetoothPlugin - "+ACTION_IS_BOUND_BT, "Got Exception "+ Ex.getMessage());
+				result = new PluginResult(PluginResult.Status.ERROR);
+			}
+			
+			
+			
+		
+		
+		} else {
+			result = new PluginResult(PluginResult.Status.INVALID_ACTION);
+			Log.d(LOG_TAG, "Invalid action : "+action+" passed");
+		}
+		this.callbackContext.sendPluginResult(result);
+		return true;
+	}
+	
+	
+	
+	
+	public void setDiscovering(boolean state){
+		discovering=state;
+	}
+
+	
+	
+	public void addDevice(BluetoothDevice device){		
+		if (!found_devices.contains(device))
+		{
+			Log.i(LOG_TAG,"Device stored ");
+			found_devices.add(device);
+		}
+	}
+	
+	
+	
+    @Override
+	public void onDestroy() {
+		// TODO Auto-generated method stub
+    	Log.i(LOG_TAG,"onDestroy "+this.getClass());
+    	context.unregisterReceiver(mReceiver);
+    	super.onDestroy();
+	}
+	
+	
+    
+    /** BroadcastReceiver to receive bluetooth events */    
+	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+	    public void onReceive(Context context, Intent intent) 
+	    {
+	    	
+	        String action = intent.getAction();
+	        Log.i(LOG_TAG,"Action: "+action);
+	        
+	        // When discovery finds a device	        
+	        if (BluetoothDevice.ACTION_FOUND.equals(action)) 
+	        {	        	
+	            // Get the BluetoothDevice object from the Intent
+	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+	            Log.i(LOG_TAG,"Device found "+device.getName()+ " "+device.getBondState()+" " + device.getAddress());
+	       
+	            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {	
+	            	Log.i(LOG_TAG,"Device not paired");
+	            	addDevice(device);
+	            }else Log.i(LOG_TAG,"Device already paired");	         
+	         
+	        // When discovery starts	
+	        }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
+	        	
+	        	Log.i(LOG_TAG,"Discovery started");
+	        	setDiscovering(true);
+	        	
+	        // When discovery finishes	
+            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
+            	
+            	Log.i(LOG_TAG,"Discovery finilized");
+            	setDiscovering(false);
+            	JSONArray devicesFound = new JSONArray();
+                for (BluetoothDevice device : found_devices) {
+                    Log.i(LOG_TAG,device.getName() + " "+device.getAddress()+" "+device.getBondState());
+                    if ((device.getName()!=null) && (device.getBluetoothClass()!=null)) {
+                        JSONObject theDevice = new JSONObject();
+                        try {
+                            theDevice.put("name", device.getName());
+                            theDevice.put("address", device.getAddress());
+                            theDevice.put("class", device.getBluetoothClass().getDeviceClass());
+                            devicesFound.put(theDevice);
+                        } catch (JSONException e) {
+                            Log.e(LOG_TAG, e.getMessage(), e);
+                        }
+                    } else {
+                        Log.i(LOG_TAG,device.getName() + " Problems retrieving attributes. Device not added ");
+                    }
+                }   
+                
+                Log.d("BluetoothPlugin - "+ACTION_DISCOVER_DEVICES, "Returning: "+ devicesFound);
+                PluginResult result = new PluginResult(PluginResult.Status.OK, devicesFound);
+                callbackContext.sendPluginResult(result);	
+            }
+	    }
+    };
+
+}