当前位置: 首页 > 软件库 > 手机/移动开发 > >

ble

授权协议 MIT License
开发语言 JavaScript TypeScript
所属分类 手机/移动开发
软件类型 开源软件
地区 不详
投 递 者 姚星腾
操作系统 iOS
开源组织
适用人群 未知
 软件概览

NativeScript Bluetooth plugin

Installation

From the command prompt go to your app's root folder and execute:

if using @nativescript

tns plugin add @nativescript-community/ble

And do yourself a favor by adding TypeScript support to your nativeScript app:

tns install typescript

API

Want to dive in quickly? Check out the demo app! Otherwise, mix and match these functions as you see fit:

Prerequisites

Discovery

Connectivity

Interaction

Debugging

isBluetoothEnabled

Reports if bluetooth is enabled.

// require the plugin
import { Bluetooth } from '@nativescript-community/ble';
var bluetooth = new Bluetooth();

bluetooth.isBluetoothEnabled().then(
  function(enabled) {
    console.log("Enabled? " + enabled);
  }
);

hasLocationPermission

Since plugin version 1.2.0 the startScanning function will handle this internally so it's no longer mandatory to add permission checks to your code.

On Android 6 you need to request permission to be able to interact with a Bluetooth peripheral (when the app is in the background) when targeting API level 23+. Even if the uses-permission tag for ACCESS_COARSE_LOCATION is present in AndroidManifest.xml.

Note that for BLUETOOTH and BLUETOOTH_ADMIN you don't require runtime permission; adding those to AndroidManifest.xml suffices (which the plugin does for you).

Note that hasLocationPermission will return true when:

  • You're running this on iOS, or
  • You're targeting an API level lower than 23, or
  • You're using a device running Android < 6, or
  • You've already granted permission.
bluetooth.hasLocationPermission().then(
  function(granted) {
    // if this is 'false' you probably want to call 'requestLocationPermission' now
    console.log("Has Location Permission? " + granted);
  }
);

requestLocationPermission

Since plugin version 1.2.0 the startScanning function will handle this internally so it's no longer mandatory to add permission checks to your code.

// if no permission was granted previously this will open a user consent screen
bluetooth.requestLocationPermission().then(
  function(granted) {
    console.log("Location permission requested, user granted? " + granted);
  }
);

enable (Android only)

The promise will be rejected on iOS

// This turns bluetooth on, will return false if the user denied the request.
bluetooth.enable().then(
  function(enabled) {
    // use Bluetooth features if enabled is true 
  }
);

startScanning

A few of the optional params require a bit of explanation:

seconds

Scanning for peripherals drains the battery quickly, so you better not scan any longer than necessary. If a peripheral is in range and not engaged in another connection it usually pops up in under a second. If you don't pass in a number of seconds you will need to manually call stopScanning.

skipPermissionCheck

Set this to true if you don't want the plugin to check (and request) the required Bluetooth permissions.Particularly useful if you're running this function on a non-UI thread (ie. a Worker).Relevant on Android only.

filters

It's inefficient to scan for all available Bluetooth peripherals and have them report all services they offer.Moreover on Android if we don't use filters we must have location permissions and have GPS enabled

If you're only interested in finding a heartrate peripheral for instance, pass in service UUID '180d' like this: filters: [{serviceUUID:'180d'}]. If you add 2 or more (comma separated) services then only peripherals supporting ALL those services will match.

Note that UUID's are ALWAYS strings; don't pass integers.

onDiscovered

While scanning the plugin will immediately report back uniquely discovered peripherals.

This function will receive an object representing the peripheral which contains these properties (and types):

  • UUID: string
  • name: string
  • RSSI: number (relative signal strength, can be used for distance measurement)
  • services?: (optional - this is set once connected to the peripheral)
  • manufacturerId?: number (optional)
  • advertismentData?: { localName?:string manufacturerData?: ArrayBuffer; serviceUUIDs?: string[]; txPowerLevel?:number, flags?:number } (optional)
bluetooth.startScanning({
  filters: [{serviceUUID:'180d'}],
  seconds: 4,
  onDiscovered: function (peripheral) {
  	console.log("Periperhal found with UUID: " + peripheral.UUID);
  }
}).then(function() {
  console.log("scanning complete");
}, function (err) {
  console.log("error while scanning: " + err);
});

stopScanning

At any time during a scan, being one where you passed in a number or seconds or not, you can stop the scan by calling this function.

