Giter Site home page Giter Site logo

don / bluetoothserial Goto Github PK

View Code? Open in Web Editor NEW
1.1K 68.0 667.0 9.51 MB

Cordova (PhoneGap) Plugin for Serial Communication over Bluetooth

License: Other

JavaScript 9.81% Java 33.05% Objective-C 40.19% C 2.90% C# 14.06%
bluetooth bluetooth-low-energy cordova-plugin

bluetoothserial's Introduction

Bluetooth Serial Plugin for PhoneGap

This plugin enables serial communication over Bluetooth. It was written for communicating between Android or iOS and an Arduino.

Android and Windows Phone use Classic Bluetooth. iOS uses Bluetooth Low Energy.

Supported Platforms

Supporting other Bluetooth Low Energy hardware

Limitations

  • The phone must initiate the Bluetooth connection
  • iOS Bluetooth Low Energy requires iPhone 4S, iPhone5, iPod 5, or iPad3+
  • Will not connect Android to Android*
  • Will not connect iOS to iOS*

Installing

Install with Cordova cli

$ cordova plugin add cordova-plugin-bluetooth-serial

Note that this plugin's id changed from com.megster.cordova.bluetoothserial to cordova-plugin-bluetooth-serial as part of the migration from the Cordova plugin repo to npm.

Examples

There are some sample projects included with the plugin.

API

Methods

connect

Connect to a Bluetooth device.

bluetoothSerial.connect(macAddress_or_uuid, connectSuccess, connectFailure);

Description

Function connect connects to a Bluetooth device. The callback is long running. Success will be called when the connection is successful. Failure is called if the connection fails, or later if the connection disconnects. An error message is passed to the failure callback.

Android

For Android, connect takes a MAC address of the remote device.

iOS

For iOS, connect takes the UUID of the remote device. Optionally, you can pass an empty string and the plugin will connect to the first BLE peripheral.

Windows Phone

For Windows Phone, connect takes a MAC address of the remote device. The MAC address can optionally surrounded with parenthesis. e.g. (AA:BB:CC:DD:EE:FF)

Parameters

  • macAddress_or_uuid: Identifier of the remote device.
  • connectSuccess: Success callback function that is invoked when the connection is successful.
  • connectFailure: Error callback function, invoked when error occurs or the connection disconnects.

connectInsecure

Connect insecurely to a Bluetooth device.

bluetoothSerial.connectInsecure(macAddress, connectSuccess, connectFailure);

Description

Function connectInsecure works like connect, but creates an insecure connection to a Bluetooth device. See the Android docs for more information.

Android

For Android, connectInsecure takes a macAddress of the remote device.

iOS

connectInsecure is not supported on iOS.

Windows Phone

connectInsecure is not supported on Windows Phone.

Parameters

  • macAddress: Identifier of the remote device.
  • connectSuccess: Success callback function that is invoked when the connection is successful.
  • connectFailure: Error callback function, invoked when error occurs or the connection disconnects.

disconnect

Disconnect.

bluetoothSerial.disconnect([success], [failure]);

Description

Function disconnect disconnects the current connection.

Parameters

  • success: Success callback function that is invoked after the connection is disconnected. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

write

Writes data to the serial port.

bluetoothSerial.write(data, success, failure);

Description

Function write data to the serial port. Data can be an ArrayBuffer, string, array of integers, or a Uint8Array.

Internally string, integer array, and Uint8Array are converted to an ArrayBuffer. String conversion assume 8bit characters.

Parameters

  • data: ArrayBuffer of data
  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

// string
bluetoothSerial.write("hello, world", success, failure);

// array of int (or bytes)
bluetoothSerial.write([186, 220, 222], success, failure);

// Typed Array
var data = new Uint8Array(4);
data[0] = 0x41;
data[1] = 0x42;
data[2] = 0x43;
data[3] = 0x44;
bluetoothSerial.write(data, success, failure);

// Array Buffer
bluetoothSerial.write(data.buffer, success, failure);

available

Gets the number of bytes of data available.

bluetoothSerial.available(success, failure);

Description

Function available gets the number of bytes of data available. The bytes are passed as a parameter to the success callback.

Parameters

  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.available(function (numBytes) {
    console.log("There are " + numBytes + " available to read.");
}, failure);

read

Reads data from the buffer.

bluetoothSerial.read(success, failure);

Description

Function read reads the data from the buffer. The data is passed to the success callback as a String. Calling read when no data is available will pass an empty String to the callback.

Parameters

  • success: Success callback function that is invoked with the number of bytes available to be read.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.read(function (data) {
    console.log(data);
}, failure);

readUntil

Reads data from the buffer until it reaches a delimiter.

bluetoothSerial.readUntil('\n', success, failure);

Description

