@abandonware/bleno 中文文档教程
bleno
一个用于实现 BLE(低功耗蓝牙)外围设备的 Node.js 模块。
需要 BLE 中央模块? 请参阅 noble。
注意:macOS / Mac OS X、Linux、FreeBSD 和 Windows 是目前唯一受支持的操作系统。
Prerequisites
OS X
- install the XCode command line tools via
xcode-select --install
- 10.9 or later
Linux
- Kernel version 3.6 or above
libbluetooth-dev
bluetoothd
disabled, if BlueZ 5.14 or later is installed. Usesudo hciconfig hci0 up
to power Bluetooth adapter up after stopping or disablingbluetoothd
.System V
:sudo service bluetooth stop
(once)sudo update-rc.d bluetooth remove
(persist on reboot)systemd
sudo systemctl stop bluetooth
(once)sudo systemctl disable bluetooth
(persist on reboot)
如果您同时使用 noble 和 bleno,连接的 BLE 设备可能无法从 BLE 适配器检索服务列表。 查看 noble 的关于 bleno 兼容性的文档
Ubuntu/Debian/Raspbian
sudo apt-get install bluetooth bluez libbluetooth-dev libudev-dev libusb-1.0-0-dev
确保 node
在您的路径上,如果它是不,一些选项:
- symlink
nodejs
tonode
:sudo ln -s /usr/bin/nodejs /usr/bin/node
- install Node.js using the NodeSource package
Fedora / Other-RPM based
sudo yum install bluez bluez-libs bluez-libs-devel
Intel Edison
FreeBSD
确保你有 GNU Make:
sudo pkg install gmake
通过将 no-ubt.conf 放入 /usr/local/etc/devd/no-ubt.conf
并重新启动 devd(sudo service devd restart
)。
卸载 ng_ubt
内核模块(如果已加载):
sudo kldunload ng_ubt
确保您对与蓝牙适配器对应的 /dev/usb/*
设备具有读写权限。
Windows
- node-gyp requirements for Windows
- Python 2.7
- Visual Studio (Express)
- node-bluetooth-hci-socket prerequisites
- Compatible Bluetooth 4.0 USB adapter
- WinUSB driver setup for Bluetooth 4.0 USB adapter, using Zadig tool
Install
npm install bleno@npm:@abandonware/bleno
Usage
var bleno = require('bleno');
有关代码示例,请参阅示例文件夹。
Actions
Advertising
Start advertising
注意:在广告开始之前,bleno.state
必须是 poweredOn
。 bleno.on('stateChange', callback(state));
可用于注册状态更改事件。
var name = 'name';
var serviceUuids = ['fffffffffffffffffffffffffffffff0']
bleno.startAdvertising(name, serviceUuids[, callback(error)]);
注意::名称和服务UUID有限制
- name
- maximum 26 bytes
- service UUID's
- 1 128-bit service UUID
- 1 128-bit service UUID + 2 16-bit service UUID's
- 7 16-bit service UUID
Start advertising iBeacon
var uuid = 'e2c56db5dffb48d2b060d0f5a71096e0';
var major = 0; // 0x0000 - 0xffff
var minor = 0; // 0x0000 - 0xffff
var measuredPower = -59; // -128 - 127
bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower[, callback(error)]);
注意::
- OS X:
- in iBeacon mode your peripheral is non-connectable!
Start advertising with EIR data (Linux only)
var scanData = Buffer.alloc(...); // maximum 31 bytes
var advertisementData = Buffer.alloc(...); // maximum 31 bytes
bleno.startAdvertisingWithEIRData(advertisementData[, scanData, callback(error)]);
- For EIR format section Bluetooth Core Specification sections and 8 and 18 for more information the data format.
Stop advertising
bleno.stopAdvertising([callback]);
Set services
设置外设可用的主要服务。
var services = [
... // see PrimaryService for data type
];
bleno.setServices(services[, callback(error)]);
Disconnect client
bleno.disconnect(); // Linux only
Update RSSI
bleno.updateRssi([callback(error, rssi)]); // not available in OS X 10.9
Primary Service
var PrimaryService = bleno.PrimaryService;
var primaryService = new PrimaryService({
uuid: 'fffffffffffffffffffffffffffffff0', // or 'fff0' for 16-bit
characteristics: [
// see Characteristic for data type
]
});
Characteristic
var Characteristic = bleno.Characteristic;
var characteristic = new Characteristic({
uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
properties: [ ... ], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
secure: [ ... ], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
value: null, // optional static value, must be of type Buffer - for read only characteristics
descriptors: [
// see Descriptor for data type
],
onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
onNotify: null, // optional notify sent handler, function() { ...}
onIndicate: null // optional indicate confirmation received handler, function() { ...}
});
Result codes
- Characteristic.RESULT_SUCCESS
- Characteristic.RESULTINVALIDOFFSET
- Characteristic.RESULTINVALIDATTRIBUTE_LENGTH
- Characteristic.RESULTUNLIKELYERROR
Read requests
可以通过构造函数选项或通过扩展 Characteristic 和覆盖 onReadRequest 来指定读取请求处理程序。
处理程序的参数是
offset
(0x0000 - 0xffff)callback
callback
必须使用结果和数据(Buffer
类型)调用 - 可以是异步的。
var result = Characteristic.RESULT_SUCCESS;
var data = Buffer.alloc( ... );
callback(result, data);
Write requests
可以通过构造函数选项或通过扩展 Characteristic 和覆盖 onWriteRequest 来指定写入请求处理程序。
处理程序的参数是
data
(Buffer)offset
(0x0000 - 0xffff)withoutResponse
(true | false)callback
.
callback
必须使用结果代码调用 - 可以是异步的。
var result = Characteristic.RESULT_SUCCESS;
callback(result);
Notify subscribe
可以通过构造函数选项或通过扩展 Characteristic 和覆盖 onSubscribe 来指定通知订阅处理程序。
处理程序的参数是
maxValueSize
(maximum data size)updateValueCallback
(callback to call when value has changed)
Notify unsubscribe
可以通过构造函数选项或通过扩展特性和覆盖 onUnsubscribe 来指定通知取消订阅处理程序。
Notify value changes
使用 Buffer
类型的参数调用 updateValueCallback
回调(请参阅 Notify subscribe)
可以通过构造函数选项或通过扩展 Characteristic 和覆盖 onNotify 来指定通知发送处理程序。
Descriptor
var Descriptor = bleno.Descriptor;
var descriptor = new Descriptor({
uuid: '2901',
value: 'value' // static value, must be of type Buffer or string if set
});
Events
Adapter state change
state = <"unknown" | "resetting" | "unsupported" | "unauthorized" | "poweredOff" | "poweredOn">
bleno.on('stateChange', callback(state));
Advertisement started
bleno.on('advertisingStart', callback(error));
bleno.on('advertisingStartError', callback(error));
Advertisement stopped
bleno.on('advertisingStop', callback);
Services set
bleno.on('servicesSet', callback(error));
bleno.on('servicesSetError', callback(error));
Accept
bleno.on('accept', callback(clientAddress)); // not available on OS X 10.9
Disconnect
bleno.on('disconnect', callback(clientAddress)); // Linux only
RSSI Update
bleno.on('rssiUpdate', callback(rssi)); // not available on OS X 10.9
Running on Linux
注意:确保您还检查了 Linux 先决条件
Running without root/sudo
运行以下命令:
sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
这将授予 node
二进制文件 < code>cap_net_raw 权限,因此它可以启动/停止 BLE 广播。
注意:以上命令需要安装setcap
,可以使用以下命令安装:
- apt:
sudo apt-get install libcap2-bin
- yum:
su -c \'yum install libcap2-bin\'
Multiple Adapters
hci0
默认用于覆盖设置< code>BLENO_HCI_DEVICE_ID 环境变量到接口号。
例如,指定hci1
:
sudo BLENO_HCI_DEVICE_ID=1 node <your file>.js
Set custom device name
默认情况下,bleno 使用主机名(require('os').hostname()
)作为设备名称(0x2a00)特征的值,以匹配 OS X 的行为。
可以通过设置 BLENO_DEVICE_NAME
环境变量来指定自定义设备名称:
sudo BLENO_DEVICE_NAME="custom device name" node <your file>.js
或者
process.env['BLENO_DEVICE_NAME'] = 'custom device name';
Set Advertising Interval
bleno 默认使用 100 毫秒的广告间隔。
可以通过将 BLENO_ADVERTISING_INTERVAL
环境变量设置为所需的毫秒值来指定自定义广告间隔:
sudo BLENO_ADVERTISING_INTERVAL=500 node <your file>.js
广告间隔必须介于 20 毫秒到 10 秒(10,000 毫秒)之间。
Useful tools/links
- Tools
- LightBlue for iOS/OS X
- nRF Master Control Panel (BLE) for Android
- hcitool and
gatttool
by BlueZ for Linux
License
版权所有 (C) 2015 Sandeep Mistry sandeep.mistry@gmail.com
特此免费授予任何获得本软件和相关文档文件(“软件”),不受限制地处理本软件,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售本软件副本的权利,并允许获得软件的人这样做,但须满足以下条件:
上述版权声明和本许可声明应包含在软件的所有副本或重要部分中。
本软件“按原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和非侵权的保证。 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是在合同诉讼、侵权行为还是其他方面,由软件或软件的使用或其他交易引起、由软件引起或与之相关软件。
bleno
A Node.js module for implementing BLE (Bluetooth Low Energy) peripherals.
Need a BLE central module? See noble.
Note: macOS / Mac OS X, Linux, FreeBSD and Windows are currently the only supported OSes.
Prerequisites
OS X
- install the XCode command line tools via
xcode-select --install
- 10.9 or later
Linux
- Kernel version 3.6 or above
libbluetooth-dev
bluetoothd
disabled, if BlueZ 5.14 or later is installed. Usesudo hciconfig hci0 up
to power Bluetooth adapter up after stopping or disablingbluetoothd
.System V
:sudo service bluetooth stop
(once)sudo update-rc.d bluetooth remove
(persist on reboot)systemd
sudo systemctl stop bluetooth
(once)sudo systemctl disable bluetooth
(persist on reboot)
If you're using noble and bleno at the same time, connected BLE devices may not be able to retrieve a list of services from the BLE adaptor. Check out noble's documentation on bleno compatibility
Ubuntu/Debian/Raspbian
sudo apt-get install bluetooth bluez libbluetooth-dev libudev-dev libusb-1.0-0-dev
Make sure node
is on your path, if it's not, some options:
- symlink
nodejs
tonode
:sudo ln -s /usr/bin/nodejs /usr/bin/node
- install Node.js using the NodeSource package
Fedora / Other-RPM based
sudo yum install bluez bluez-libs bluez-libs-devel
Intel Edison
See Configure Intel Edison for Bluetooth LE (Smart) Development
FreeBSD
Make sure you have GNU Make:
sudo pkg install gmake
Disable automatic loading of the default Bluetooth stack by putting no-ubt.conf into /usr/local/etc/devd/no-ubt.conf
and restarting devd (sudo service devd restart
).
Unload ng_ubt
kernel module if already loaded:
sudo kldunload ng_ubt
Make sure you have read and write permissions on the /dev/usb/*
device that corresponds to your Bluetooth adapter.
Windows
- node-gyp requirements for Windows
- Python 2.7
- Visual Studio (Express)
- node-bluetooth-hci-socket prerequisites
- Compatible Bluetooth 4.0 USB adapter
- WinUSB driver setup for Bluetooth 4.0 USB adapter, using Zadig tool
Install
npm install bleno@npm:@abandonware/bleno
Usage
var bleno = require('bleno');
See examples folder for code examples.
Actions
Advertising
Start advertising
NOTE: bleno.state
must be poweredOn
before advertising is started. bleno.on('stateChange', callback(state));
can be used register for state change events.
var name = 'name';
var serviceUuids = ['fffffffffffffffffffffffffffffff0']
bleno.startAdvertising(name, serviceUuids[, callback(error)]);
Note:: there are limits on the name and service UUID's
- name
- maximum 26 bytes
- service UUID's
- 1 128-bit service UUID
- 1 128-bit service UUID + 2 16-bit service UUID's
- 7 16-bit service UUID
Start advertising iBeacon
var uuid = 'e2c56db5dffb48d2b060d0f5a71096e0';
var major = 0; // 0x0000 - 0xffff
var minor = 0; // 0x0000 - 0xffff
var measuredPower = -59; // -128 - 127
bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower[, callback(error)]);
Notes::
- OS X:
- in iBeacon mode your peripheral is non-connectable!
Start advertising with EIR data (Linux only)
var scanData = Buffer.alloc(...); // maximum 31 bytes
var advertisementData = Buffer.alloc(...); // maximum 31 bytes
bleno.startAdvertisingWithEIRData(advertisementData[, scanData, callback(error)]);
- For EIR format section Bluetooth Core Specification sections and 8 and 18 for more information the data format.
Stop advertising
bleno.stopAdvertising([callback]);
Set services
Set the primary services available on the peripheral.
var services = [
... // see PrimaryService for data type
];
bleno.setServices(services[, callback(error)]);
Disconnect client
bleno.disconnect(); // Linux only
Update RSSI
bleno.updateRssi([callback(error, rssi)]); // not available in OS X 10.9
Primary Service
var PrimaryService = bleno.PrimaryService;
var primaryService = new PrimaryService({
uuid: 'fffffffffffffffffffffffffffffff0', // or 'fff0' for 16-bit
characteristics: [
// see Characteristic for data type
]
});
Characteristic
var Characteristic = bleno.Characteristic;
var characteristic = new Characteristic({
uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
properties: [ ... ], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
secure: [ ... ], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
value: null, // optional static value, must be of type Buffer - for read only characteristics
descriptors: [
// see Descriptor for data type
],
onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
onNotify: null, // optional notify sent handler, function() { ...}
onIndicate: null // optional indicate confirmation received handler, function() { ...}
});
Result codes
- Characteristic.RESULT_SUCCESS
- Characteristic.RESULTINVALIDOFFSET
- Characteristic.RESULTINVALIDATTRIBUTE_LENGTH
- Characteristic.RESULTUNLIKELYERROR
Read requests
Can specify read request handler via constructor options or by extending Characteristic and overriding onReadRequest.
Parameters to handler are
offset
(0x0000 - 0xffff)callback
callback
must be called with result and data (of type Buffer
) - can be async.
var result = Characteristic.RESULT_SUCCESS;
var data = Buffer.alloc( ... );
callback(result, data);
Write requests
Can specify write request handler via constructor options or by extending Characteristic and overriding onWriteRequest.
Parameters to handler are
data
(Buffer)offset
(0x0000 - 0xffff)withoutResponse
(true | false)callback
.
callback
must be called with result code - can be async.
var result = Characteristic.RESULT_SUCCESS;
callback(result);
Notify subscribe
Can specify notify subscribe handler via constructor options or by extending Characteristic and overriding onSubscribe.
Parameters to handler are
maxValueSize
(maximum data size)updateValueCallback
(callback to call when value has changed)
Notify unsubscribe
Can specify notify unsubscribe handler via constructor options or by extending Characteristic and overriding onUnsubscribe.
Notify value changes
Call the updateValueCallback
callback (see Notify subscribe), with an argument of type Buffer
Can specify notify sent handler via constructor options or by extending Characteristic and overriding onNotify.
Descriptor
var Descriptor = bleno.Descriptor;
var descriptor = new Descriptor({
uuid: '2901',
value: 'value' // static value, must be of type Buffer or string if set
});
Events
Adapter state change
state = <"unknown" | "resetting" | "unsupported" | "unauthorized" | "poweredOff" | "poweredOn">
bleno.on('stateChange', callback(state));
Advertisement started
bleno.on('advertisingStart', callback(error));
bleno.on('advertisingStartError', callback(error));
Advertisement stopped
bleno.on('advertisingStop', callback);
Services set
bleno.on('servicesSet', callback(error));
bleno.on('servicesSetError', callback(error));
Accept
bleno.on('accept', callback(clientAddress)); // not available on OS X 10.9
Disconnect
bleno.on('disconnect', callback(clientAddress)); // Linux only
RSSI Update
bleno.on('rssiUpdate', callback(rssi)); // not available on OS X 10.9
Running on Linux
Note: Make sure you've also checked the Linux Prerequisites
Running without root/sudo
Run the following command:
sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
This grants the node
binary cap_net_raw
privileges, so it can start/stop BLE advertising.
Note: The above command requires setcap
to be installed, it can be installed using the following:
- apt:
sudo apt-get install libcap2-bin
- yum:
su -c \'yum install libcap2-bin\'
Multiple Adapters
hci0
is used by default to override set the BLENO_HCI_DEVICE_ID
environment variable to the interface number.
Example, specify hci1
:
sudo BLENO_HCI_DEVICE_ID=1 node <your file>.js
Set custom device name
By default bleno uses the hostname (require('os').hostname()
) as the value for the device name (0x2a00) characterisic, to match the behaviour of OS X.
A custom device name can be specified by setting the BLENO_DEVICE_NAME
environment variable:
sudo BLENO_DEVICE_NAME="custom device name" node <your file>.js
or
process.env['BLENO_DEVICE_NAME'] = 'custom device name';
Set Advertising Interval
bleno uses a 100 ms advertising interval by default.
A custom advertising interval can be specified by setting the BLENO_ADVERTISING_INTERVAL
environment variable with the desired value in milliseconds:
sudo BLENO_ADVERTISING_INTERVAL=500 node <your file>.js
Advertising intervals must be between 20 ms to 10 s (10,000 ms).
Useful tools/links
- Tools
- LightBlue for iOS/OS X
- nRF Master Control Panel (BLE) for Android
- hcitool and
gatttool
by BlueZ for Linux
License
Copyright (C) 2015 Sandeep Mistry sandeep.mistry@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
你可能也喜欢
- 0bit-mentions 中文文档教程
- @123swap/swap-core 中文文档教程
- @4success/successfactors-cli-tools 中文文档教程
- @7urtle/logger 中文文档教程
- @abcnews/scrollyteller 中文文档教程
- @abdul778/react-calendar-timeline 中文文档教程
- @activepipe/draft-js 中文文档教程
- @adamcikado/flydrive-s3 中文文档教程
- @adgstudio/graphql-generator 中文文档教程
- @adia-technology/international-ssn-validator 中文文档教程