You may for instance want to stop scanning when the peripheral you found in startScanning's onDiscovered callback matches your criteria.

bluetooth.stopScanning().then(function() {
  console.log("scanning stopped");
});

connect

Pass in the UUID of the peripheral you want to connect to and once a connection has been established the onConnected callback function will be invoked. This callback will received the peripheral object as before, but it's now enriched with a services property. An example of the returned peripheral object could be:

peripheral: {
    UUID: '3424-542-4534-53454',
    name: 'Polar P7 Heartrate Monitor',
    RSSI: '-57',
    services: [{    
      UUID: '180d',
      name: 'Heartrate service',
      characteristics: [{
        UUID: '34534-54353-234324-343',
        name: 'Heartrate characteristic',
        properties: {
          read: true,
          write: false,
          writeWithoutResponse: false,
          notify: true
        }
      }]
    }]
  }

Here's the connect function in action with an implementation of onConnected that simply dumps the entire peripheral object to the console:

bluetooth.connect({
  UUID: '04343-23445-45243-423434',
  onConnected: function (peripheral) {
  	console.log("Periperhal connected with UUID: " + peripheral.UUID);

  	// the peripheral object now has a list of available services:
  	peripheral.services.forEach(function(service) {
  	  console.log("service found: " + JSON.stringify(service));
   });
  },
  onDisconnected: function (peripheral) {
  	console.log("Periperhal disconnected with UUID: " + peripheral.UUID);
  }
});

Also note that onDisconnected function: if you try to interact with the peripheral after this event you risk crashing your app.

disconnect

Once done interacting with the peripheral be a good citizen and disconnect. This will allow other applications establishing a connection.

bluetooth.disconnect({
  UUID: '34234-5453-4453-54545'
}).then(function() {
  console.log("disconnected successfully");
}, function (err) {
  // in this case you're probably best off treating this as a disconnected peripheral though
  console.log("disconnection error: " + err);
});

read

If a peripheral has a service that has a characteristic where properties.read is true then you can call the read function to retrieve the current state (value) of the characteristic.

The promise will receive an object like this:

{
  value: <ArrayBuffer>, // an ArrayBuffer which you can use to decode (see example below)
  ios: <72>, // the platform-specific binary value of the characteristic: NSData (iOS), byte[] (Android)
  android: <72>, // the platform-specific binary value of the characteristic: NSData (iOS), byte[] (Android)
  characteristicUUID: '434234-234234-234234-434'
}

Armed with this knowledge, let's invoke the read function:

bluetooth.read({
  peripheralUUID: '34234-5453-4453-54545',
  serviceUUID: '180d',
  characteristicUUID: '3434-45234-34324-2343'
}).then(function(result) {
  // fi. a heartrate monitor value (Uint8) can be retrieved like this:
  var data = new Uint8Array(result.value);
  console.log("Your heartrate is: " + data[1] + " bpm");  
}, function (err) {
  console.log("read error: " + err);
});

write

If a peripheral has a service that has a characteristic where properties.write is true then you can call the write function to update the current state (value) of the characteristic.

The value may be a string or any array type value. If you pass a string you should pass the encoding too

bluetooth.write({
  peripheralUUID: '34134-5453-4453-54545',
  serviceUUID: '180e',
  characteristicUUID: '3424-45234-34324-2343',
  value: [1]
}).then(function(result) {
  console.log("value written");
}, function (err) {
  console.log("write error: " + err);
});

writeWithoutResponse

Same API as write, except that when the promise is invoked the value has not been written yet; it has only been requested to be written an no response will be received when it has.

startNotifying

If a peripheral has a service that has a characteristic where properties.notify is true then you can call the startNotifying function to retrieve the value changes of the characteristic.

Usage is very much like read, but the result won't be sent to the promise, but to the onNotify callback function you pass in. This is because multiple notifications can be received and a promise can only resolve once. The value of the object sent to onNotify is the same as the one you get in the promise of read.

bluetooth.startNotifying({
  peripheralUUID: '34234-5453-4453-54545',
  serviceUUID: '180d',
  characteristicUUID: '3434-45234-34324-2343',
  onNotify: function (result) {
    // see the read example for how to decode ArrayBuffers
	console.log("read: " + JSON.stringify(result));
  }  
}).then(function() {
  console.log("subscribed for notifications");
});

stopNotifying

Enough is enough. When you're no longer interested in the values the peripheral is sending you do this:

bluetooth.stopNotifying({
  peripheralUUID: '34234-5453-4453-54545',
  serviceUUID: '180d',
  characteristicUUID: '3434-45234-34324-2343'
}).then(function() {
  console.log("unsubscribed for notifications");
}, function (err) {
  console.log("unsubscribe error: " + err);
});

setCharacteristicLogging

The app using bluetooth can generate many console.log messages - one for each characteristic read, write, change.This can be reduced by calling bluetooth.setCharacteristicLogging(false).

Troubleshooting

Get a merge issue in AndroidManifest.xml? Remove the platforms/android folder and rebuild.

Future work

  • Support interacting with multiple characteristics of the same peripheral at the same time.
  • BLE是蓝牙低功耗的简称(Bluetooth Low Energy)。蓝牙低功耗(BLE)技术是低成本、短距离、可互操作的鲁棒性无线技术,工作在免许可的2.4GHz ISM射频频段。 低成本,低功耗 快速启动,瞬间链接。最快3ms低延迟 传输距离的提高 高安全性。使用AES-128加密算法进行数据报加密认证 蓝牙1.0:基本码率,Basic Rate,BR 蓝牙2.0:增强码率,Enhanced

  • 现在移动设备上使用的蓝牙大多是4.0,而蓝牙 4.0 有两个分支,经典 4.0 和 BLE4.0,经典 4.0 就是传统的3.0 蓝牙升级而成,向下兼容。而 BLE 4.0 是一个新的分支,不向下兼容。 相较于传统蓝牙,BLE的优点是快速搜索,快速连接,超低功耗保持连接和传输数据,弱点是数据传输速率低,物理带宽只有 1M,实际传输速度在 1~6KB 之间   蓝牙BLE相对于传统蓝牙的优点:最大化

  • 本章将介绍BLE协议不同的层,包括各个层的部件和它们的概念。  2.1  通用访问规范(Generic Access Profile,GAP) GAP是应用层能够直接访问BLE协议栈的最底层,它包括管理广播和连接事件的有关参数。 注意:GAP的更多详细介绍见《Bluetooth Core Specification》(蓝牙核心规范)的第3卷C部分。 2.1.1 角色 为了创建和维持一个BLE连接,

  • 1.BLE通信中主要有两对角色: 在GAP通信过程中是以Central和Peripheral角色存在的:Peripheral发起广播, Central发起扫描请求。Central收到Peripheral的扫描回复后建立连接。 在GATT通信过程中是以Server和Client角色存在的:serve端用于提供数据,Client端用于使用Server提供的数据并完成处理。 *在GAP中的Central

  • 【BLE】蓝牙概念 1. 种类 单模蓝牙:仅支持传统蓝牙和BLE(低功耗蓝牙)中的一种; 双模蓝牙:同时支持传统蓝牙和BLE(低功耗蓝牙)。 2. 部署方案 3. 节点类型 根据蓝牙协议不同的协议层有不同的角色 1. Server和Client(GATT)——属性服务层 Server(服务器)就是数据中心,一般指蓝牙设备,一般是从机; Client(客户端)就是数据访问者,一般指手机,一般是主机。

  • Android蓝牙开发分为经典蓝牙和低功耗蓝牙 经典蓝牙:蓝牙3.0版本以下的蓝牙。 低功耗蓝牙:蓝牙4.0(及以上版本) 两者的区别很明显,虽然都叫做蓝牙,但已经算是两个东西了;流程的话都类似,协议不同 发现设备->配对/绑定设备->建立连接->数据通信 经典蓝牙和低功耗蓝牙除了配对/绑定这个环节是一样的之外,其它三个环节都是不同的。 1. 发现设备 经典蓝牙:经典蓝牙设备发现其它经典蓝牙设备的

  • 本文涉及的内容均转自无线技术联盟微信公众号,仅用来学习的目的,如有不妥,请联系我后及时删除,QQ:993650814.   1、细说BLUETOOTH 5 【2X 数据吞吐量】 2、细说BLUETOOTH 5 【4X 远距离】 3、细说BLUETOOTH 5 【8X 大广播包数据传输】 4、蓝牙5速率详细分析和提升方式【附测试数据】 5、从空中截获BLE数据包看蓝牙5协议流程【第一部分:beaco

  • 蓝牙低功耗无线电的调制速率由规范规定为恒定的1Mbps(兆比特每秒)。当然,这是理论上的上限。在实践中,根据所使用设备的限制,您可以期望每秒5- 10kb。就距离而言,BLE专注于非常短的距离通信。可以创建和配置一个BLE设备,该设备可以可靠地传输30米或30米以上的视线范围内的数据,但典型的操作范围可能更接近2到5米。当然,续航里程越高,电池消耗就越多,所以在调整你的设备以适应更高的续航里程时要

  • 一、术语 自适应跳频: 干扰是任何无线技术提供可靠数据通信时所遇到的最大挑战之一。由于蓝牙、Wi-Fi和802.15.4等无线技术设备共享一个传输介质, 如果一个正在传输的数据包与另一个正在传输的数据包在完全相同的时间和相同的通道上发生冲突,数据包就有可能损坏或丢失。 为了克服干扰并找到一条避免数据包冲突的清晰传输路径,蓝牙技术使用一种被称为自适应跳频(AFH,adaptive fre

 相关资料
  • 问题内容: 我正在尝试创建一个应用程序,该应用程序可以连接并接收来自多个蓝牙低能耗设备的通知。我想知道如何实现这一目标。每个连接是否需要一个单独的线程?考虑到API的异步特性,如何确保能够按发现的顺序发现服务并设置通知。我目前使用的是此处提供的相同结构:https : //developer.android.com/guide/topics/connectivity/bluetooth- le.h

  • 问题内容: 我已经将通知设置为android,它不是在调用方法???? 它不进入该功能。为什么会这样呢? 任何帮助表示赞赏 要求解决方案。 这是我的代码: 先感谢您!! 问题答案: 首先,如果您通过以下方式阅读了特征,将触发: 读取特征和设置通知是两件事。您要从中获取数据的特征的类型是什么? 是吗: 读 通知 表明 如果是,则可以使用方法读取特征,但如果是或首先,则必须通过调用以下方法来读取特征:

  • 问题内容: 有点卡在这里,可能需要您的帮助。我想一次阅读几个BLE特性,有人建议为此使用PriorityQueue。我已经知道所有的uuid,等等。只需要一种同时读取多个uuid的方法。谁能解释它到底是什么样子?也许还有另一个更简单的解决方案? 在此先感谢,这是我的代码: 更新: 即使将它们放在不同的线程上,它仍然仍然只对一个gatt.readCharacteristic(…)做出反应。如下所示:

  • 问题内容: 我需要计算BLEU分数来识别两个句子是否相似。我阅读了一些文章,这些文章主要涉及测量机器翻译准确性的BLEU分数。但是我需要BLEU分数来找出句子中相似度。相同的语言[英语]。(ie)(两个句子都是英语)。感谢您的期待。 问题答案: 好吧,如果您只是想计算BLEU分数,那很简单。将一个句子作为参考翻译,将另一个作为候选翻译。

  • 问题内容: 我又来了。 所以,长话短说:在我的应用程序中,我试图借助Android Samples(that)从BLE设备(滴答心率监测器:that)接收数据。但是…我没有从我的设备接收数据!我可以得到特征和描述符,但是……仅此而已。我只是.. 错过了重点 。这是我的代码: __ 这是我的日志: 问题答案: 您有一个电话,但没有回调来接收该值。它是BluetoothGattCallback的一部分

  • 问题内容: 我有一台使用以下命令广播BLE广告的linux计算机: 效果很好,但是计算机每秒只广播一次蓝牙广告。我想将此频率提高到每秒10次或更多。有没有办法增加BlueZ中的广告频率?还是每秒一次是标准且不变的?如果无法使用命令行工具,我很乐意使用C API进行此操作。 问题答案: 我想我知道了。 代替: 做这个: 第二个hcitool命令(0x08 0x0006)是“ LE设置广告参数。前两个

  • 问题内容: 我想用BLE扫描某些设备。我只想显示我的设备,所以我知道了设备的名称,如果是好的设备,我会将其放在列表中。 我的问题是,如果我更改设备的名称,此检查将为false。因此,我看是否有可能获得一些我添加的用于执行检查的服务的不变的东西。唯一的方法是使用gatt在发现服务后执行此操作,然后再连接到该设备,但是,是否有可能在不连接设备的情况下从该设备发现某些服务? 问题答案: 我不具备andr

  • 本文向大家介绍stacking和blending的区别?相关面试题,主要包含被问及stacking和blending的区别?时的应答技巧和注意事项,需要的朋友参考一下 参考回答: Stacking和blending的区别在于数据的划分,blending用不相交的数据训练不同的基模型,并将其输出取加权平均。而stacking是将数据集划分为两个不相交的集合,在第一个集合的数据集中训练多个模型,在第二