Function readUntil reads the data from the buffer until it reaches a delimiter. The data is passed to the success callback as a String. If the buffer does not contain the delimiter, an empty String is passed to the callback. Calling read when no data is available will pass an empty String to the callback.

Parameters

  • delimiter: delimiter
  • success: Success callback function that is invoked with the data.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.readUntil('\n', function (data) {
    console.log(data);
}, failure);

subscribe

Subscribe to be notified when data is received.

bluetoothSerial.subscribe('\n', success, failure);

Description

Function subscribe registers a callback that is called when data is received. A delimiter must be specified. The callback is called with the data as soon as the delimiter string is read. The callback is a long running callback and will exist until unsubscribe is called.

Parameters

  • delimiter: delimiter
  • success: Success callback function that is invoked with the data.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

// the success callback is called whenever data is received
bluetoothSerial.subscribe('\n', function (data) {
    console.log(data);
}, failure);

unsubscribe

Unsubscribe from a subscription.

bluetoothSerial.unsubscribe(success, failure);

Description

Function unsubscribe removes any notification added by subscribe and kills the callback.

Parameters

  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.unsubscribe();

subscribeRawData

Subscribe to be notified when data is received.

bluetoothSerial.subscribeRawData(success, failure);

Description

Function subscribeRawData registers a callback that is called when data is received. The callback is called immediately when data is received. The data is sent to callback as an ArrayBuffer. The callback is a long running callback and will exist until unsubscribeRawData is called.

Parameters

  • success: Success callback function that is invoked with the data.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

// the success callback is called whenever data is received
bluetoothSerial.subscribeRawData(function (data) {
    var bytes = new Uint8Array(data);
    console.log(bytes);
}, failure);

unsubscribeRawData

Unsubscribe from a subscription.

bluetoothSerial.unsubscribeRawData(success, failure);

Description

Function unsubscribeRawData removes any notification added by subscribeRawData and kills the callback.

Parameters

  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.unsubscribeRawData();

clear

Clears data in the buffer.

bluetoothSerial.clear(success, failure);

Description

Function clear removes any data from the receive buffer.

Parameters

  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

list

Lists bonded devices

bluetoothSerial.list(success, failure);

Description

Android

Function list lists the paired Bluetooth devices. The success callback is called with a list of objects.

Example list passed to success callback. See BluetoothDevice and BluetoothClass#getDeviceClass.

[{
    "class": 276,
    "id": "10:BF:48:CB:00:00",
    "address": "10:BF:48:CB:00:00",
    "name": "Nexus 7"
}, {
    "class": 7936,
    "id": "00:06:66:4D:00:00",
    "address": "00:06:66:4D:00:00",
    "name": "RN42"
}]

iOS

Function list lists the discovered Bluetooth Low Energy peripheral. The success callback is called with a list of objects.

Example list passed to success callback for iOS.

[{
    "id": "CC410A23-2865-F03E-FC6A-4C17E858E11E",
    "uuid": "CC410A23-2865-F03E-FC6A-4C17E858E11E",
    "name": "Biscuit",
    "rssi": -68
}]

The advertised RSSI may be included if available.

Windows Phone

Function list lists the paired Bluetooth devices. The success callback is called with a list of objects.

Example list passed to success callback for Windows Phone.

[{
    "id": "(10:BF:48:CB:00:00)",
    "name": "Nexus 7"
}, {
    "id": "(00:06:66:4D:00:00)",
    "name": "RN42"
}]

Note

id is the generic name for uuid or [mac]address so that code can be platform independent.

Parameters

  • success: Success callback function that is invoked with a list of bonded devices.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.list(function(devices) {
    devices.forEach(function(device) {
        console.log(device.id);
    })
}, failure);

isConnected

Reports the connection status.

bluetoothSerial.isConnected(success, failure);

Description

Function isConnected calls the success callback when connected to a peer and the failure callback when not connected.

Parameters

  • success: Success callback function, invoked when device connected.
  • failure: Error callback function, invoked when device is NOT connected.

Quick Example

bluetoothSerial.isConnected(
    function() {
        console.log("Bluetooth is connected");
    },
    function() {
        console.log("Bluetooth is *not* connected");
    }
);

isEnabled

Reports if bluetooth is enabled.

bluetoothSerial.isEnabled(success, failure);

Description

Function isEnabled calls the success callback when bluetooth is enabled and the failure callback when bluetooth is not enabled.

Parameters

  • success: Success callback function, invoked when Bluetooth is enabled.
  • failure: Error callback function, invoked when Bluetooth is NOT enabled.

Quick Example

bluetoothSerial.isEnabled(
    function() {
        console.log("Bluetooth is enabled");
    },
    function() {
        console.log("Bluetooth is *not* enabled");
    }
);

readRSSI

Reads the RSSI from the connected peripheral.

bluetoothSerial.readRSSI(success, failure);

Description

