nativescript-community / ble Goto Github PK
View Code? Open in Web Editor NEWConnect to and interact with Bluetooth LE peripherals.
Home Page: https://nativescript-community.github.io/ble/
License: MIT License
Connect to and interact with Bluetooth LE peripherals.
Home Page: https://nativescript-community.github.io/ble/
License: MIT License
When I try to pass the value as an Uint8Array
to call writeWithoutResponse
function, the command doesn't seem to be processed correctly.
However the same value presented as a string works fine.
Here is an example (the commented out line is for the code that works):
bluetooth.writeWithoutResponse({
serviceUUID: this.serviceUUID,
characteristicUUID: this.characteristicUUID,
peripheralUUID: this.deviceUUID,
// value: '0x71,0x20,0x40'
value: new Uint8Array([0x71, 0x20, 0x40])
})
When I tried to manually adapt the steps of Bluetooth._encodeValue
to copy the contents of my Uint8Array
- like below - then the instruction seems to be processed just fine.
var result = Array.create("byte", parts.length);
for (var i=0; i<val.length; i++) {
result[i] = val[i];
}
return result;
Am I using the Uint8Array
in a wrong way? This is the way I am used to use it with Web Bluetooth ;)
I used your Cordova plugin to talk to a AnD BLE scale with success.
Now porting the app over to NativeScript and using this plugin.
Ran into a problem on Android using writeWithoutResponse(). The old plugin waited for onCharacteristicWrite() to be called before calling the success callback. This plugin returns immediately.
Now when starting another BLE call after writeWithoutResponse() returns it fails.
I changed writeWithoutResponse() to use the same logic as write(), setting the onWritePromise, and it all works perfectly.
When I try to run the demo app in my phone "Redmi Note 3" Android version "6.0.1", I am not able to detect any other device, provided both the location and bluetooth are enabled in all the devices. Kindly help.
Right now, this only supports checking if Bluetooth is enabled or not. It'd be great if it allowed turning on Bluetooth from within the application. This way, the user wouldn't have to do it manually.
Just wondering..
About line 780:
console.log("Characteristic " + characteristicUUID + " does not have NOTIFY or INDICATE property set");
shouldn't it rather be:
reject("Characteristic " + characteristicUUID + " does not have NOTIFY or INDICATE property set");
return;
About lines 770, 771:
reject("Set notification failed for " + characteristicUUID);
return;
It seems some peripheral do no provide the descriptor even though they announce the characteristic is notifiable in the properties array. Does it make sense to instead do:
bluetoothGattDescriptor=new android.bluetooth.BluetoothGattDescriptor(clientCharacteristicConfigId, android.bluetooth.BluetoothGattDescriptor.PERMISSION_WRITE);
bluetoothGattCharacteristic.addDescriptor(bluetoothGattDescriptor);
console.log("BluetoothGattDescriptor created...")
At least that allowed me to be notified ;-)
Anyway, thanks for your plugin!
I am using an Android 6.0.1 device (Samsung S6 edge+) and NativeScript 2.5.
I am trying to use startScanning
function with serviceUUIDs
parameter? However I don’t seem to be able to make it to work.
Whenever I provide serviceUUIDs
I get 0 results
bluetooth.startScanning({
seconds: 3,
serviceUUIDs: ['ffe5'],
// serviceUUIDs: ['0000ffe5-0000-1000-8000-00805f9b34fb'],
onDiscovered: (peripheral: Peripheral) => {
console.log(`UUID: ${peripheral.UUID} name: ${peripheral.name}`)
}
})
I am certain that my device has a ffe5
service, as this is the service I use for sending instructions to it.
However when I use the same serviceUUIDs
with web bluetooth
in a web project it seems to work. So I assume that my serviceUUIDs are correct.
I’ve tried to use both a short notation serviceUUIDs: ['ffe5']
and a long one serviceUUIDs: ['0000ffe5-0000-1000-8000-00805f9b34fb']
neither seems to work
Hello,
I have an app that produces a ton of bluetooth traffic (it's transferring a devices firmware over bluetooth) and on ios, the console actually completely freezes and detaches due to excessive console logging. I've tested disabling console logging in bluetooth.android.js and bluetooth.ios.js and have seen the issue disappear.
I can see how console logging could be useful, but we should provide a way to either enable or disable it.
Would you be accepting to a pull request with some way to toggle debug output on or off?
Once in a while when I try to connect my device to a BLE peripheral (my laptopt, in my case) following the "Connecting" state message, I get an explosion of messages in the format ----- Invoking disc cb
which causes the app to freeze. This can also happen when I intentionally disconnect my peripheral from my device, but it's mostly bothering when it happens during the connecting state.
The message seems to originate from here:
https://github.com/EddyVerbruggen/nativescript-bluetooth/blob/81b8ae455e45fa2e2009b7b48e54aff800b1d9f6/bluetooth.android.js#L457
Hi,
I get diffent result when Perihicals are connected:
It works perfectly in IOS ("UUID":"E2E4278A-056A-4B22-947D-37010C1FE970"),
but on android ("UUID":"00:1E:C0:2F:EC:03") i get different UUID's. It does not seems logic???
IOS:
Peripheral connected: {"UUID":"E2E4278A-056A-4B22-947D-37010C1FE970","name":"Omega","state":"connected","services":[{"UUID":"12345678-9012-3456-7890-1234567890EE","name":{},"characteristics":[{"UUID":"12345678-9012-3456-7890-123456789000","name":{},"value":null,"properties":{"broadcast":false,"read":true,"broadcast2":false,"read2":true,"write":false,"writeWithoutResponse":true,"notify":true,"indicate":false,"authenticatedSignedWrites":false,"extendedProperties":false,"notifyEncryptionRequired":false,"indicateEncryptionRequired":false},"isNotifying":false},{"UUID":"12345678-9012-3456-7890-123456789001","name":{},"value":"SQE=","properties":{"broadcast":false,"read":false,"broadcast2":false,"read2":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"authenticatedSignedWrites":false,"extendedProperties":false,"notifyEncryptionRequired":false,"indicateEncryptionRequired":false},"isNotifying":false},{"UUID":"12345678-9012-3456-7890-123456789002","name":{},"value":"gQA4AaA5AAAA","properties":{"broadcast":false,"read":false,"broadcast2":false,"read2":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"authenticatedSignedWrites":false,"extendedProperties":false,"notifyEncryptionRequired":false,"indicateEncryptionRequired":false},"isNotifying":false},{"UUID":"12345678-9012-3456-7890-123456789003","name":{},"value":"hwGg","properties":{"broadcast":false,"read":false,"broadcast2":false,"read2":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"authenticatedSignedWrites":false,"extendedProperties":false,"notifyEncryptionRequired":false,"indicateEncryptionRequired":false},"isNotifying":false},{"UUID":"12345678-9012-3456-7890-123456789004","name":{},"value":null,"properties":{"broadcast":false,"read":false,"broadcast2":false,"read2":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"authenticatedSignedWrites":false,"extendedProperties":false,"notifyEncryptionRequired":false,"indicateEncryptionRequired":false},"isNotifying":false}]}]}
Android:
Peripheral connected: {"UUID":"00:1E:C0:2F:EC:03","name":"Omega","state":"connected","services":[{"UUID":"1800","characteristics":[{"UUID":"2a00","name":"2a00","properties":{"read":true,"write":true,"writeWithoutResponse":false,"notify":false,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[]},{"UUID":"2a01","name":"2a01","properties":{"read":true,"write":false,"writeWithoutResponse":false,"notify":false,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[]},{"UUID":"2a04","name":"2a04","properties":{"read":true,"write":false,"writeWithoutResponse":false,"notify":false,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[]}]},{"UUID":"1801","characteristics":[]},{"UUID":"12345678-9012-3456-7890-1234567890ee","characteristics":[{"UUID":"12345678-9012-3456-7890-123456789000","name":"12345678-9012-3456-7890-123456789000","properties":{"read":true,"write":false,"writeWithoutResponse":true,"notify":true,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[{"UUID":"2902","value":null}]},{"UUID":"12345678-9012-3456-7890-123456789001","name":"12345678-9012-3456-7890-123456789001","properties":{"read":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[{"UUID":"2902","value":null}]},{"UUID":"12345678-9012-3456-7890-123456789002","name":"12345678-9012-3456-7890-123456789002","properties":{"read":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[{"UUID":"2902","value":null}]},{"UUID":"12345678-9012-3456-7890-123456789003","name":"12345678-9012-3456-7890-123456789003","properties":{"read":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[{"UUID":"2902","value":null}]},{"UUID":"12345678-9012-3456-7890-123456789004","name":"12345678-9012-3456-7890-123456789004","properties":{"read":false,"write":false,"writeWithoutResponse":false,"notify":true,"indicate":false,"broadcast":false,"authenticatedSignedWrites":false,"extendedProperties":false},"descriptors":[{"UUID":"2902","value":null}]}]}]}
in bluetooth.d.ts is the value missing in interface WriteOptions.
Currently, it is:
export interface WriteOptions extends CRUDOptions {}
But it needs to be:
export interface WriteOptions extends CRUDOptions {
value: any;
}
I would push the change to a new branch but I'm not authorized to do so.
It would be great if you could apply the change. Thanks in advance.
I am attempting to use this module to detect Estimote beacons. The main issue I'm having is with the optional params of the StartScanning function.
bluetooth.startScanning({
serviceUUIDs: [],
seconds: 4,
onDiscovered: function (peripheral) {
console.log("Periperhal found with UUID: " + peripheral.UUID);
}
})
Estimote beacons don't have a serviceUUID, at least none that I could find after looking around. So, I'm not sure how to go about filtering the beacons from the other bluetooth devices being detected by the scanner and I'm not sure how to go about identifying individual beacons.
Thanks.
I need a way to poll when I call bluetooth.requestCoarseLocationPermission()
to know when the user has allowed or rejected the request.
I am starting to do more work with my BLE-to-serial adapter. When I catch the notify event, I am expecting binary data. My return type appears to be NSData. Should this be marshaled to an ArrayBuffer? I'm not sure what is the best way to handle binary data on the iOS side.
Hi,
First of all, thank you for this great module!
I'm new to BLE sphere, so sorry if my wish is out of scope: is there any chance to extend this plugin to peripheral devices? I successfully exchanged data between my macbook as a peripheral (thanks to Bleno nodejs module) and my phone as a central (thanks to guess who...), now I would like to go to phone-phone interactions.
Thanks again,
Sébastien
I use Crashlytics and am getting the following two crash reports. I've attached the full stack trace for both. I'm not able to get to the bottom of what could cause this.
_Fatal Exception: com.tns.NativeScriptException:
Calling js method run failed
TypeError: Cannot read property 'stopScan' of null
File: "file:///data/data/za.co.digitlab.GFConnect/files/app/tns_modules/nativescript-bluetooth/bluetooth.js, line: 478, column: 45_
_Fatal Exception: com.tns.NativeScriptException:
Calling js method onServicesDiscovered failed
TypeError: Cannot read property 'onConnected' of undefined
File: "file:///data/data/za.co.digitlab.GFConnect/files/app/tns_modules/nativescript-bluetooth/bluetooth.js, line: 257, column: 17_
za.co.digitlab.gfconnect_issue_1_crash_59E919A3031500011E5F0FFAB83B7D8C_f8b36b5ab51811e78fd856847afe9799_0_v2.txt
za.co.digitlab.gfconnect_issue_1_crash_59E8A30A00F6000125FDF227511FBFCE_0b68a7cab51811e78fd856847afe9799_0_v2.txt
Hello,
I'm trying to implement this plugin in an app using typescript. I used the demo example to see how it working, but when I call my startScanning method, onDiscovered returns an empty peripheral object... no idea why.
here is my code:
bluetooth.startScanning(
{
serviceUUIDs: [], // pass an empty array to scan for all services
seconds: 4, // passing in seconds makes the plugin stop scanning after <seconds> seconds
onDiscovered: function (peripheral) {
var obsp = new Observable(peripheral);
console.log(peripheral);
that.observablePeripheralArray.push(obsp);
console.log("final len: ", that.observablePeripheralArray.length);
console.log(that.observablePeripheralArray);
}
}
)
and here is the log:
JS: ---- Lollipop+ scanCallback result: {"type":"scanResult","UUID":"E8:41:48:A7:4C:E7","name":"GIL#B914AF7329C428D4","RSSI":-100,"state":"disconnected","advertisement":"FQlHSUwjQjkxNEFGNzMyOUM0MjhENAIBBQMDDxgRB57K3CQO5angk/OjtQEAQG4AAAAAAAAAAAAAAAAAAAA="}
JS: [object Object]
JS: final len: 1
JS: Observable
Thanks
I have had situations where isBluetoothEnabled() returns false even phone bluetooth is on.
Switching bluetooth off and on does not help. Restarting phone does not help.
Tested with version 1.1.2 & 1.1.3.
Problem has occurred with iPhone 5s & 6s.
Can I use this lib to connect a Headset or something to my App, or do I need a different approach to archive that?
I am really new to Bluetooth.
Thanks in advance.
On Android 6, user have to enable location service (Settings -> Location -> On) to make this plugin (And all BLE depended apps) working.
If we have hasCoarseLocationPermission
and requestCoarseLocationPermission
methods, then, there should be also similar methods for location service.
Or at least it will be good to make a note about this in readme :)
Is there a way to subscribe to changes to a characteristic? I'm working with a NFC device that reads tags that is communicating with my app over bluetooth and am attempting to setup a stream where my app will continuously read tag data being sent by the NFC device.
Right now I have it setup so I'm just continuously doing reads (using the .read w/ the peripheral id, service id, and characteristic id) at a really small interval (10 milliseconds) and am getting empty data: {"type":"read","characteristicUUID":"CACC07FF-FFFF-4C48-8FAE-A9EF71B75E26","valueRaw":{},"value":{}} and converting value to a Uint8Array as in one of the examples gets me:{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}
I know my write commands are working and that the NFC device is transmitting the tag data due to visual cues on the device, so I'm just struggling to get the data read properly and I'm wondering if the issue is because of these random-interval-reads as opposed to a subscription
I have a Bluetooth module which is broadcasting a custom BLE service. I have been using the LightBlue iOS app to debug. This is showing the results I expect:
However, when using your plugin and then your demo app, I have found it is showing a different service on the exact same service, on the same device. Why is this?
hi, i've read the other topic about bluetooth detecting problems, but i still can't resolve it, i'm new in nativescript and mobile programming, this is my discovering function, it works until the enable function, then the
onDiscovered: function (peripheral) { console.log("Periperhal found with UUID: " + peripheral.UUID); }
don't return nothing,
where am i wrong?
exports.bt = function () { bluetooth.isBluetoothEnabled().then( function (enabled) { console.log("Enabled? " + enabled); if (!enabled) { bluetooth.enable().then( function(enabled) { console.log("attivato "+ enabled); bluetooth.startScanning({ serviceUUIDs: [], seconds: 10, onDiscovered: function (peripheral) { console.log("Periperhal found with UUID: " + peripheral.UUID); } }).then(function () { console.log("scanning complete "); console.log("Periperhal found with UUID: " + peripheral.UUID); }, function (err) { console.log("error while scanning: " + err); }); } ); } } ); };
thank you for your help
Hi
I am making an android app which is communicating with a "Health monitor".
To access raw data notification service I need to write a specific string (password) to a characteristic.
The issue comes at "Bluetooth._encodeValue" method, which sees what value is a string without "x" and it returns null.
I added extra argument "passRaw" to the write method in my local copy and everything works just fine.
I wonder, is there is any other way to write a string?
that my solution:
bluetooth.write({
peripheralUUID: peripheral.UUID,
serviceUUID: service.UUID,
characteristicUUID: characteristic.UUID,
value: pass,
passRaw: true
and bluetooth.android.js:693
var val = arg.passRaw ? arg.value : Bluetooth._encodeValue(arg.value);
When starting scanning, check for permission, request it, then scan. That last bit is not possible at the moment.
This will make it no longer required for developers to check permissions themselves.
Can we have/add support for Bluetooth classic https://developer.android.com/guide/topics/connectivity/bluetooth.html from within this plugin ?
Currently raw advertising data is available only on android.
A short googling showed me, that iOS do not provide raw advertising data, but it is possible to get at least:
CBAdvertisementDataManufacturerDataKey
CBAdvertisementDataServiceDataKey
(https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManagerDelegate_Protocol/#//apple_ref/doc/constant_group/Advertisement_Data_Retrieval_Keys)
I want to start a discussion here about how nativescript-bluetooth API can look, to allow accessing adv data on iOS.
1st tought:
just add manufacturerData
and serviceData
properties to onDiscovered callback, so on android we will have:
{
...,
advertisement: String,
manufacturerData: String,
serviceData: String
}
and on iOS
{
...,
manufacturerData: String,
serviceData: String
}
Application which I want to implement with {N} and {N}-bluetooth should use manufacturerData to update device state (like ON/OFF) without connection.
Hi Eddy
Pretty new to this.
Using typescript.
Here is an excerpt of my code.
import { Observable, fromObject } from "data/observable";
import { ObservableArray } from "data/observable-array";
import bluetooth = require('nativescript-bluetooth');
let addressList = ["disable", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"];
@Component({
selector: "ns-items",
moduleId: module.id,
templateUrl: "items.component.html",
styleUrls: ["items-common.css"]
})
//hi
export class ItemsComponent implements OnInit {
items: Item[];
public addresses: Array<string>;
pobjects: ObservableArray<object>;
hello: string;
// This pattern makes use of Angular’s dependency injection implementation to inject an instance of the ItemService service into this class.
// Angular knows about this service because it is included in your app’s main NgModule, defined in app.module.ts.
constructor(private itemService: ItemService) {
this.addresses = [];
for (let i = 0; i < addressList.length; i++) {
this.addresses.push(addressList[i]);
}
this.pobjects = new ObservableArray();
}
public onchange(args) {
}
public getUUID() {
//this.pobjects.push(4);
//console.log(this.pobjects.getItem(0));
console.log(this.hello);
bluetooth.startScanning({
serviceUUIDs: [],
seconds: 4,
onDiscovered: function(peripheral) {
console.log("Peripheral found with UUID: "+ peripheral.UUID);
}
}).then(function(){
console.log("scanning complete");
}, function(err) {
console.log("error while scanning: "+err);
})
}
The problem is in the following area:
Whenever a button is pressed getUUID is called which starts scanning.
What I want to do is push peripherals found into my pobjects observable array
But whenever I put this.pobjects.push(fromObject(peripherals))
into ondiscovered: function(peripheral)
it seems to not recognise the object with the following error
JS ERROR typeError: undefined is not an object (evaluating 'this.pobjects.push')
What am I doing wrong?
public getUUID() {
//this.pobjects.push(4);
//console.log(this.pobjects.getItem(0));
console.log(this.hello);
bluetooth.startScanning({
serviceUUIDs: [],
seconds: 4,
onDiscovered: function(peripheral) {
console.log("Peripheral found with UUID: "+ peripheral.UUID);
}
}).then(function(){
console.log("scanning complete");
}, function(err) {
console.log("error while scanning: "+err);
})
}
If the user has bluetooth switched off, do we have to poll until the user switches on bluetooth or is there any other way?
Hello, I have successfully Integrated this library in my demo project. It works as expected for connecting, writing, reading etc.
Then I tried to pull all the code into worker thread as In Android, we put BLE communication code into background thread.
Here's my implementation:
require("globals");
var bluetooth = require("nativescript-bluetooth");
global.onmessage = function (msg) {
if (msg.data == "START") {
bluetooth.startScanning({
//.....properies & call back goes here
});
}
}
But it gives following error in Worker thread
JS: Error in Bluetooth.startScanning: Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
JS: android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:453)
JS: com.tns.Runtime.WorkerGlobalOnMessageCallback(Native Method)
JS: com.tns.Runtime.access$400(Runtime.java:33)
JS: com.tns.Runtime$WorkerThreadHandler.handleMessage(Runtime.java:233)
JS: android.os.Handler.dispatchMessage(Handler.java:102)
JS: android.os.Looper.loop(Looper.java:158)
JS: android.os.HandlerThread.run(HandlerThread.java:61)
So am I missing something or currently there is no support for Worker Threads?
Hello,
I couldn't figure out how to update view while searching device.
Here is my code
searching device function:
app.component.ts
log: string = "Start test";
startScanning() {
ble.startScanning({
serviceUUIDs: [],
seconds: 5,
onDiscovered: (peripheral) => {
if (peripheral.name == "SWING") {
this.stopScanning();
this.updateLog(`Device Name: ${peripheral.name}`); //Update view
}
}).then(() => {
this.updateLog("scanning completed");
}, (err) => {
console.error(`Error on scanning: ${err}`);
})
}
app.component.html
<TextView text="{{ log }}" editable="false"></TextView>
While it scanning, it won't update the log to the view before 5 seconds which finishes the ble.startScanning
.
I believe that I do not fully understand RxJs (Promise) functionality, so I couldn't figure out this issue.
Thank you.
Hello,
I am looking for a way to use this plugin on an app built with NativeScript Angular, but it seems very tricky to me. I suppose that it's definitely possible. Has anyone done it successfully?
There can be a use case in which app can be interested in all adv packets.
I propose adding a new, optional callback to bluetooth.startScanning
:
let scanningOptions = {
onScanResult: (peripheral) => {...}, //event name is to be discussed
onDiscovered: (peripheral) => {...},
seconds: 0
}
bluetooth.startScanning(scanningOptions);
This way the app can f.e.:
I've tried adding this plugin to an iOS app for an iPad (9.3.5) and whenever I run isBlueToothEnabled(), I get back false. I then installed the demo app https://github.com/EddyVerbruggen/nativescript-bluetooth-demo on the same device and am getting that it is not enabled there as well. My bluetooth is definitely enabled and it works as I am able to pair with a device using a different app (not one I developed).
I've been testing the plugin for a while on my app for my phone that's running Android 6.0, but I haven't been able to get it to show that it can detect the bluetooth devices in my vicinity (my laptop).
onDiscovered
happens.then()
clause with a callback to see if perhaps after the scan something would come up out of th bluetooth._connections
object. None.👐
can i use this plugin with beacons ( edystone/iBeacon) ?
On iOS, from what I see in the code, a "peripheral" object appears to have the structure
{
UUID: ...,
name: ...,
RSSI: ...,
state: ...
}
while on Android I see
{
type: ...,
RSSI: ...,
device: {
name: ...,
address: ...
},
advertisement: ...
}
where UUID and address appear to be used synonymous in regard to consecutive actions like service discovery.
I would expect the structure to be identical regardless of OS.
Hi Eddy,
For a project I am doing, I need to enable background BLE updates. On Android, you seem to just create a generic background service and then pass the ble updates into in - here but for ios it seems to require authorizing the Bluetooth updates to persist in the background - Docs
I had hoped to create a generic background-service plugin, but the ios approach seems to make that difficult, so I wondered if you wanted to add background support to your app? I am more than happy to help. Alternatively, I could make a separate plugin. Let me know what you think would be best.
Hej, I'm writing a plugin which utilizes nativescript-bluetooth
and I ran into an issue on iOS, where the onConnected callback is not triggered after the connection to a peripheral is established. About 20 seconds after the connections is established the peripheral is disconnected. The same behavior appears with the demo app.
iOS Versions tested: 10.1.1, 10.3.1
Xcode Version: 8.3.3
Here's the console log of the demo app:
CONSOLE LOG file:///app/tns_modules/nativescript-bluetooth/bluetooth.js:239:16: ----- delegate centralManager:didDiscoverPeripheral: BOT @ -35
CONSOLE LOG file:///app/main-view-model.js:41:16: !!&&&&***** Clicked item with index 0
CONSOLE LOG file:///app/main-view-model.js:43:16: --- peri selected: 77571063-AFD5-4F8D-BE5E-E0A108938FF4
CONSOLE LOG file:///app/tns_modules/nativescript-bluetooth/bluetooth.js:426:20: Connecting to peripheral with UUID: 77571063-AFD5-4F8D-BE5E-E0A108938FF4
CONSOLE LOG file:///app/tns_modules/nativescript-bluetooth/bluetooth.js:264:16: ----- delegate centralManager:didConnectPeripheral: <CBPeripheral: 0x1702ea280, identifier = 77571063-AFD5-4F8D-BE5E-E0A108938FF4, name = BOT, state = connected>
CONSOLE LOG file:///app/tns_modules/nativescript-bluetooth/bluetooth.js:268:16: ----- delegate centralManager:didConnectPeripheral: cached perio: <CBPeripheral: 0x1702ea280, identifier = 77571063-AFD5-4F8D-BE5E-E0A108938FF4, name = BOT, state = connected>
CONSOLE LOG file:///app/tns_modules/nativescript-bluetooth/bluetooth.js:275:16: ----- delegate centralManager:didConnectPeripheral, let's discover service
The demo app was build with following versions:
node: 6.10.1
nativescript: 3.1.3
tns-core-modules: 3.1.1
tns-android: 3.1.1
tns-ios: 3.1.0
In my plugin I've tested this with nativescript-bluetooth
version 1.1.6 and 1.2.0
Here's a part of the package.json
:
{
...
"nativescript": {
"platforms": {
"android": "3.0.0",
"ios": "3.0.0"
}
},
...
"dependencies": {
"nativescript-bluetooth": "1.1.6",
"nativescript-platform": "^1.1.1",
"nativescript-zip": "^1.3.2"
},
"devDependencies": {
"tns-core-modules": "~3.0.0",
"tns-platform-declarations": "^3.0.1",
"typescript": "~2.2.1",
"prompt": "~1.0.0",
"rimraf": "~2.5.0"
}
}
The app in which I'm using my plugin was build with:
node: 6.10.1
nativescript: 3.1.3
tns-core-modules: 3.0.1
tns-android: 3.0.0
tns-ios: 3.0.1
The console log is identical to the log of the demo app (except the lines of the view-model of course).
On Android everything is working fine.
Any idea how to solve this? Could version conflicts be the cause?
Thanks in advance!
hello,
i have got a HM-10 BLE device, when i connect i have no services in the peripheral properties, i just need to send a character like "a" or "b", how can I make it works?
this is the scancallback result:
Lollipop+ scanCallback result: {"type":"scanResult","UUID":"50:8C:B1:6A:7C:AB","name":"HMSoft","RSSI":-71,"
state":"disconnected","advertisement":"AgEGCf9ITVCMsWp8qwcWALAAAAAAAwLg/wIKAAcJSE1Tb2Z0AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAA=","manufacturerId":19784,"manufacturerData":{}}
i have found on this site these services:
http://blog.blecentral.com/2015/05/05/hm-10-peripheral/
Service UUID: 0000ffe0-0000-1000-8000-00805f9b34fb) that enables bidirectional communication between the module and any other central device that connects to it. The service defines a single characteristic (Characteristic UUID: 0000ffe1-0000-1000-8000-00805f9b34fb)
so if I try to connect and write the ascii for "a" I have this result:
Connecting to peripheral with UUID: 50:8C:B1:6A:7C:AB
JS: ------- _MyGattCallback.onConnectionStateChange, status: 0, new state: 2
JS: ---- discovering services..
JS: ------- _MyGattCallback.onConnectionStateChange, status: 8, new state: 0
JS: ----- invoking disc cb
JS: Periperhal disconnected with UUID: 50:8C:B1:6A:7C:AB
someone have ever worked with this device? where am i wrong?
thank you
This is similar to issue #62.
startNotifying() calls gatt.writeDescriptor() then calls resolve() right away. I think it should wait and call resolve() from onDescriptorWrite() instead.
The case I have is a Blood Pressure device that only starts sending data after you start listening to two different characteristics. This requires two calls to Bluetooth.startNotifying(), but the second one fails unless you wait for the first one to call onDescriptorWrite()
When passing a service UUID to startScanning() for use as scan filter, no peripheral is found.
This is reproducible on at least two different BT LE capable devices with differing variants of Android 6.
it is probably due to known issues in the BT LE implementation of Android 5/6 as mentioned here: EddyVerbruggen/nativescript-bluetooth-demo#4
In fact I had the same problem when trying this myself some time ago with NativeScript as well as with native Android code (then testing on Android 5.1), following different examples from the web, and at some point decided to rather build a workaround.
I'd be happy if some in-deep Android developer would prove me wrong.
Otherwise, to make startScanning() work as expected and fully cross platform, the only reliable solution seems to be scanning for all devices on Android 5+, doing the filtering as an afterwork in the callback's onScanResult() and from there call onDiscovery() conditionally.
The alternative would be leaving that check to the app developer. But this would violate the cross platform idea and may well result in similar bug reports in the future.
Here is the full warning I get when I try to run an android app which uses your plugin.
WARNING: The file: /Users/georgeedwards/Desktop/Personal-App/node_modules/nativescript-bluetooth/platforms/android/README.md is depricated, you can read more about what will be the expected plugin structure here: https://www.nativescript.org/blog/migrating-n-android-plugins-from-version-1.7-to-2.0
I'm using v1.1.1.
Is there any way to get all connected as well as disconnected peripherals? The startScanning method parameter onDiscovered (callback) only gives "disconnected" ones.
I'm starting to study the plugin for use of Bluetooth.
Unfortunately I discovered that the tablet I have does not have bluetooth, so when I initialize the plugin I get an exception, since the getAdapter function returns null.
Given this I would suggest that this plugin's start point would be a 'Promise' something like:
Bluetooth.init = function() {
return new Promise(function(resolve, reject) {
var bluetoothManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.BLUETOOTH_SERVICE);
adapter = bluetoothManager.getAdapter();
if(adapter === null) {
reject("this device not have bluetooth!");
return;
}
//......
});
};
And this initialization was controlled by the application, so we would have access to the 'then' and 'cath' functions to take some action so the application did not break.
Hello
I have a Xperia C that empowered with an Android Jelly Beans MR 1 (SDK 17 - 4.2.2) and with Bluetooth.
However the nativescript-bluetooth plugin does not work with it because of the SDK 4.2.2, I would like to study the implementation of such functionality in a retroactive way to make the plugin compatible with these phones, in Brazil there are many Bluetooth-enabled phones but versions of the previous SDK 4.3.
What do they suggest as a starting point, I tried to search about the use of the NativeScript-core-modules / Utils getService () function but I did not find enough material.
Grateful.
ps: See #42
Hello, I'm writing the bluetooth communication part of an app with several other people, and I've been struggling for quite some time now so that's why I'm opening this issue here hoping someone can help !
I'm connecting to a peripheral that has a UART over BLE service, so I'm subscribing to notifications on the TX characteric of the UART service (and the logs correctly reports that notify is TRUE) but when I write values on the RX characteristic, I never receive anything while I should be receiving something (I'm sending an HEX command that works perfectly in native android code or also on cordova...).
Here is how I subscribe to notifications (notifications subscription works as I said earlier as I'm correctly seeing in the console JS: --- notifying
- this is on Android, but works also on iOS):
public subscribeTXnotification = function () {
//Subscribe to TX notifications
console.log("----- Starting TX subscription");
bluetooth.startNotifying({
peripheralUUID: this.connectedPeripheral.UUID,
serviceUUID: this.uartService,
characteristicUUID: this.txUuid,
onNotify: this.onData
}).then(function() {
console.log("----------- subscribed for notifications of TX Channel");
});
}
and the onData callback is here:
public onData = function (data) {
console.log("read: ", JSON.stringify(data));
}
You should note that I'm coding using TypeScript and those functions are part of a class.
Example of write call is here:
bluetooth.write(
{
peripheralUUID: that.connectedPeripheral.UUID,
serviceUUID: that.uartService,
characteristicUUID: that.rxUuid,
value: '0xAA0400002955', //AA010400C555
}
).then(
function(result) {
console.log("Done: ", JSON.stringify(result));
},
function (err) {
dialogs.alert({
title: "Whoops!",
message: err,
okButtonText: "Hmmkay"
});
}
);
Also, I tried on both iOS and Android and I get the same behaviors. Write works without printing any errors in the console but I never receive anything.
Hello,
I am trying to get sensor data from the below Bluetooth data logger.
https://www.bluemaestro.com/product/tempo-disc-temperature-humidity-data-logger/
https://www.bluemaestro.com/wp-content/uploads/2016/10/Temperature-Humidity-Data-Logger-Commands-API.pdf
It has this BT Chipset I believe.
http://infocenter.nordicsemi.com/pdf/nRF52832_PB_v1.4.pdf
Using the Nativescript Bluetooth Demo app I can see the Datalogger and connect to it, but it doesn't seem to read any characteristic data from the BT device. It only has 1 service which has a Notify and Write characteristics.
You have mentioned reading data from a Heartrate ServiceUUID but how can one get the logged data from this BlueMaestro tempo disc?
BlueMaestro has a utility app for ios that can read the data from the data loggers. It also has an SDK to develop upon, but it is native iOS code and I would like to develop in Nativescript using your plugin :)
App called BlueMaestro Tempo Utility
SDK: https://github.com/BlueMaestro/IOS-Tempo-Utility-App-SDK/blob/master/README.md
Any help or guidance would be greatly appreciated.
Many thanks,
Brian
Hi,
I'm trying to figure out why I cannot connect to my thermal printer on android (ios is working fine). I can scan and get uuid just fine, but on intent of connecting it's just get stuck and thats it, no timeouts nothing. Device is Samsung S3
I tried playing with minSdk and it is set to 21 (tried 17, 19). Just to be sure printer is working I downloaded "Bluetooth Printer" app from the store, and I see the same uuid and can make test print so I asume everything is ok with ble printer.
I started digging and I found several issues related with "who gets first to connect" or something like that. My debugging took me to connectGatt()
method, and my printer shows blue light pointgin that maybe device is connected, but services are never returned, so sending something to write gives gatt.getService
error.
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.