Bluetooth Mesh

Last Updated on : 2023-06-05 02:50:03download

Bluetooth mesh enables Bluetooth devices to communicate with each other over a mesh network. This topic describes the API methods and examples of Bluetooth mesh capabilities provided by Smart Life App SDK for iOS.

Concepts

The Bluetooth Special Interest Group (SIG) provides Bluetooth mesh technologies to enable mesh networking. Bluetooth mesh is also known as Bluetooth SIG mesh. This mesh networking standard allows for many-to-many communication over Bluetooth radio. The standard must be followed to implement Bluetooth mesh networking and device updates.

Terms

Term Description
Product category and type Each Bluetooth mesh device corresponds to a product that belongs to a product category and a product type. The SDK provides pcc to specify a product category and type to specify a product type.
Mesh group localId The 2-byte localId field provides a unique identifier to distinguish each mesh group on a mesh network. To control devices in a group, commands can be sent to the mesh network with the specified localId field value.
Mesh nodeId The 2-byte nodeId field provides a unique identifier to distinguish each mesh device on a mesh network. To control a device on the network, commands can be sent to the mesh network with the specified nodeId field value.
Local connections Paired devices are controlled with commands on a mesh network through Bluetooth connections.
Gateway connections Paired devices are controlled with commands on a mesh network through gateway connections. The gateway must be deployed close to the devices.

Synchronous operations

When devices are added, deleted, or managed in a group, these operations are implemented with local Bluetooth commands and synchronously recorded in the cloud. Therefore, device information is synchronized to the local mesh network and the cloud at the same time.

Device classification rules (categories and types)

  • A device is classified with a combination of device type, product category, and product type. The class name is then stored in the little-endian format.

    • Device type
      • Standard type: 1
      • Raw: 2
    • Bluetooth mesh products are classified into the following product categories:
      • Lighting (01): smart lights ranging from cool white lights (C) to white and colored lights (RGBCW)
      • Electrical (02): one to six-outlet sockets
      • Remote control (05): one to six-button remote controls
    • Product types of a category:
      • Smart lights ranging from cool white lights (C) to white and colored lights (RGBCW) (01–05)
      • One to six-outlet power strips (01–06)
      • One to six-button remote controls (01–06)
  • Example:

    Product Class value Description
    Standard white and colored light (RGBCW) 1510 1015 in the little-endian format:
    • 1: standard device
    • 01: light
    • 5: white and colored light (RGBCW)
    Standard 4-outlet power strip 2410 1024 in the little-endian format:
    • 1: standard device
    • 02: socket
    • 4: 4-outlet power strip
    Raw type of device xx20 20xx in the little-endian format: 2 represents a raw type of device.

Management

Bluetooth mesh operation classes are included in the file ThingSmartBleMesh+SIGMesh.h.

Create a Bluetooth mesh network

A home can belong to multiple Bluetooth mesh networks, but one Bluetooth mesh network is recommended for each home. Before the request, check whether a Bluetooth mesh network is created. If not, you can call this API method to create one.

All Bluetooth mesh operations are implemented based on the initialized home data. For more information, see Home Management.

API description