Function readRSSI calls the success callback with the rssi.

BLE only This function is experimental and the API may change

Parameters

  • success: Success callback function that is invoked with the rssi value.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.readRSSI(
    function(rssi) {
        console.log(rssi);
    }
);

showBluetoothSettings

Show the Bluetooth settings on the device.

bluetoothSerial.showBluetoothSettings(success, failure);

Description

Function showBluetoothSettings opens the Bluetooth settings on the operating systems.

iOS

showBluetoothSettings is not supported on iOS.

Parameters

  • success: Success callback function [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.showBluetoothSettings();

enable

Enable Bluetooth on the device.

bluetoothSerial.enable(success, failure);

Description

Function enable prompts the user to enable Bluetooth.

Android

enable is only supported on Android and does not work on iOS or Windows Phone.

If enable is called when Bluetooth is already enabled, the user will not prompted and the success callback will be invoked.

Parameters

  • success: Success callback function, invoked if the user enabled Bluetooth.
  • failure: Error callback function, invoked if the user does not enabled Bluetooth.

Quick Example

bluetoothSerial.enable(
    function() {
        console.log("Bluetooth is enabled");
    },
    function() {
        console.log("The user did *not* enable Bluetooth");
    }
);

discoverUnpaired

Discover unpaired devices

bluetoothSerial.discoverUnpaired(success, failure);

Description

Android

Function discoverUnpaired discovers unpaired Bluetooth devices. The success callback is called with a list of objects similar to list, or an empty list if no unpaired devices are found.

Example list passed to success callback.

[{
    "class": 276,
    "id": "10:BF:48:CB:00:00",
    "address": "10:BF:48:CB:00:00",
    "name": "Nexus 7"
}, {
    "class": 7936,
    "id": "00:06:66:4D:00:00",
    "address": "00:06:66:4D:00:00",
    "name": "RN42"
}]

The discovery process takes a while to happen. You can register notify callback with setDeviceDiscoveredListener. You may also want to show a progress indicator while waiting for the discover proces to finish, and the sucess callback to be invoked.

Calling connect on an unpaired Bluetooth device should begin the Android pairing process.

iOS

discoverUnpaired is not supported on iOS. iOS uses Bluetooth Low Energy and list discovers devices without pairing.

Windows Phone

discoverUnpaired is not supported on Windows Phone.

Parameters

  • success: Success callback function that is invoked with a list of unpaired devices.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

bluetoothSerial.discoverUnpaired(function(devices) {
    devices.forEach(function(device) {
        console.log(device.id);
    })
}, failure);

setDeviceDiscoveredListener

Register a notify callback function to be called during bluetooth device discovery. For callback to work, discovery process must be started with discoverUnpaired. There can be only one registered callback.

Example object passed to notify callback.

{
    "class": 276,
    "id": "10:BF:48:CB:00:00",
    "address": "10:BF:48:CB:00:00",
    "name": "Nexus 7"
}

iOS & Windows Phone

See discoverUnpaired.

Parameters

  • notify: Notify callback function that is invoked when device is discovered during discovery process.

Quick Example

bluetoothSerial.setDeviceDiscoveredListener(function(device) {
	console.log('Found: '+device.id);
});

clearDeviceDiscoveredListener

Clears notify callback function registered with setDeviceDiscoveredListener.

Quick Example

bluetoothSerial.clearDeviceDiscoveredListener();

setName

Sets the human readable device name that is broadcasted to other devices.

bluetoothSerial.setName(newName);

Android

For Android, setName takes a String for the new name.

iOS

Not currently implemented.

Windows Phone

Not currently implemented.

Parameters

  • newName: Desired name of device.

Quick Example

bluetoothSerial.setName("Really cool name");

setDiscoverable

Makes the device discoverable by other devices.

bluetoothSerial.setDiscoverable(discoverableDuration);

Android

For Android, setDiscoverable takes an int for the number of seconds device should be discoverable. A time of 0 will make it permanently discoverable.

iOS

Not currently implemented.

Windows Phone

Not currently implemented.

Parameters

  • discoverableDuration: Desired number of seconds device should be discoverable for.

Quick Example

bluetoothSerial.setDiscoverable(0);

Misc

Where does this work?

Android

Current development is done with Cordova 4.2 on Android 5. Theoretically this code runs on PhoneGap 2.9 and greater. It should support Android-10 (2.3.2) and greater, but I only test with Android 4.x+.

Development Devices include

  • Nexus 5 with Android 5
  • Samsung Galaxy Tab 10.1 (GT-P7510) with Android 4.0.4 (see Issue #8)
  • Google Nexus S with Android 4.1.2
  • Nexus 4 with Android 5
  • Samsung Galaxy S4 with Android 4.3

On the Arduino side I test with Sparkfun Mate Silver and the Seeed Studio Bluetooth Shield. The code should be generic and work with most hardware.

I highly recommend Adafruit's Bluefruit EZ-Link.

iOS

NOTE: Currently iOS only works with RedBear Labs Hardware, Adafruit Bluefruit LE, Laird BL600, and BlueGiga UART services

This plugin was originally developed with Cordova 3.4 using iOS 7.x on an iPhone 5s connecting to a RedBearLab BLEMini. Ensure that you have update the BLE Mini firmware to at least Biscuit-UART_20130313.bin.

Most development is now done with iOS 8 with Cordova 4.2 using RedBear Lab BLE Shield or Adafruit Bluefruit LE Friend.

Supporting other BLE hardware

For Bluetooth Low Energy, this plugin supports some hardware running known UART-like services, but can support any Bluetooth Low Energy hardware with a "serial like" service. This means a transmit characteristic that is writable and a receive characteristic that supports notification.

Edit BLEdefines.h and adjust the UUIDs for your service.

See Issue 141 for details on how to add support for Amp'ed RF Technology BT43H.

Props

Android

Most of the Bluetooth implementation was borrowed from the Bluetooth Chat example in the Android SDK.

iOS

The iOS code uses RedBearLab's BLE_Framework.

API

The API for available, read, readUntil was influenced by the BtSerial Library for Processing for Arduino

Wrong Bluetooth Plugin?

If you don't need serial over Bluetooth, try the PhoneGap Bluetooth Plugin for Android or perhaps phonegap-plugin-bluetooth.

If you need generic Bluetooth Low Energy support checkout my Cordova BLE Plugin.

If you need BLE for RFduino checkout my RFduino Plugin.

What format should the Mac Address be in?

An example a properly formatted mac address is AA:BB:CC:DD:EE:FF

Feedback

Try the code. If you find an problem or missing feature, file an issue or create a pull request.

bluetoothserial's People

Contributors

chrismorter avatar davide-sd avatar don avatar johnmclear avatar legege avatar marvinmarnold avatar mrtomhoward avatar panickev avatar pardo-bsso avatar rhinolance avatar shokre avatar tigoe avatar usb2win avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bluetoothserial's Issues

Error when receiving two consecutive messages

When receiving two consecutive messages, in the handleMessage of BluetoothSerial the second message, msg.obj is refer to the first one!

I resolve this by changing the run() in BluetoothSerialService, creating a byte[] in every cycle:

before:

public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothSerial.MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothSerialService.this.start();
                break;
            }
        }
    }

