# Bluetooth Low Energy Mesh Network (BLE Mesh)
Bluetooth Low Energy Mesh Network (BLE Mesh) is built on Bluetooth Low Energy (BLE) A communication protocol based on the protocol that allows a large number of BLE devices to form a mesh network, enabling interconnection and co-control between devices over a large enough physical coverage to meet the communication needs of multi-device scenarios.
The BLE Mesh communication protocol supports excellent features such as low power consumption, scalability, flexibility, high reliability, and security, and has a wide range of applications in smart home, smart lighting, industrial automation, medical health, environmental monitoring and other fields.
# 1. Fundamental Concepts
# BLE Mesh Network
BLE mesh network is a many-to-many network topology in which device nodes in the network send and receive messages through a "publish / subscribe mechanism."
# Networking of equipment
Undistributed BLE Mesh devices need to complete distribution network operations before they can join the BLE Mesh network and become a device node to communicate with other nodes in the network. The device that helps the BLE Mesh device complete the distribution network operation is called the "start configuration device."
# Device nodes
After the operation of the distribution network, the undistributed BLE Mesh device becomes the device node in the BLE Mesh network. The device node typically has one or more of the characteristics of relay, agent, friend, low power consumption, and so on.
A device node consists of several elements, each of which contains multiple models, and each model defines the basic functions of the node, such as the state required by the node; messages to control the state; and actions generated by processing messages. The implementation of node function is based on model. The model can be divided into SIG model and custom model. The former is defined by SIG, while the latter is defined by the developer. The model can also be divided into client model and service model based on the sending / receiving of the message.
# Mesh address
If the device nodes in the BLE Mesh network want to communicate with each other, it is necessary to assign an address for each node to send and receive messages. Mesh addresses are divided into unicast addresses, multicast addresses and virtual addresses.
The single-broadcast address is assigned by Startup Configure Devices after the device is networked successfully. Single-broadcast addresses may appear in the Source / Destination Address field of the message. A message sent to a single-broadcast address can only be processed by the element that owns that single-broadcasting address.
A multicast address is a multicast address in BLE Mesh networks that is often used to group device nodes. If you send a message with a broadcast address, all device nodes that have subscribed to the broadcast address receive the message.
The virtual address is associated with a specific UUID tag and can be used as the publish or subscribe address for the model.
# Mesh message
Mesh messages are divided into control messages and access messages. Control messages are messages related to BLE Mesh network operations, such as heartbeats and friend request messages. Access messages allow the client model to retrieve or set state values in the server model, or are used by the server to report state values.
Mesh message is the basic unit of data transmission in BLE Mesh network. It is composed of operation code and parameters. The former is used to identify the unique use of the message, and the latter can store valid data, such as destination address, device state, etc.
# Agent Devices
If you want other devices that are not BLE Mesh devices (such as mobile phones) to become part of the BLE Mesh network, you can use GATT connections with a proxy device node to send and receive various messages in the BLE mesh network.
# 2."Weixin Mini Program BLE Mesh Plug-in" Usage Process
In Weixin Mini Program, the basic capabilities of BLE Mesh are provided in the form of Mini Programs, based on the standard BLE Mesh communication protocol. Developers can achieve the local fast network distribution, control management, network sharing and other functions of BLE Mesh devices through the "Mini Program BLE Mesh plug-in."The platform provides interface documentation and [example Mini Program]] for easy access by developers.
# 2.1 Access plug-in
Before using a plug-in, you first need to add a plug in Settings - Third-Party Services - Plug-in Management in the Weixin Mini Program administration background. Developers can log in to the Mini Program administration background and find and add plug-ins via AppID - wx013447465d3aa024. Then declare the specified version of the plug-in in theapagejsonfile. For a detailed introduction of the Mini Programs plug-in, see " Using Plug-ins ."
At present, only those Weixin Mini Program who have applied for the " [" service category can use the "Mini Program BLEMesh plug-in."
"plugins": {
"ble-mesh-plugin": {
"version": "latest",
"provider": "wx013447465d3aa024"
}
}
TherequirePluginmethod to get the relevant interface for the Weixin Mini Program BLEMesh plug-in.For example, you can call it like this:
const { getMeshBLEManager } = requirePlugin('ble-mesh-plugin')
# 2.2 Initial BLE Mesh Bluetooth Configurator
Before you can use Weixin Mini Program BLEMesh capabilities, you need to prepare the BLEMesh Bluetooth Configurator to scan for nearby BLEMesh devices.
const meshBLEManager = getMeshBLEManager()
meshBLEManager.init().then(({ enabled }) => {
if (!enabled) {
wx.showModal({
title: '错误',
content: '未启用蓝牙功能, 请打开蓝牙后重试',
showCancel: false,
})
}
})
# 2.3 Scan found BLE Mesh device
After the BLE Mesh Bluetooth Configurator is first developed, the BLE Mesh device needs to be scanned bymeshBLEManager.startScanMeshDevice. If the device is scanned nearby, it will call back meshBLEManager.onMeshDeviceFoundevent that returns the scanned instance of the BLEMesh device.Since the operation of scanning equipment consumes system resources, please callmeshBLEManager.stopScanMeshDeviceto stop scanning after searching the required equipment.
meshBLEManager.onMeshDeviceFound((res) => {
// 扫描到的 BLE Mesh 设备
console.log(res.device)
// 找到需要的设备后,停止扫描操作
meshBLEManager.stopScanMeshDevice()
})
// Start scanning BLE Mesh devices
meshBLEManager.startScanMeshDevice({
allowDuplicatesKey: false,
})
# 2.4 Creating a BLE Mesh Network
To achieve the interconnection and collaborative control of multiple BLE Mesh devices, a BLE Mesh network needs to be created.
createMeshNetwork({ name: 'mesh_network' }).then((res) => {
// 创建 BLE Mesh 网络后会生成唯一的网络标识id,用于后续的网络管理、设备配网、设备消息通信等功能。
console.log(res.networkId)
})
# 2.5 Shared BLE Mesh Network
Developers can import and export BLE Mesh network data byexportMeshNetworksandimportMeshNetworks, allowing multiple Weixin Mini Program users to control and manage BLE Mesh devices under the same network.In addition, callinggetMeshNetworksalso gets a list of all BLE mesh networks that currently exist.
// Export BLE Mesh network data
const { restoreData } = exportMeshNetworks({ data: [{ name: 'mesh_network' }] })
// Import BLE Mesh network data
importMeshNetworks({ restoreData })
// Get a list of currently existing BLE Mesh networks
const networks = getMeshNetworks() // [{ name: 'network_name', networkId: 'network_id' }]
# Be careful
Persistent storage of the data may be required after exporting the BLE Mesh network data viaexportMeshNetworks.To ensure network security, developers should perform data encryption and storage operations, and then decrypt the data at import time.
When importing BLE Mesh network data to a new user Weixin Mini Program viaimportMeshNetworks, due to iOS system limitations, different users of the same BLE Mesh device get different Bluetooth device IDs, making it impossible to establish a proxy device connection. This requires the device side to continuously broadcast after the distribution network is successful.Node IdentityBluetooth broadcast package, convenient Mini Program plug-in to identify device nodes, update Bluetooth deviceId.
# 2.6 BLE Mesh Network Management
ThroughgetMeshNetworkManagerThe BLE Mesh Network Management Configurator is available, which includes functions such as creating / deleting BLE Mesh groups, obtaining a list of unicast addresses for all nodes in the BLE Mesh network, and a list of multicast addresses.
// Get the BLE Mesh Network Management Configurator
const meshNetworkManager = getMeshNetworkManager({ networkId: 'network_id' })
// Create a BLE Mesh group
const group = meshNetworkManager.createGroup({ name: 'group_name' })
// Delete the BLEMesh group
meshNetworkManager.removeGroup({ name: 'group_name' })
// Get a list of group broadcast addresses
const groups = meshNetworkManager.getGroups()
[{
name, // BLE Mesh 群组名称
address, // BLE Mesh 组播地址
nodes, // BLE Mesh 组播地址下绑定的设备节点信息
}]
// Get a list of single-air addresses
const unicasts = meshNetworkManager.getUnicasts()
[{
deviceId, // BLE Mesh 设备id
name, // BLE Mesh 设备名称
localName, // BLE Mesh 设备广播数据段中的 LocalName 数据段
address, // BLE Mesh 设备单播地址
}]
# 2.7 BLE Mesh Equipment Distribution Network
To implement the BLE Mesh device provisioning, you first need to obtain the BLE Mesh device provisioning managerprovisioningManager, and then use theprovisioningManager.provisionComplete distribution network operation.In addition, multiple BLEMesh devices can be provisioned with one click viaprovisioningManager.batchProvision.When the BLEMesh device completes the distribution network operation, it is considered to join the BLEMesh network.
// Get the BLE Mesh Device Access Configurator
const provisioningManager = getProvisioningManager({ networkId: 'network_id' })
// Single BLE Mesh device distribution network
await provisioningManager.provision({
unprovisionedDevice, // 未配网的 BLE Mesh 设备实例
authenticationMethod: AuthenticationMethod.NoOOB, // 配网时的 OOB 安全认证方式
})
// Batches of multiple BLE Mesh devices
await provisioningManager.batchProvision({
unprovisionedDevices, // 未配网的 BLE Mesh 设备实例数组
})
# 2.8 BLE Mesh Device Messaging
After the completion of the BLE Mesh equipment distribution network, if you want to communicate with the equipment message, to achieve control equipment and access to equipment information and other functions.You should first obtain the BLEMesh proxy device Guest ConfiguratorproxyClientManager, and use theproxyClientManager.hasProxyServerVerify that there is an available proxy device around, and then passproxyClientManager.addAppKeyToNode [[TAG-@@AndproxyClientManager.bindAppKeyToModel`The AppKey in the BLE Mesh network is bound to the server model of the target device, and finally sends a standard BLE Mesh message to change the state on the server model of the target device or retrieve relevant information.
// Get the BLE Mesh Proxy Device Guest Configurator
const proxyClientManager = getProxyClientManager({ networkId: 'network_id' })
// Check if there are available proxy devices around Server
const hasProxyServer = proxyClientManager.hasProxyServer
if (hasProxyServer) {
// 添加 AppKey 到目标设备
await this.proxyClientManager.addAppKeyToNode({
destination, // 目标设备的单播地址
})
// 绑定 AppKey 到目标设备的 GenericOnOffServer 模型上
await proxyClientManager.bindAppKeyToModel({
destination, // 目标设备的单播地址
modelId: ModelIds.GenericOnOffServer, // 标准 GenericOnOffServer 模型的 modelId
})
// 获取目标设备的 GenericOnOffServer 模型上的开关状态
const resGet = await proxyClientManager.getOnOffStatus({
destination, // 目标设备的单播地址或组播地址
})
console.log(resGet.source, resGet.message.isOn)
// 控制目标设备的 GenericOnOffServer 模型上的开关状态
const resSet = await proxyClientManager.setOnOffStatus({
destination, // 目标设备的单播地址或组播地址
status, // 需要设置的开关状态
})
console.log(resSet.source, resSet.message.isOn)
// 开发者还可以通过自定义 BLE Mesh 消息,发送接收最基础的 opcode 和 parameters ,来实现例如 Vendor Model 的功能。
proxyClientManager.onMessage(({ source, opcode, parameters }) => {
// handle mesh message
})
proxyClientManager.send({
destination, // 目标设备的单播地址或组播地址
opcode, // 操作码
parameters, // 携带参数
})
}
# 3. Note
Developers can quickly access BLE Mesh capabilities through the "Weixin Mini Program" sample Mini Program .
For a detailed description of Weixin Mini Program BLEMesh capabilities, please refer to the "Mini Program BLEMesh Plug-ins" interface documentation .
Please try to use the "Weixin Mini Program BLEMesh plug-in"
latestversion to ensure full functionality, stable availability.At present, the "Weixin Mini Program BLEMesh Plug-in" only provides the basic capabilities of BLEMesh, and will be updated iteratively as the developer needs.