+ (void)createSIGMeshWithHomeId:(long long)homeId
						success:(void(^)(ThingSmartBleMeshModel *meshModel))success
						failure:(ThingFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback.
failure The failure callback.

Example

ObjC:

ThingSmartHome *home = #<The initialized home instance>;
long long homeId = home.homeModel.homeId;
[ThingSmartBleMesh createSIGMeshWithHomeId:homeId success:^(ThingSmartBleMeshModel *meshModel) {
	// success do...
} failure:^(NSError *error) {
	NSLog(@"create mesh error: %@", error);
}];

Delete a Bluetooth mesh network

API description

Deletes a Bluetooth mesh network. If sub-devices are included in the mesh group, they are also removed.

- (void)removeMeshWithSuccess:(ThingSuccessHandler)success failure:(ThingFailureError)failure;

Parameters

Parameter Description
success The success callback.
failure The failure callback.

Example

self.mesh = #<ThingSmartBleMesh instance>;
[self.mesh removeMeshWithSuccess:^{
	// success do...
} failure:^(NSError *error) {
	XCTFail(@"test remove mesh failure: %@", error);
}];

Query a list of mesh networks in a home

API description

Returns a list of mesh networks for an initialized home instance.

- (void)getSIGMeshListWithSuccess:(void(^)(NSArray <ThingSmartBleMeshModel *> *list))success
						  failure:(ThingFailureError)failure;

Parameters

Parameter Description
success The success callback.
failure The failure callback.

Example

ThingSmartHome *home = #<home instance>
[home getSIGMeshListWithSuccess:^(NSArray<ThingSmartBleMeshModel *> *list) {
	// success do
} failure:^(NSError *error) {
	NSLog(@"get Bluetooth mesh list error: %@", error);
}];

Query a Bluetooth mesh instance

API description

+ (instancetype)bleMeshWithMeshId:(NSString *)meshId homeId:(long long)homeId;

Parameters

Parameter Description
meshId The mesh ID.
homeId The home ID.

Example

// Returns the mesh instance `sigMeshModel` for the `home` instance of the `ThingSmartHome` class.
ThingSmartBleMeshModel *sigMeshModel = [self getCurrentHome].sigMeshModel;

Initialize a Bluetooth mesh network controller

Initializes a Bluetooth mesh network controller to implement features, such as device scanning, pairing, and connection.

meshModel is set to the value of the parameter sigMeshModel, rather than the parameter meshModel, from ThingSmartHome.

API description

+ (ThingSmartSIGMeshManager * _Nullable)initSIGMeshManager:(ThingSmartBleMeshModel *)meshModel
                                                      ttl:(NSInteger)ttl
                                                  nodeIds:(NSArray * _Nullable)nodeIds

Parameters

Parameter Description
meshModel sigMeshModel
ttl The maximum number of times a message can be forwarded over a Bluetooth mesh network. Default value: 8.
nodeIds The list of nodeId for each device on a Bluetooth mesh network, excluding low-power nodes.

Get a Bluetooth mesh network controller

Returns a Bluetooth mesh network controller only after ThingSmartBleMesh is used to initialize one.

API description

+ (ThingSmartSIGMeshManager * _Nullable)getSIGMeshManager:(NSString *)meshId;

Parameters

Parameter Description
meshId The mesh ID.

Bluetooth mesh operation classes are included in the file ThingSmartSIGMeshManager.

Connect to a Bluetooth mesh sub-device

Connects to a Bluetooth mesh sub-device with ScanForProxyed. For more information, see Pairing.

- (void)startScanWithScanType:(ThingSmartSIGScanType)scanType
		  meshModel:(ThingSmartBleMeshModel *)meshModel __deprecated_msg("This method is deprecated, Use startSearch instead");
                    
- (void)startSearch;

Pairing

A Bluetooth device in the reset and disconnected state can be paired to join a Bluetooth mesh network. Common device resetting methods are listed in the following table.

Product category Lighting product Socket
Reset method Turn on and off the light consecutively three times in a row Press and hold the switch for three seconds
State ready for pairing Blink quickly Indicator blinking quickly

Scan for sub-devices pending pairing

API description

Starts scanning for a Bluetooth mesh device pending pairing. When the device is discovered, it can be paired. In a pairing process, the Bluetooth mesh device joins the target mesh network based on certain communication technologies.

meshModel is set to the value of the parameter sigMeshModel, rather than the parameter meshModel, from ThingSmartHome.

- (void)startScanWithScanType:(ThingSmartSIGScanType)scanType
		  meshModel:(ThingSmartBleMeshModel *)meshModel __deprecated_msg("This method is deprecated, Use startSearch instead");
                    
- (void)startSearch;

Parameters

Parameter Description
scanType The type of scanning. Devices that are paired or not paired can be discovered. If paired devices are discovered, they automatically join the target mesh network.
meshModel The information about the mesh model.

Example

//[ThingSmartSIGMeshManager sharedInstance].delegate = self;
// ScanForUnprovision, // Scans for devices that are not paired.
// ScanForProxyed, // Scans for paired devices.
//[[ThingSmartSIGMeshManager sharedInstance] startScanWithScanType:ScanForUnprovision
//                            meshModel:home.sigMeshModel];

    ThingSmartSIGMeshManager *manager = [ThingSmartBleMesh getSIGMeshManager:@"meshId"];
    manager.delegate = self;
    [manager startSearch];

Callback

After a device is discovered, the following method can be implemented in the callback ThingSmartSIGMeshManagerDelegate to query the discovered device.

// An device pending pairing is discovered.
- (void)sigMeshManager:(ThingSmartSIGMeshManager *)manager
	   didScanedDevice:(ThingSmartSIGMeshDiscoverDeviceInfo *)device;

Parameters

Parameter Description
manager The information about the mesh manager.
device The information about the device pending pairing.

Activate sub-devices

Pairs standard Bluetooth mesh devices.

API description

- (void)startActive:(NSArray<ThingSmartSIGMeshDiscoverDeviceInfo *> *)devList meshModel:(ThingSmartBleMeshModel *)meshModel __deprecated_msg("This method is deprecated, Use startActive: instead");

- (void)startActive:(NSArray<ThingSmartSIGMeshDiscoverDeviceInfo *> *)devList;

Parameters

Parameter Description
devList The list of devices to be activated.
meshModel The information about the mesh model.

Callback for an activated sub-device

API description

After a device is activated or failed to be activated, the following method can be implemented in the callback ThingSmartSIGMeshManagerDelegate.

The sub-device is activated:

- (void)sigMeshManager:(ThingSmartSIGMeshManager *)manager
	didActiveSubDevice:(ThingSmartSIGMeshDiscoverDeviceInfo *)device
				 devId:(NSString *)devId
				 error:(NSError *)error;

Parameters

Parameter Description
manager The information about the mesh manager.
device The information about the device.
devId The device ID.
error The error message that might be returned during activation. If it is returned, name and deviceId are empty.

API description

The sub-device failed to be activated:

- (void)sigMeshManager:(ThingSmartSIGMeshManager *)manager
 didFailToActiveDevice:(ThingSmartSIGMeshDiscoverDeviceInfo *)device
				 error:(NSError *)error;

Parameters

Parameter Description
manager The information about the mesh manager.
device The information about the device.
error The error message that might be returned during activation.

Stop activating a sub-device

Stops pairing a Bluetooth device during either the device scanning or pairing stage.

API description

- (void)stopActiveDevice;

Identify mesh connections

Checks whether Bluetooth devices are connected to a mesh network. This result determines the way to send control and operation commands.

// The mesh connection tag. If a Bluetooth device is connected to the mesh network, this value is `yes`.
//BOOL isLogin = [ThingSmartSIGMeshManager sharedInstance].isLogin;

BOOL isLogin =  [ThingSmartBleMesh getSIGMeshManager:@"meshId"].isLogin;

Pair a mesh gateway

  • Pairs a Bluetooth mesh gateway in Wi-Fi Easy Connect (EZ) mode. For more information, see Wi-Fi EZ Mode.
  • Pairs a Bluetooth Low Energy (LE) and Wi-Fi combo gateway. For more information, see Pair a combo device.

Pair a sub-device with a mesh gateway

Pairs a sub-device with a Bluetooth mesh gateway. For more information, see Sub-Device Pairing.

Pairing error codes

Error code Description
701 An error has occurred while connecting to the device over Bluetooth.
702 An error has occurred while processing the composition response.
703 A composition timeout error has occurred.
704 Failed to add appkey.
705 A timeout error has occurred while adding appkey.
706 An error has occurred while processing the network transmission response.
707 A network transmission timeout error has occurred.
708 An error has occurred while processing the publication model response.
709 A publication model timeout error has occurred.
710 An error has occurred while processing the response of adding bind.
711 A timeout error has occurred while adding bind.
712 An IdentifySet timeout error has occurred.

Devices

The device class is ThingSmartDevice. In this class, the deviceType field of ThingSmartDeviceModel indicates a device type. The value of deviceType for mesh devices is ThingSmartDeviceModelTypeSIGMeshSubDev.

Query a device instance

API description

+ (instancetype)deviceWithDeviceId:(NSString *)devId;

Parameters

Parameter Description
devId The device ID.

Connect a mesh device over Bluetooth

Connects to a mesh device over Bluetooth from a mobile phone on which Bluetooth is enabled. Commands are sent to the device over Bluetooth. You can use deviceModel.isOnline && deviceModel.isMeshBleOnline to check the device connection status.

Connect a mesh device through a Bluetooth mesh gateway

Connects to a mesh device through a Bluetooth mesh gateway from a mobile phone on which Bluetooth is disabled or that is far away from the device. Commands are sent to the device over Wi-Fi. You can use deviceModel.isOnline && !deviceModel.isMeshBleOnline to check the device connection status.

Query Bluetooth mesh sub-device status

API description

- (void)getDeviceStatusWithDeviceModel:(ThingSmartDeviceModel *)deviceModel;

Parameters

Parameter Description
deviceModel The device model.

Remove a Bluetooth mesh sub-device

The device removal method is simplified and applies to all devices. For more information, see Remove devices.

Groups

Certain devices on a Bluetooth mesh network can be grouped, so they can be controlled with group control commands. For example, all lights are added to a group. Users can control the switch status and colors of the group and thus control all lights in the group with the same properties.

The devices of the same category are recommended to be added to the same Bluetooth mesh device group. Before devices are added to the group, the group address must be returned from the server end. The following methods of ThingSmartBleMeshGroup are available.

Generate a group ID in the cloud

API description

+ (void)getBleMeshGroupAddressFromCluondWithMeshId:(NSString *)meshId
					success:(ThingSuccessInt)success
					failure:(ThingFailureError)failure;

Parameters

Parameter Description
meshId The mesh ID.
success The success callback with the decimal value of localId returned.
failure The failure callback.

The group address returned from the server end must be added with 0x4000 before it is used in the request. In the response, a group named by groupName in sigMeshModel is returned.

Create a mesh group

API description

+ (void)createMeshGroupWithGroupName:(NSString *)groupName
							  meshId:(NSString *)meshId
							 localId:(NSString *)localId
								 pcc:(NSString *)pcc
							 success:(ThingSuccessInt)success
							 failure:(ThingFailureError)failure;

Parameters

Parameter Description
groupName The name of the mesh group.
meshId The mesh ID.
localId The local short address of the group. It is a 2-byte hexadecimal string.
pcc The category and type of the group device.
success The success callback with a group ID returned.
failure The failure callback.

Add a device to a mesh group over Bluetooth

API description

Adds a device to a group. The following method of ThingSmartSIGMeshManager is used.

- (void)addDeviceToGroupWithDevId:(NSString *)devId
					 groupAddress:(uint32_t)groupAddress;

Parameters

Parameter Description
devId The device ID.
groupAddress The address of the group.

Callback

// The callback for `ThingSmartSIGMeshManagerDelegate`.
- (void)sigMeshManager:(ThingSmartSIGMeshManager *)manager
didHandleGroupWithGroupAddress:(nonnull NSString *)groupAddress
		  deviceNodeId:(nonnull NSString *)nodeId
			 error:(NSError *)error;

Parameters

Parameter Description
manager The information about the manager.
groupAddress The hexadecimal mesh address of the group.
nodeId The hexadecimal mesh node address of the device.
error The failure callback.

Add a device to a mesh group through a gateway

API description

Adds a sub-device to a mesh group through a gateway by using ThingSmartBleMeshGroup. In this case, the sub-device must belong to the Bluetooth mesh gateway.

- (void)addSubDeviceWithSubList:(NSArray<ThingSmartDeviceModel *> * _Nonnull )subList success:(nullable ThingSuccessHandler)success failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
subList The sub-device of the gateway to be managed.
success The success callback.
failure The failure callback.

Callback for ThingSmartBleMeshGroupDelegate

@protocol ThingSmartBleMeshGroupDelegate <NSObject>

/// The response of adding a Bluetooth sub-device to a mesh group through a gateway.
///Either of the following error messages might be returned:<ul><li>`1`: The maximum number of scenes allowed is exceeded.</li><li>`2`: The sub-device timeout error has occurred.</li><li>`3`: The specified parameter value is out of the valid range.<ul><li>`4`: An error has occurred while writing to files.</li><li>`5`: Other errors have occurred while processing your request.</li></ul>
/// Group Response of Zigbee Devices Joining Gateway
/// 1: Over the Scenario Limit 2: Subdevice Timeout 3: Setting Value Out of Range 4: Write File Error 5: Other Errors
- (void)meshGroup:(ThingSmartBleMeshGroup *)group addResponseCode:(NSArray <NSNumber *> *)responseCode;

@end

Remove a device from a mesh group over Bluetooth

API description

- (void)deleteDeviceToGroupWithDevId:(NSString *)devId groupAddress:(uint32_t)groupAddress;

Parameters

Parameter Description
devId The device ID.
groupAddress The address of the group.

Callback for ThingSmartSIGMeshManagerDelegate

- (void)sigMeshManager:(ThingSmartSIGMeshManager *)manager
didHandleGroupWithGroupAddress:(nonnull NSString *)groupAddress
		  deviceNodeId:(nonnull NSString *)nodeId
			 error:(NSError *)error;

Parameters

Parameter Description
manager The information about the manager.
groupAddress The hexadecimal mesh address of the group.
nodeId The hexadecimal mesh node address of the device.
error The failure callback.

Remove a device from a mesh group through a gateway

API description

Removes a sub-device from a mesh group through a gateway by using ThingSmartBleMeshGroup. In this case, the sub-device must belong to the Bluetooth mesh gateway.

- (void)removeSubDeviceWithSubList:(NSArray<ThingSmartDeviceModel *> * _Nonnull )subList success:(nullable ThingSuccessHandler)success failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
subList The sub-device of the gateway to be managed.
success The success callback.
failure The failure callback.

Callback for ThingSmartBleMeshGroupDelegate


// The callback for ThingSmartBleMeshGroupDelegate.
@protocol ThingSmartBleMeshGroupDelegate <NSObject>

/// The response of removing a Bluetooth sub-device from a mesh group through a gateway.
///Either of the following error messages might be returned:<ul><li>`1`: The maximum number of scenes allowed is exceeded.</li><li>`2`: The sub-device timeout error has occurred.</li><li>`3`: The specified parameter value is out of the valid range.<ul><li>`4`: An error has occurred while writing to files.</li><li>`5`: Other errors have occurred while processing your request.</li></ul>
/// Group Response of Zigbee Devices removing Gateway
/// 1: Over the Scenario Limit 2: Subdevice Timeout 3: Setting Value Out of Range 4: Write File Error 5: Other Errors
- (void)meshGroup:(ThingSmartBleMeshGroup *)group removeResponseCode:(NSArray <NSNumber *> *)responseCode;

@end

Synchronize the group operation result to the cloud

Class name Description
ThingSmartBleMeshGroup The group class.

API description

Synchronizes group device changes to the cloud after a delegate method returns the result that a device is added or deleted. The group instance is used to synchronize the data.

// A device is added.
- (void)addDeviceWithDeviceId:(NSString *)deviceId success:(ThingSuccessHandler)success failure:(ThingFailureError)failure;

// A device is removed.
- (void)removeDeviceWithDeviceId:(NSString *)deviceId success:(ThingSuccessHandler)success failure:(ThingFailureError)failure;

Query group devices

API description

Returns devices in a group with a specified group address. The following method of ThingSmartSIGMeshManager and the callback supported by the firmware are used to implement this feature.

- (void)queryGroupMemberWithGroupAddress:(uint32_t)groupAddress;

// The callback.
- (void)sigMeshManager:(ThingSmartSIGMeshManager *)manager
	  queryDeviceModel:(ThingSmartDeviceModel *)deviceModel
		  groupAddress:(uint32_t)groupAddress;

Parameters

Parameter Description
groupAddress The address of the group.

Control

Smart devices are managed with DPs. Bluetooth mesh devices are also controlled by device DPs.

Format of DPs

DPs are sent to control devices in the following format: {"(dpId)" : "(dpValue)"}. Example: @{@"101" : @"44"}. For more information about DPs, see Device Control.

Thing has simplified the process of sending DPs. You do not need to check whether devices are connected using a gateway or not. DPs can be sent as long as devices run online.

Send DPs to control a device

API description

  // ThingSmartDevice
  - (void)publishDps:(NSDictionary *)dps
			 success:(nullable ThingSuccessHandler)success
			 failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
dps The DPs in the dictionary format.
success The success callback.
failure The failure callback.

Send DPs to control a group

API description

// ThingSmartBleMeshGroup
- (void)publishDps:(NSDictionary *)dps success:(nullable ThingSuccessHandler)success failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
dps The DPs in the dictionary format.
success The success callback.
failure The failure callback.

Update

Starting from v3.35.5, device firmware update is optimized and simplified. For more information, see Firmware Updates.

Get firmware update information

API description

//Returns update information by using the ThingSmartDevice instance.
- (void)getFirmwareUpgradeInfo:(void (^)(NSArray <ThingSmartFirmwareUpgradeModel *> *upgradeModelList))success failure:(ThingFailureError)failure;

/*
The update information is returned in the response. You can check the `type` field to determine whether an update is required. Valid values:
	 `0`: updating
	 `1`: no update available
	 `2`: forced update or update notification
	 `3`: check for updates

// If an update is required, the firmware address is included in the response. The firmware can be downloaded and converted into firmware data for subsequent operations.
*/

Parameters

Parameter Description
success The success callback.
failure The failure callback.

Bluetooth Low Energy (LE) mesh devices must be woken up before the update. The wake-up method varies depending on different devices.

Check online status of a sub-device

Sub-devices are updated over Bluetooth, so their online status must be checked. Make sure they are locally connected before the update.

BOOL isBLEOnline = device.deviceModel.isMeshBleOnline;

Specify target sub-device

Specifies only one sub-device for each update.

[ThingSmartSIGMeshManager sharedInstance].delegate = self;
[[ThingSmartSIGMeshManager sharedInstance] prepareForOTAWithTargetNodeId:self.device.deviceModel.nodeId];

Callback for connected target device

// ThingSmartSIGMeshManagerDelegate

- (void)notifySIGLoginSuccess {
	[ThingSmartSIGMeshManager sharedInstance].delegate = nil;
	//weakify(self);
	[[ThingSmartSIGMeshManager sharedInstance] startSendOTAPack:_otaData targetVersion:_upgradeModel.version success:^{
		//strongify(self);
	    // The target version number.
		[self updateVersion];
	} failure:^{
		// log error
	}];
}

Updates device version number

- (void)updateVersion {
	[self.device updateDeviceVersion:_upgradeModel.version type:_upgradeModel.type success:^{
		// ota success
	} failure:^(NSError *error) {
		// log error
	}];
}

Update mesh gateway firmware

Updates a Bluetooth mesh gateway in a similar way that a common device is updated. For more information, see Firmware Updates.