after:

public void run() {
Log.i(TAG, "BEGIN mConnectedThread");

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                byte[] buffer = new byte[1024];

                // Read from the InputStream
                int bytes = mmInStream.read(buffer);

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothSerial.MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothSerialService.this.start();
                break;
            }
        }

Add an cleaner example skeleton.

Not sure if this might help others, but I wrote the following code to implement your ble library.

var ble = (function() {
  var _bluetoothSerial = cordova.require('bluetoothSerial');
  return {
    peripherals : [],
    subscribe: function(callback) {
        _bluetoothSerial.subscribe("\n", callback, this.error("Subscribe Failed"));
    },
    list: function(callback) {
        _bluetoothSerial.list(ondevicelist, this.error("Could not get device list"));
        var that = this;
        function ondevicelist(devices) {
          for(var i = 0; i < devices.length; ++i) {
            if(devices[i].hasOwnProperty('uuid')) {
              that.peripherals[devices[i].uuid] = devices[i];
            }
          }

          if(devices.length > 0) {
            callback(that.peripherals);
          }
        }
    },
    connect: function(params) {
      _bluetoothSerial.connect(params.uuid, params.onConnect, params.onFailure);
    },
    sendData: function(text, callback) {
        _bluetoothSerial.write(text, callback);
    },
    error: function(message) {
      //alert(message);
        /* Error Handling Here */
    }
  };
})();

cc2540 Support (was Cordova 3.1.0-0.2.0 Support?)

I can't connect to my BLE module for Arduino. I changed the Macaddress to my device and below is the log from Xcode.

2013-11-08 01:42:29.789 violin[3981:60b] Bluetooth Serial Cordova Plugin - BLE version
2013-11-08 01:42:29.791 violin3981:60b2013 Don Coleman
Status of CoreBluetooth central manager changed 5 (State powered up and ready (CBCentralManagerStatePoweredOn))

2013-11-08 01:42:32.467 violin[3981:60b] write
Could not find service with UUID <d3e60000 8f3640d6 b2d5c5d9 f5e81869> on peripheral with UUID NULL

connectInsecure No Device Pin

I am trying to make a connection to a device that does not accept a PIN, however I have been unsuccessful using the connectInsecure method.

Are there any pre-requisites for an insecure connection to work?

