# Bluetooth Low Energy (Bluetooth Low Energy, BLE)
Host Mode: Base Library 1.1.0 (WeChat Client) iOS 6.5.6,Android 6.5.7) Start support.
Slave mode: base library 2.10.3 Start supporting.
Bluetooth Low Energy is derived from Bluetooth 4.0 Compared with classic Bluetooth, the power consumption is extremely low, the transmission speed is faster, but the amount of data transmitted is small. Commonly used in a variety of intelligent electronic products that require high battery life and only need small data transmission, such as smart wearable devices, smart appliances, sensors, etc., the application scenarios are wide.
# 1. role/Working mode
The Bluetooth Low Energy protocol defines a number of roles, or operating modes, for devices. Mini Program Bluetooth currently supports the following:
# 1) Center equipment/Host (Central)
The central device can scan the peripheral equipment and connect with it when it finds the peripheral equipment, then it can use the service provided by the peripheral equipment.
In general, the phone will act as the central device, the use of peripheral equipment to provide data processing or display and so on. The Mini Program provides a Bluetooth Low Energy interface that sets the phone as a central device by default.
# 2) Peripheral equipment/Slave machine (Peripheral)
The peripheral equipment is always on the air, waiting to be searched and connected by the central equipment. Such as smart bracelets, sensors and other devices.
If the peripheral equipment is set to unconnectable when it is broadcast, it is also referred to as broadcast mode. (Broadcaster), Common examples areBluetooth beacon (Beacon) Equipment.
# Be careful
In Mini Programs, a Bluetooth device can be in both host and slave mode. On an Android device, you just need to call wx.openBluetoothAdapter Initialize a Bluetooth AdapterAnd in iOS Device, you need to use two different mode
Parameter initializes the Bluetooth adapter for the central and peripheral equipment, respectively. It is recommended that the master and slave modes be initialized once.wx.closeBluetoothAdapter The Bluetooth adapter in both modes is turned off.
# 2. Communication protocol
After two Bluetooth Low Energy devices have established a connection, the data interaction between the two parties is based on GATT (Generic Attribute Profile) Specification, according to which a configuration file can be defined (Profile), describe the services provided by this Bluetooth device (Service)。
In the whole communication process, there are several main concepts:
- Profile (Profile): Profile Are predefined by the Bluetooth standard Service That do not actually exist in Bluetooth devices. If Bluetooth devices are to be compatible with each other, they only have to support the same Profile Just... A Bluetooth device can support multiple Profile。
- service (Service): Service A device can provide multiple services, such as power information service, system information service and so on. Each service consists of a UUID Unique identification.
- Features (Characteristic): Each Service Contain 0 Many Characteristic。For example, the power information service would have a Characteristic Represents power data. Characteristic Contains avalue (value)and 0 ManyDescriptor (Descriptor) Composition.When communicating with Bluetooth devices, it is mainly through reading and writing Characteristic of value Done. Each Characteristic By a UUID Unique identification.
- Descriptor (Descriptor): Descriptor Is a defined property that describes an eigenvalue. For example, Descriptor You can specify human-readable descriptions, ranges of feature values, or feature-specific units of measurement. Each Descriptor By a UUID Unique identification.
As shown in the figure below, we can simply understand that: Each Bluetooth device may provide multiple Service, each Service There may be multiple Characteristic, we base on the protocol of the Bluetooth device on the corresponding Characteristic The value can be read and written to achieve the purpose of communication with it.
# 3. UUID (Universally Unique Identifier)
According to Bluetooth 4.2 Protocol specification(Vol 3, Part B, section 2.5.1 UUID),UUID Is a 128 The unique identifier of the bit that identifies the Service and Characteristic Etc.
In order to reduce storage and transmission 128 position UUID Value of the burden, the Bluetooth Technology Alliance pre-allocated a batch of UUID. This batch UUID Possess a common part, known as the Bluetooth Base UUID, i.e. 00000000-0000-1000-8000-00805F9B34FB
Of the system. Accordingly, the pre-allocated UUID Can also be used 16 Bit or 32 The number indicates that, 16 position UUID Most commonly used. use 16/32 Bit UUID Can reduce the load of storage and transmission. Developer-defined UUID Care should be taken not to be associated with the pre-assigned UUID Conflict.
In the Mini Program,wx.startBluetoothDevicesDiscovery and wx.getConnectedBluetoothDevices Parameter Support for 16/32/128 position UUID。In the parameters of other interfaces,
- iOS Support for direct use 16 position and 128 Bit UUID
- Android 8.0.9 Version start, support for direct use of 16/32/128 position UUID
- Android 8.0.9 The following versions are supported only 128 Bit UUID, which requires the developer to manually fill the position to 128 Bit. The complement is as followsfor example
128-bit UUID = 16-bit UUID * 296 + Bluetooth Base UUID 128-bit UUID = 32-bit UUID * 296 + Bluetooth Base UUID
0x180F -> 0000180F-0000-1000-8000-00805F9B34FB
The return value for all interfaces is uniform 128 position UUID。
# 4. Process for the use of center equipment
# 4.1 Initialize the Bluetooth module
Before using the Bluetooth interface, you must first call the wx.openBluetoothAdapter Initializes the Bluetooth adapter module. Other interfaces must be successfully initialized before they can be invoked.
An error is returned when the Bluetooth switch is not turned on or the phone does not support Bluetooth (errCode=10001)At this point the Mini Program Bluetooth module has been initialized and can be accessed by wx.onBluetoothAdapterStateChange Monitoring changes in the state of the phone's Bluetooth, you can also call all the API of the Bluetooth module. Developers in the development should consider compatible users in the use of Mini Program process to open/Turn off the Bluetooth switch situation and give the necessary tips to improve usability.
# 4.2 Scan and find Bluetooth peripheral equipment
After the Bluetooth module is successfully initialized, it is generally necessary to pass the wx.startBluetoothDevicesDiscovery Scan peripheral equipment. When a Bluetooth peripheral equipment is scanned, it calls back. wx.onBluetoothDeviceFound Event, returns the device that was scanned to. Scanning equipment is more expensive system resources, please call in time after searching the required equipment. wx.stopBluetoothDevicesDiscovery Stop the search.
If you have previously connected a device, get the DeviceId, skip the scanning step.
// Monitor scans for new device events
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach((device) => {
// We can do some filtering here.
console.log('Device Found', device)
})
// When you find the device you want to search for, stop scanning in time
wx.stopBluetoothDevicesDiscovery()
})
// Initialize the Bluetooth module
wx.openBluetoothAdapter({
mode: 'central',
success: (res) => {
// Start scouting for nearby Bluetooth peripheral equipment.
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
})
},
fail: (res) => {
if (res.errCode !== 10001) return
wx.onBluetoothAdapterStateChange((res) => {
if (!res.available) return
// Start searching for nearby Bluetooth peripheral equipment.
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
})
})
}
})
# 4.3 Connecting devices
To communicate between Bluetooth low energy devices, a connection must first be established.
wx.createBLEConnection({
deviceId, // Search to the device's deviceId
success: () => {
// Connect successfully, get services
wx.getBLEDeviceServices({
deviceId,
})
}
})
# 4.4 Access to Bluetooth peripheral equipment
wx.getBLEDeviceServices({
deviceId, // Search to the device's deviceId
success: (res) => {
for (let i = 0 i < res.services.length i++) {
if (res.services[i].isPrimary) {
// According to the specific business needs, choose a main service for communication
}
}
}
})
# 4.5 Eigenvalues for read and write services
wx.getBLEDeviceCharacteristics({
deviceId, // Search to the device's deviceId
serviceId, // One of the services found in the previous step
success: (res) => {
for (let i = 0 i < res.characteristics.length i++) {
let item = res.characteristics [i]
if (item.properties.write) { // The characteristic value can be written
// This example is to send a Bluetooth device a 0x00 of 16 Binary data
// Actual use, data should be sent according to the device specific protocol
let buffer = new ArrayBuffer(1)
let DataView = new DataView(buffer)
dataView.setUint8(0, 0)
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
value: buffer,
})
}
if (item.properties.read) { // This feature is readable
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
})
}
if (item.properties.notify || item.properties.indicate) {
// Must be enabled wx.notifyBLECharacteristicValueChange To listen in on the device. onBLECharacteristicValueChange event
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true,
})
}
}
}
})
// Monitor before operation to ensure the first time to obtain data
wx.onBLECharacteristicValueChange((result) => {
// Disconnect and turn off the Bluetooth adapter at the right time after use
wx.closeBLEConnection({
deviceId,
})
wx.closeBluetoothAdapter({})
})
# 4.6 Disconnect and turn off the Bluetooth adapter
After use, you should disconnect and turn off the Bluetooth adapter at the right time.
# 5. Note
- iOS On, to the eigenvalues of the
read
、write
、notify
Operation, since the system needs to acquire an eigenvalue instance, the incomingserviceId
andcharacteristicId
Must be made by wx.getBLEDeviceServices and wx.getBLEDeviceCharacteristics It can be used only after getting it. Recommend that uniformity be implemented after the connection is established wx.getBLEDeviceServices and wx.getBLEDeviceCharacteristics After the data interaction with the Bluetooth device. - Considering that the Bluetooth function can be positioned indirectly, Android 6.0 With versions above, device searches cannot be performed without location permissions or location switches not turned on.
- On Android, some models will have more when they get device services
00001800
and00001801
UUID Of services, which is the system behavior, be careful not to use these two services. - Establishing and closing connections must be called in pairs. If you fail to close the connection in time to release resources, it is easy to cause state 133 GATT ERROR Of the anomaly.
- When transferring data with a Bluetooth device, it is important to note MTU (Maximum Transmission Unit). If the amount of data exceeds MTU Will cause an error. It is recommended to transmit in pieces according to the Bluetooth device protocol. Android devices can call wx.setBLEMTU Conduct MTU Consultation. in MTU Unknown cases, it is recommended to use 20 Bytes are transmitted in units.