I am attempting a connection using the SimpleSerial example with the device MAC address, connect works but prompts for a PIN, connectInsecure does nothing.

Error while installing using CLI

I get the following error when installing via Cordova CLI:

[Error: grafting xml as selector "plugins" from "/pasth/to/my/projects/config.xml" during config install went bad :(]

phonegap'pers welcomed?

Hi
googled my way to your repo, in my efforts to build a small app which will let me use pocket bluetooth barcode scanners with ipod touch and one/two REST-ful webservices to register where my kids are at <:)

I did a fresh project to test the bluetooth comm

$ phonegap create blue dk.alco.blue Blue
[phonegap] created project at /Users/walther/Documents/src/blue
$ cd blue
$ phonegap local plugin add https://github.com/don/BluetoothSerial.git
[phonegap] adding the plugin: https://github.com/don/BluetoothSerial.git
[phonegap] successfully added the plugin

and then I was fresh out of ideas :)

  • trying to take the SimpleSerial example files into my project brought me no lunch (probably 'cause I haven't got the faintest idea what I'm doing, where files are to be at, and how the entire 'eco-system' is set up

(I've done HTML since the IMG tag was a novelty and JS back when closures where not even opened yet – but with less than 1 line of Objective-C under my belt, I feel quite crippled around PhoneGap)

I sure could do with a kind push <:)

Question: How do I Unsubscribe, disconnect and then connect with a new BTdevice automatically?

I've been breaking my head to make this work and I keep on receiving the "Unable to connect to device" error when it reaches the connect stage of the code.
The only way it can work is if I disconnect and when successful, automatically unsubscribe and then manually invoke the bluetoothSerial.connect.
The code that is not working is bellow:

                function(){
                bluetoothSerial.unsubscribe(
                function (data) {
                console.log("UNSUBSCRIBED-> "+data);
                // CONNECT TO NEXT BTDEVICE
                app.connect()

                },
                app.showError
        );
                },     // stop listening to the port
                app.showError      // show the error if you fail
            );
showError: function(error) {
        console.log("ERROR RECEIVED -> "+ error);
    },
connect: function () {
            // attempt to connect:
            console.log("CONNECT");
            console.log("TRYING TO CONNECT WITH Mac> "+app.macAddress);
            bluetoothSerial.connect(
                app.macAddress,  // device to connect to
                app.openPort,    // start listening if you succeed
                app.showError    // show the error if you fail
        );
    }, 

Thanks!

Installing without Cordova cli

I have manually installed Phonegap, and have not used the CLI. Is there a way of installing the BluetoothSerial plugin without the CLI and Build?

Thanks, James.

Unable to Connect to Device (Android 4.4.2)

I am unable to connect to a Bluetooth based Barcode Scanner using the connect function.

I know the plugin is installed and working because it can find the device using the bluetoothSerial.list function. I've also read over the given plugin examples and as far as I can tell my implementation is correct.

I am passing the bluetoothSerial.connect function a hardcoded MAC address (this is just for testing and will change to a dynamic variable later). Here is the JavaScript code i'm using:

bluetoothSerial.connect('00:06:66:A0:4F:36', function () {
alert('connected');
}, function () {
alert('There was a problem connecting to the bluetooth device. Please reconnect device.');
});

This code has never produced a successful connection. Am i doing something wrong?

Device info: Nexus 10 (Android vers. 4.4.2)

List Function

The List function is supposed to show all available bluetooth devices, correct?

If so, then why does my device (an Estimote iBeacon) not show up? This iBeacon is supposed to communicate via Bluetooth LE. They do show up when I run the Estimote Demo App however. Any ideas?

ios, .list function always return 0 devices

Hi, thanks for the plugin!

But I am experiencing the app keep cannot find any devices.

I tested with peripheral emulator 'LightBlue', and other bluetooth LE devices detector, all working fine but when I try to discover with this plugin it detect none.

Am I missing something on installation?

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2013-08-06 14:06:55.754 XXX[742:907] Bluetooth Serial Cordova Plugin - BLE version
2013-08-06 14:06:55.754 XXX742:9072013 Don Coleman
2013-08-06 14:06:55.759 XXX[742:907] subscribe
Status of CoreBluetooth central manager changed 5 (State powered up and ready (CBCentralManagerStatePoweredOn))

2013-08-06 14:06:57.770 XXX[742:907] Looking for Bluetooth Devices...
2013-08-06 14:06:57.771 XXX[742:907] Scanning for BLE Peripherals
2013-08-06 14:06:57.772 XXX[742:907] scanForPeripheralsWithServices
Stopped Scanning

Known peripherals : 0

List of currently known peripherals :

2013-08-06 14:07:00.778 XXX[742:907] No Bluetooth Peripherals Discovered.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$ cordova plugin add com.megster.cordova.bluetooth

Exampl: CHAT
This command in the terminal does not work:
[Error: ENOENT, no such file or directory 'com.megster.cordova.BluetoothSerial/plugin.xml']

The previous one[$ cordova plugin add ~/BluetoothSerial] works but Im not sure if that is right since you changed the readme file.

Have you tested BluetoothSerial with iOS7? Does it work?

Have you tested the BluetoothSerial plugin with iOS7? I have been writing my own simple module for communicating with a device and it works with iOS6 but not iOS7. If your plugin works with iOS7 (which seems to be more strict with permissions, etc. in Bluetooth than iOS6) then I will be greatly encouraged to look into this plugin.

Documentation

I think the example for isConnected() in documentation, isn't correct:
bluetoothSerial.isConnected(function (connected) {
console.log(connected); // true or false
}, failure);

Seeing the examples I think the correct way it's:
bluetoothSerial.isConnected(function () {
console.log("It's connected");
}, failure);

Dropped or swapped characters

Hello,

I am using Phonegap/this plugin/js for the first time to send Arduino serial data to an app.

Using the SimpleSerial example (bluetoothSerial.subscribe), I am seeing some issues with some lines being corrupted (swapped/removed/added characters in the received string).

Below is received data sent to console.log (viewed on comp w/adb logcat)

D/CordovaLog(16839): Received:[1.74, -13.43, 17.5341.82, 5241.82, 521, 23.88,1, 23.88, ]
D/CordovaLog(16839): Received:[1.54, -14.04, 17.94, 51.76, 42.03, 52.48, 26.75, 24.39, ]
D/CordovaLog(16839): Received:[0.20, -14.56, 17.8 41.82, 52.48, 41.2.48, 41.51, 34.13, ]
D/CordovaLog(16839): Received:[1.54, -142, 51.97,2, 51.97, 41.72, 39.77, 42.44, 34.95, ]
D/CordovaLog(16839): Received:[0.20, -15.07, 16.91, 51.56, 413, 42.5.7 34.8544, 34.85, ]
D/CordovaLog(16839): Received:[1.33, -14.04, 17.12, 51.76, 41.72, 344, 34.34, ] 34.34, ]
D/CordovaLog(16839): Received:[4.04, 174.04, 17.94, 51.86, 41.61, 52.48, 42., ] 34.24, ]
D/CordovaLog(16839): Received:[1.13, -14.35, 17.12, 51.86, 40.69, 533, 34.8533, 34.85, ]

This issue doesn't exist when using a Bluetooth app downloaded from the Play store.

Thanks

Built with Cordova 2.7.6
Device Samsung Galaxy S2
Android 4.0.3
Baud rate 9600
BT chipset: http://www.elecfreaks.com/store/download/datasheet/Bluetooth/Bluetooth%20HC-06.pdf

Add status method

bluetoothSerial.status(success, failure)

success handler will be called whenever the bluetooth connection status changes

Bluetooth Serial Plugin

Thanks for the plugin

I am trying to connect an iPhone 5 (iOS 6.1) and an iPad (ios 6) using bluetooth. these two devices are paired. I am using Bluetooth Serial Plugin.

On loading the app it shows the message "Looking for bluetooth devices…", then shows the message "Please pair a bluetooth device" even though the iPad and the iPhone 5 are paired.

Am I missing some thing? Please help

Thanks in advance

NSB App Studio

I'm trying to use the plugin in NSB AppStudio.

bluetoothSerial.isEnabled(success, unsuccess) gives me:

"Bluetooth is disabled" or "OK"

correctly according to the status of BT : Off or On,
therefore i assume that the program is working, but

bluetoothSerial.list(Success, Unsuccess) gives, in Success(result), this result:

[object Object],[object Object],[object Object],[object Object],[object Object]

where i suppose it should give a list of the existing Mac Addresses (??)

What's more:
MacAddress = "00:12:D1:7B:63:32" (got from another app for MAC finding) in
bluetoothSerial.connect(MacAddress, ConnectSuccess, ConnectFailure) gives

"Unable to connecto to device"

Anybody has any tips? Is it normal to receive those strings or is there any anomaly?

Bluetooth Serial Chat

onmessage is not called when a message is sent to the Serial Chat, however I can send data to the laptop.

I have tried it on the Bluetooth SPP app in the Play Store, and I can recieve it fine there.

This is the code not being called when a message is sent from the laptop.

    onmessage: function(message) {

        messages.value += "Them: " + message;
        messages.scrollTop = messages.scrollHeight;
    },

Using bluetoothSerial.list before CoreBluetooth initialised.

I'm trying to get this plugin working with the Laird BL600 BLE module, which includes a virtual serial port service. There are a few things that aren't quite working, but here's the first:-

Upon window.onload, I'm calling bluetoothSerial.list(..), however when I do this I get:

CoreBluetooth not correctly initialized !
State = 0 (State unknown (CBCentralManagerStateUnknown))

and then a moment later:

Status of CoreBluetooth central manager changed 5 (State powered up and ready (CBCentralManagerStatePoweredOn))

If I try calling bluetoothSerial.list(..) again, it works. I don't quite follow the logic on how Bluetooth is intialised by the plugin, but it appears that [self.CM scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:@BLE_DEVICE_SERVICE_UUID]] options:nil]; shouldn't run until centralManagerDidUpdateState fires and indicates state as CBCentralManagerStatePoweredOn? Or maybe I'm using the plugin incorrectly?

I'm running on an iPhone 4S, iOS 6.1.3.

iOS handle null peripheral name

2013-05-29 17:32:54.957 Chat[425:907] Finished load of: file:///var/mobile/Applications/C66A263B-B734-4224-8DF9-0AAE11994947/Chat.app/www/index.html
2013-05-29 17:32:56.634 Chat[425:907] Looking for Bluetooth Devices...
2013-05-29 17:32:56.635 Chat[425:907] Scanning for BLE Peripherals
2013-05-29 17:32:56.637 Chat[425:907] scanForPeripheralsWithServices
didDiscoverPeripheral

Duplicate UUID found updating ...
Stopped Scanning

Known peripherals : 1

List of currently known peripherals : 

0  |  3F034D6F-5653-1F03-8C4F-82454961B665

------------------------------------
Peripheral Info :
UUID : 3F034D6F-5653-1F03-8C4F-82454961B665
Name : (null)
-------------------------------------
2013-05-29 17:32:59.640 Chat[425:907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: name)'
*** First throw call stack:
(0x336922a3 0x3b37697f 0x335f4313 0xfb501 0xfac63 0x33fa9f53 0x336675df 0x33667291 0x33665f01 0x335d8ebd 0x335d8d49 0x371a02eb 0x354ee301 0xf8a3f 0xf8a00)
libc++abi.dylib: terminate called throwing an exception

BluetoothSerial.read vs BluetoothSerial.subscibe

Hi,

In the chat example, you have used "bluetoothSerial.subscribe" to listen to the messages. Would the process differ if "bluetoothSerial.read" is used? what is the difference between the two in terms of operation?

Adi

Eligible Devices

I see that others are modifying the code to make it work for other Arduino device radios. I want to know, before tweaking this code, is there a way to get this to work with iOS 7 devices and bluetooth serial devices without a BLE radio? Looking to pair a non Arduino device with a Bluetooth 2.0 SPP to my iPod Touch 5th gen.

Current attempts at using the connect function with the proper device MAC address resulting in the "Could not find peripheral" message.

Extract RSSI

Hi,

first of all thanks for the plugin.
I was wondering if is possible to extract the RSSI (strength of the signal) for the iOS platform for each device founded.

Thanks a lot,
OSNN

iOS crashes when received data can't be parsed into a string

iOS crashes when received data can't be parsed into a string

  • (void)bleDidReceiveData:(unsigned char *)data length:(int)length {

    2013-11-26 15:23:23.617 Count[843:60b] bleDidReceiveData
    (lldb) p s
    (NSString *) $1 = nil
    (lldb) p length
    (int) $2 = 2
    (lldb) p data
    (unsigned char *) $3 = 0x000bfbf3 "\x87\xfe"

Trouble Getting Started with Plugin in PhoneGap Build

Hi everyone,

I'm just getting started with app development and am wanting to use this plugin with PhoneGap Build. I've added the gap:plugin name="com.megster.cordova.bluetoothserial" / line to my config.xml file and when I build my app, the plugin does show up in the Plugins section of the build menu. Right now the app is just a tester so that I can get a feel for the Bluetooth plugin. So I have a button that I click and I append a paragraph that tells me if the Bluetooth is enabled or not. However, when I try the app on my phone, neither the success nor failure functions for the bluetoothSerial.isEnabled function is called. So I'm thinking that I might be missing something as far as setting up the plugin. Any ideas as to what's going on? I've looked at the examples and really am just having trouble following them.

I appreciate the help! Feel free to check out my repo at https://github.com/mpedersen15/bluetoothTest to see exactly what I'm doing wrong.

Thank you all in advance for the help and thanks Don for the plugin!

Bluetooth Plugin working with other BLE boards

Hi Don,
Nice job on this plugin ! How hard would it be to use it with other boards?

The OLP425 is a BLE module by Connect Blue. The board is built by Texas Instruments and the SDK is available from their website.

I was asked to work with this specific board on iOS. Would it require extensive changes to the plugin?

Thanks

Null Pointer on Nexus S

Nexus S

json.put("class", device.getBluetoothClass().getDeviceClass());

W/System.err( 2931): java.lang.NullPointerException
W/System.err( 2931): at com.megster.cordova.BluetoothSerial.listBondedDevices(BluetoothSerial.java:173)
W/System.err( 2931): at com.megster.cordova.BluetoothSerial.execute(BluetoothSerial.java:80)
W/System.err( 2931): at org.apache.cordova.CordovaPlugin.execute(CordovaPlugin.java:84)
W/System.err( 2931): at org.apache.cordova.CordovaPlugin.execute(CordovaPlugin.java:65)
W/System.err( 2931): at org.apache.cordova.PluginManager.execHelper(PluginManager.java:229)
W/System.err( 2931): at org.apache.cordova.PluginManager.exec(PluginManager.java:214)
W/System.err( 2931): at org.apache.cordova.ExposedJsApi.exec(ExposedJsApi.java:53)
W/System.err( 2931): at android.webkit.JWebCoreJavaBridge.sharedTimerFired(Native Method)
W/System.err( 2931): at android.webkit.JWebCoreJavaBridge.sharedTimerFired(Native Method)
W/System.err( 2931): at android.webkit.JWebCoreJavaBridge.fireSharedTimer(JWebCoreJavaBridge.java:92)
W/System.err( 2931): at android.webkit.JWebCoreJavaBridge.handleMessage(JWebCoreJavaBridge.java:108)
W/System.err( 2931): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err( 2931): at android.os.Looper.loop(Looper.java:137)
W/System.err( 2931): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:827)
W/System.err( 2931): at java.lang.Thread.run(Thread.java:856)

installing plugin fails

Hey there,

Im trying to use your plugin in a phonegap/cordova app.

Quite simply I use the command given in the readme file and I get this error:

C://.../npm/node_modules/cordova/node_modules/q/q.js:126
Error fetching plugin failed: Error: spawn ENOENT

Would you have any idea where that comes from?

Cheers

Subscribe function not working

I'm trying to use the plugin for an app which communicates with RFID reader through bluetooth module. I've successfully tested it on RDM6300 module. However, when I'm using it with EM18 RFID reader module which communicates in
10 ASCII DATA (card no.)+ 2 ASCII DATA (XOR result)
The subscribe function is not working.
In the first case (RDM6300) I passed delimeter as ''
In EM18 case I've tried using delimeter as '\n' or '' or 'ETX' but none of them is working. When I punch a rfid card, the data gets saved in buffer but does not invoke the subscribe function. I am able to read the buffered data using .read function.
Please suggest what shall I do to get it work with EM18 reader.

Connections from one Android device to Another

I know this was intended to connect with Arduino but it seems like connecting between a pair of android or ios devices could work too. Is this already the case? I fiddled with the examples for a while (using a nexus 7 and galaxy s4) but could not establish a connection.

The examples don't appear to have code to receive a connection in the javascript. Is that only in the arduino logic?

PhoneGap Build plugin stopped working on 12/13/2013

Hi—I posted a similar cry for help on the PGB community site, but since they say support for 3rd-party plugins is handled entirely by the authors, I wanted to post it here too, even though I know no changes have been checked into the code in months.

I am using this plugin to send data to a Bluetooth printer. Just this past Friday, the builds created through the PhoneGap Build service no longer seem to have the plugin built-in. If I try to print, I get the error "modue bluetoothSerial not found". This is despite the fact that the Plugins tab for the app on PGB still lists the correct plugin name and version (0.2.1), and the js/bluetoothSerial.js file is getting inserted correctly into the app.

Any possible ideas? Can you help me debug this?

Thanks...

Cordova 3.2.0

Cordova has released 3.2.0. The "cordova platform add android " command was working perfectly fine in 3.0.0 until I updated to 3.2.0. It constantly throws "[Error: ERROR : Make sure JAVA_HOME is set, as well as paths to your JDK and JRE for java.]"
It is not working even when i set the path.

I have no clue how to go about this. Please help!!

iOS to iOS communication

Thanks for the plugin!

Do you know how to do iOS to iOS communication? This would be amazing for creating local multiplayer games with PhoneGap.

This is not a bug

@don
I'm sorry, I tried to find ways to contact you, this was the only one I found :)
I have a question about this plugin -

Is this designed to work only with arduino, or can it work with any BT device? (I'm working with a custom built device, it's not built yet).
I managed to connect to BT devices but not read data from them.
plus, will it have a discovery option? (pair the device using this plugin?)

I'm sorry if this bothers you.
In case you want to answer, at [email protected]
thank you :)

Pairing problem with Android

Hello,
when I use the .connect function and a MAC address allready associated (to my android 4.0.4 galaxy tab 10.1) the system allways ask me for the pin code of the bluetooth device.

When I write the pin code the connection work correctly, but if I close the connection and reopen it the system ask me the PIN.

I checked at the system settings and the device is correctly paired.

Please help me :(

Thanks

Francesco

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.