Group Management

Last Updated on : 2024-08-22 06:47:34download

Group devices with the same features and control them all in one go. Both the group and scene can enable control of multiple devices at once, but they have different restrictions on actions. Scenes offer flexible and diverse actions on devices, whereas groups only support actions on features that are common to all devices in the group. Wi-Fi and Zigbee devices can be grouped in most cases.

Tuya provides the capabilities to implement device group management. For example, create, rename, manage, or dismiss a group, and manage multiple devices in the same group.

Feature description

The ThingSmartGroup class requires the group ID specified by groupId to implement initialization. An incorrect group ID might cause failed initialization. In this case, the instance returns nil.

  • Encapsulation class

    Class name Description
    ThingSmartGroup The group class.
    ThingSmartGroupModel The group data model class.
  • Data model of ThingSmartGroupModel

    Field Type Description
    groupId NSString The unique group ID.
    productId NSString The product ID (PID) of a group.
    time long long The time when the group was created.
    name NSString The name of the group.
    iconUrl NSString The URL of the group icon.
    type ThingSmartGroupType The type of group.
    isShare BOOL Indicates whether the group is a shared group.
    dps NSDictionary The data points (DPs) of devices in the group.
    dpCodes NSDictionary The DPs of the group devices, stored in the key-value pair format.
    localKey NSString The key that the group uses for communication.
    deviceNum NSInteger The number of devices managed in the group.
    productInfo NSDictionary The PID information of the group.
    pv NSString The protocol version of the group. A Wi-Fi protocol version is supported.
    homeId long long The ID of the home to which the group belongs.
    roomId long long The ID of the room to which the group belongs.
    displayOrder NSInteger The sequence in which the group is sorted by room.
    homeDisplayOrder NSInteger The sequence in which the group is sorted by home.
    deviceList NSArray The list of group devices.
    localId NSString The group ID used on a local area network (LAN).
    meshId NSString The mesh ID of the group.
    schemaArray NSArray The schema array of group DP rules.
    standard BOOL Indicates whether a standard group is used.

Group Management

Get the group type

API description

Get the type of the group.

@interface ThingGroupMakerHelper : NSObject

/// Return ThingGroupBizType based on device ID
+ (ThingGroupBizType)groupBizTypeFromDeviceId:(NSString *)devId;

/// Return ThingGroupBizType based on group ID
+ (ThingGroupBizType)groupBizTypeFromGroupId:(NSString *)groupId;

@end

Parameter description

Property Type Description
devId NSString The device ID, by which the type of the group is retrieved.
groupId NSString The group ID, by which the type of the group is retrieved.

Description of return values

Property Description
ThingGroupBizType
  • ThingGroupBizTypeWi-Fi: Wi-Fi group
  • ThingGroupBizTypeStandardWi-Fi: Standard Wi-Fi group
  • ThingGroupBizTypeZigbee: Zigbee group
  • ThingGroupBizTypeStandardSIGMesh: Standard Bluetooth mesh group
  • ThingGroupBizTypeBeacon: Beacon group
  • ThingGroupBizTypeStandardZigbee: Standard Zigbee group
  • ThingGroupBizTypeThread: Thread group

Example

let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: device.devId)

Get the group service

API description

Get the specified group service.

@interface ThingGroupServiceMaker : NSObject
+ (id<ThingGroupServiceProtocol>)groupServiceMakerWithBuildQuery:(NSDictionary *)params;
@end

Parameter description

Property Type Description
params NSDictionary
  • devId: Device ID, required when you get the group service by device.
  • groupId: Group ID, required when you get the group service by group.
  • deviceList: The device list, required when the group type is Bluetooth mesh or bacon. For more information, see ThingSmartDeviceModel.

Description of return values

Data Description
id<ThingGroupServiceProtocol> The object of a group service.

Example

let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: device.devId)

var params: [AnyHashable: AnyObject] = [:]
params["devId"] = device.devId! as AnyObject

if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
    let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
    let deviceList = impl?.deviceListForCurrentSpace() ?? []
    params["deviceList"] = deviceList as AnyObject
}

self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

Get the device list

API description

Get the list of devices that match the group type.

- (void)fetchDeviceListWithSuccess:(ThingGroupDevListResult)result failure:(void(^)(NSError *error))failure;

Parameter description

Property Type Description
result None The success callback. For more information, see ThingSmartGroupDevListModel.
failure None The failure callback.

Description of ThingSmartGroupDevListModel

Data Type Description
devId NSString The device ID.
gwId NSString The gateway ID.
online BOOL Indicates whether the device is online.
iconUrl NSString The URL of the device icon.
productId NSString The product ID (PID) of the device.
checked BOOL Indicates whether the device is selected.
name NSString The name of the device.
nodeId NSString The node ID of the device.

Example

let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: device.devId)

var params: [AnyHashable: AnyObject] = [:]
params["devId"] = device.devId! as AnyObject

if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
    let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
    let deviceList = impl?.deviceListForCurrentSpace() ?? []
    params["deviceList"] = deviceList as AnyObject
}

self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

self.service?.fetchDeviceList?(success: { list in

}, failure: { e in

})

Create a group

API description

Create a group.

- (void)createGroupWithName:(NSString *)name
                 deviceList:(NSArray <NSString *> *)deviceList
                    process:(ThingGroupProcess)process
                    success:(ThingGroupSuccess)result
                    failure:(ThingGroupResultFailure)failure;

Parameter description

Property Type Description
name NSString The success callback. For more information, see ThingSmartGroupDevListModel.
deviceList NSArray <NSString *> The list of device IDs to be added to the group.
process NSDictionary<NSString *,NSNumber *> The progress.
result None The success callback with a group ID returned.
failure None The failure callback with an error code per failed device.

Example

SVProgressHUD.show()

self.service?.fetchDeviceList?(success: { list in
    guard let listIds = list?.compactMap({ return $0.devId }) else {
        SVProgressHUD.dismiss()
        return
    }

    self.service?.createGroup?(withName: "My group Name", deviceList: listIds, process: { process in

    }, success: { groupId in
        SVProgressHUD.dismiss()
        return
    }, failure: { e in
        SVProgressHUD.dismiss()
        return
    })

}, failure: { e in
    SVProgressHUD.dismiss()
    return
})

Edit a group

API description

Edit a group.

- (void)updateGroupWithDeviceList:(NSArray <NSString *> *)deviceList
                             process:(ThingGroupProcess)process
                             success:(ThingGroupSuccess)result
                          failure:(ThingGroupResultFailure)failure;

Parameter description

Property Type Description
deviceList NSArray <NSString *> The list of device IDs to be added to the group.
process NSDictionary<NSString *,NSNumber *> The progress.
result None The success callback with a group ID returned.
failure None The failure callback with an error code per failed device.

Example

func editGroup(with group: ThingSmartGroupModel) {
    let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: group.groupId)

    var params: [AnyHashable: AnyObject] = [:]
    params["groupId"] = group.groupId! as AnyObject

    if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
        let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
        let deviceList = impl?.deviceListForCurrentSpace() ?? []
        params["deviceList"] = deviceList as AnyObject
    }


    self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

    SVProgressHUD.show()
    self.service?.fetchDeviceList?(success: { list in

        guard let listIds = list?.compactMap({ return $0.devId }) else {
            SVProgressHUD.dismiss()
            return
        }

        self.service?.updateGroup?(withDeviceList: listIds, process: { process in

        }, success: { groupId in
            SVProgressHUD.dismiss()
            return
        }, failure: { e in
            SVProgressHUD.dismiss()
            return
        })

    }, failure: { e in
        SVProgressHUD.dismiss()
        return
    })
}

Delete a group

API description

Delete a group.

- (void)removeGroupWithGroupId:(NSString *)groupId
                       success:(void (^)(void))success
                       failure:(void (^)(NSError *error))failure;

Parameter description

Property Type Description
groupId NSString The ID of the group to delete.
success None The success callback.
failure None The failure callback.

Example

func deleteGroup(with group: ThingSmartGroupModel) {
    let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: group.groupId)
    var params: [AnyHashable: AnyObject] = [:]
    params["groupId"] = group.groupId! as AnyObject

    if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
        let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
        let deviceList = impl?.deviceListForCurrentSpace() ?? []
        params["deviceList"] = deviceList as AnyObject
    }

    self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

    SVProgressHUD.show()
    self.service?.removeGroup?(withGroupId: group.groupId, success: {
        SVProgressHUD.dismiss()
        self.tableView.reloadData()
        return
    }, failure: { e in
        SVProgressHUD.dismiss()
        return
    })
}

More functions

Please refer to Group Management.

Example

import UIKit
import ThingSmartBizCore
import ThingModuleServices
import SVProgressHUD
import ThingSmartDeviceKit
import ThingDeviceDetailKit
import ThingGroupManagerKit
import ThingGroupHandleSktAPI

class DeviceDetailKitVC: DeviceListBaseVC {

    override func handle(index: Int) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        if (self.isGroup) {
            if (index >= home.groupList.count) {return}
            let group = self.home.groupList[index]

            alert.addAction(UIAlertAction(title: "Timer", style: .default, handler: { action in
                let vc = DeviceDetailKitTimerVC(bizId: group.groupId, isGroup: true)
                self.navigationController?.pushViewController(vc, animated: true)
            }))

            alert.addAction(UIAlertAction(title: "Edit Group", style: .default, handler: { action in
                self.editGroup(with: group)
            }))

            alert.addAction(UIAlertAction(title: "Delete Group", style: .default, handler: { action in
                self.deleteGroup(with: group)
            }))

        }else{
            if (index >= home.deviceList.count) {return}
            let device = self.home.deviceList[index]

            alert.addAction(UIAlertAction(title: "Device Info", style: .default, handler: { action in
                let vc = DeviceDetailKitInfoVC(deviceId: device.devId)
                self.navigationController?.pushViewController(vc, animated: true)
            }))

            alert.addAction(UIAlertAction(title: "Timer", style: .default, handler: { action in
                let vc = DeviceDetailKitTimerVC(bizId: device.devId, isGroup: false)
                self.navigationController?.pushViewController(vc, animated: true)
            }))

            alert.addAction(UIAlertAction(title: "Create Group", style: .default, handler: { action in
                self.createGroup(with: device)
            }))

        }

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        self.present(alert, animated: true)
    }

    var service: ThingGroupServiceProtocol?
    func createGroup(with device: ThingSmartDeviceModel) {
        let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: device.devId)

        var params: [AnyHashable: AnyObject] = [:]
        params["devId"] = device.devId! as AnyObject

        if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
            let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
            let deviceList = impl?.deviceListForCurrentSpace() ?? []
            params["deviceList"] = deviceList as AnyObject
        }

        self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

        SVProgressHUD.show()
        self.service?.fetchDeviceList?(success: { list in

            guard let listIds = list?.compactMap({ return $0.devId }) else {
                SVProgressHUD.dismiss()
                return
            }

            self.service?.createGroup?(withName: "My group Name", deviceList: listIds, process: { process in

            }, success: { groupId in
                SVProgressHUD.dismiss()
                return
            }, failure: { e in
                SVProgressHUD.dismiss()
                return
            })

        }, failure: { e in
            SVProgressHUD.dismiss()
            return
        })
    }

    func editGroup(with group: ThingSmartGroupModel) {
        let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: group.groupId)

        var params: [AnyHashable: AnyObject] = [:]
        params["groupId"] = group.groupId! as AnyObject

        if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
            let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
            let deviceList = impl?.deviceListForCurrentSpace() ?? []
            params["deviceList"] = deviceList as AnyObject
        }

        self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

        SVProgressHUD.show()
        self.service?.fetchDeviceList?(success: { list in

            guard let listIds = list?.compactMap({ return $0.devId }) else {
                SVProgressHUD.dismiss()
                return
            }

            self.service?.updateGroup?(withDeviceList: listIds, process: { process in

            }, success: { groupId in
                SVProgressHUD.dismiss()
                return
            }, failure: { e in
                SVProgressHUD.dismiss()
                return
            })

        }, failure: { e in
            SVProgressHUD.dismiss()
            return
        })
    }

    func deleteGroup(with group: ThingSmartGroupModel) {
        let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: group.groupId)

        var params: [AnyHashable: AnyObject] = [:]
        params["groupId"] = group.groupId! as AnyObject

        if (groupType == .bleMesh || groupType == .sigMesh || groupType == .beacon) {
            let impl = ThingSmartBizCore.sharedInstance().service(of: ThingBusinessGroupProtocol.self) as? ThingBusinessGroupProtocol
            let deviceList = impl?.deviceListForCurrentSpace() ?? []
            params["deviceList"] = deviceList as AnyObject
        }

        self.service = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)

        SVProgressHUD.show()
        self.service?.removeGroup?(withGroupId: group.groupId, success: {
            SVProgressHUD.dismiss()
            self.tableView.reloadData()
            return
        }, failure: { e in
            SVProgressHUD.dismiss()
            return
        })
    }

}

Create a Wi-Fi group

Query devices available to create a group

Returns a list of devices that can be used to create a group together with a device specified by the product ID (PID) of the device.

+ (void)getDevList:(NSString *)productId
            homeId:(long long)homeId
           success:(nullable void(^)(NSArray <ThingSmartGroupDevListModel *> *list))success
           failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
productId The PID of the device from which the target group can be accessed.
homeId The ID of the home to which the group belongs.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)getGroupDevList {

    [ThingSmartGroup getDevList:@"your_group_product_id" homeId:homeId success:^(NSArray<ThingSmartGroupDevListModel *> *list) {
        NSLog(@"get group dev list success %@:", list);
    } failure:^(NSError *error) {
        NSLog(@"get group dev list failure");
    }];
}

Swift:

func getGroupDevList() {
    ThingSmartGroup.getDevList("your_group_product_id", homeId:homeId, success: { (list) in
        print("get group dev list success \(list)")
    }) { (error) in
        print("get group dev list failure")
    }
}

Query devices available to join a group

Returns a list of devices that can be added or that have been added to a group specified by the PID of the group.

- (void)getDevList:(NSString *)productId
           success:(nullable void(^)(NSArray <ThingSmartGroupDevListModel *> *list))success
           failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
productId The PID of the group.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)getGroupDevList {
//    self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];
    [self.smartGroup getDevList:@"your_group_product_id" success:^(NSArray<ThingSmartGroupDevListModel *> *list) {
        NSLog(@"get group dev list success %@:", list);
    } failure:^(NSError *error) {
        NSLog(@"get group dev list failure");
    }];
}

Swift:

func getGroupDevList() {
    smartGroup?.getDevList("your_group_product_id", success: { (list) in
        print("get group dev list success \(list)")
    }, failure: { (error) in
        print("get group dev list failure")
    })
}

Create a group

+ (void)createGroupWithName:(NSString *)name
                  productId:(NSString *)productId
                     homeId:(long long)homeId
                  devIdList:(NSArray<NSString *> *)devIdList
                    success:(nullable void (^)(ThingSmartGroup *group))success
                    failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
name The name of the group.
productId The PID of the devices used to create a group.
homeId The home ID.
devIdList The list of device IDs used to create a group.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)createNewGroup {
    [ThingSmartGroup createGroupWithName:@"your_group_name" productId:@"your_group_product_id" homeId:homeId devIdList:(NSArray<NSString *> *)selectedDevIdList success:^(ThingSmartGroup *group) {
        NSLog(@"create new group success %@:", group);
    } failure:^(NSError *error) {
        NSLog(@"create new group failure");
    }];
}

Swift:

func createNewGroup() {
    ThingSmartGroup.createGroup(withName: "your_group_name", productId: "your_group_product_id", homeId: homeId, devIdList: ["selectedDevIdList"], success: { (group) in
        print("create new group success: \(group)")
    }) { (error) in
        print("create new group failure")
    }
}

Update and save a group relationship

- (void)updateGroupRelations:(NSArray <NSString *>*)devList
                     success:(nullable ThingSuccessHandler)success
                     failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
devList The list of device IDs in the group.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)updateGroupRelations {
//    self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];

    [self.smartGroup updateGroupRelations:(NSArray<NSString *> *)selectedDevIdList success:^ {
        NSLog(@"update group relations success");
    } failure:^(NSError *error) {
        NSLog(@"update group relations failure: %@", error);
    }];
}

Swift:

func updateGroupRelations() {
    smartGroup?.updateRelations(["selectedDevIdList"], success: {
        print("update group relations success")
    }, failure: { (error) in
        if let e = error {
            print("update group relations failure: \(e)")
        }
    })
}

Execute callback

Returns the data update result after group DPs are sent.

Objective-C:

#pragma mark - ThingSmartGroupDelegate

- (void)group:(ThingSmartGroup *)group dpsUpdate:(NSDictionary *)dps {
    // Refreshes the panel UI after a group operation.
}

Swift:

// MARK: ThingSmartGroupDelegate
func group(_ group: ThingSmartGroup!, dpsUpdate dps: [AnyHashable : Any]!) {
    // Refreshes the panel UI after a group operation.
}

Create a Zigbee group

Group Management

A Zigbee group supports Zigbee sub-devices, Smart Gateway Pro sub-devices, Sub-G sub-devices, and other devices that can communicate over Zigbee.

Query devices available to create or join a group

+ (void)getDevListWithProductId:(NSString *)productId
                           gwId:(NSString *)gwId
                         homeId:(long long)homeId
                        success:(nullable void (^)(NSArray<ThingSmartGroupDevListModel *> *))success
                        failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
productId The PID of the group.
gwId The gateway ID of the group.
homeId The home ID.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)getGroupDevList {

    // For example, query the available sub-devices that can be used to create a group with the current Zigbee sub-device.
    ThingSmartDevice *oneSubDevice = [ThingSmartDevice deviceWithDeviceId:@"sub device id"];
    NSString *productId = oneSubDevice.deviceModel.productId;
    NSString *gwId = oneSubDevice.deviceModel.parentId;

    [ThingSmartGroup getDevListWithProductId:productId gwId:gwId homeId:homeId success:^(NSArray<ThingSmartGroupDevListModel *> *list) {
        NSLog(@"get group dev list success %@:", list);
    } failure:^(NSError *error) {
        NSLog(@"get group dev list failure");
    }];
}

Swift:

func getGroupDevList() {
    // For example, query the available sub-devices that can be used to create a group with the current Zigbee sub-device.
    guard let oneSubDevice = ThingSmartDevice(deviceId: "sub device id"),
          let productId = oneSubDevice.deviceModel.productId,
          let gwId = oneSubDevice.deviceModel.parentId
    else { return }

    ThingSmartGroup.getDevList(withProductId: productId, gwId: gwId, homeId: hoemId, success: { (list) in
        print("get group dev list success \(list)")
    }) { (error) in
        print("get group dev list failure")
    }
}

Create a group

+ (void)createGroupWithName:(NSString *)name
                     homeId:(long long)homeId
                       gwId:(NSString *)gwId
                  productId:(NSString *)productId
                    success:(nullable void (^)(ThingSmartGroup *))success
                    failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
name The name of the group.
homeId The ID of the home to which the group belongs.
gwId The gateway ID of the group.
productId The PID of the device from which the target group can be accessed.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)createNewGroup {

    [ThingSmartGroup createGroupWithName:@"your_group_name" homeId:homeID gwId:@"gwId" productId:@"your_group_product_id" success:^(ThingSmartGroup *group) {
        NSLog(@"create new group success %@:", group);
    } failure:^(NSError *error) {
        NSLog(@"create new group failure");
    }];
}

Swift:

func createNewGroup() {
    ThingSmartGroup.createGroup(withName: "your_group_name", homeId: homeId, gwId: "gwId" productId: "your_group_product_id", success: { (group) in
        print("create new group success: \(group)")
    }) { (error) in
        print("create new group failure")
    }
}

Add devices to a group

API description

Adds one or more devices to a group. In this interaction, the node IDs of the new devices are written to the gateway firmware of the group.

- (void)addZigbeeDeviceWithNodeList:(NSArray <NSString *>*)nodeList
                            success:(nullable ThingSuccessHandler)success
                            failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
nodeList The list of the target node IDs.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)addDevice {
    // The value of nodeId can be obtained from ThingSmartDeviceModel::nodeId.
    // self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];

    [self.smartGroup addZigbeeDeviceWithNodeList:@[@"nodeId1", @"nodeId2"] success:^() {
        NSLog(@"send add device msg success");
        // Listen for -group:addResponseCode: to get the actual operation result.
    // After receiving the callback, call -updateGroupRelations:success:failure: at the right time to update the relationship.
    } failure:^(NSError *error) {
        NSLog(@"send add device msg failure");
    }];
}

Swift:

func addDevice() {
    // The value of nodeId can be obtained from ThingSmartDeviceModel::nodeId.

    smartGroup?.addZigbeeDevice(withNodeList: ["nodeId1", "nodeId2"], success: {
        print("send add device msg success")
        // Listen for group(_, addResponseCode) to get the actual operation result.
    // After receiving the callback, call updateGroupRelations(_, success, failure) at the right time to update the relationship.
    }) { (error) in
        print("send add device msg failure")
    }
}

Remove devices from a group

API description

Removes one or more devices from a group through a gateway.

- (void)removeZigbeeDeviceWithNodeList:(NSArray <NSString *>*)nodeList
                               success:(nullable ThingSuccessHandler)success
                               failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
nodeList The list of the target node IDs.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)removeDevice {
  // Call ThingSmartGroup::groupModel.deviceList to get a list of devices in the group.
  // The value of nodeId can be obtained from ThingSmartDeviceModel::nodeId.
  [self.smartGroup removeZigbeeDeviceWithNodeList:@[@"nodeId1", @"nodeId2"] success:^() {
        NSLog(@"send remove device msg success");
        // Listen for -group:removeResponseCode: to get the actual operation result.
        // After receiving the callback, call -updateGroupRelations:success:failure: at the right time to update the relationship.
  } failure:^(NSError *error) {
        NSLog(@"send remove device msg failure");
    }];
}

Swift:

func removeDevice() {
    // Call ThingSmartGroup::groupModel.deviceList to get a list of devices in the group.
    // The value of nodeId can be obtained from ThingSmartDeviceModel::nodeId.
    
    smartGroup?.addZigbeeDevice(withNodeList: ["nodeId1", "nodeId2"], success: {
        print("send remove device msg success")
        // Listen for group(_, removeResponseCode) to get the actual operation result.
    // After receiving the callback, call updateGroupRelations(_, success, failure) at the right time to update the relationship.
    }) { (error) in
        print("send remove device msg failure")
    }
}

Invoke callback

Returns the result after Zigbee devices are added to or removed from a group through a gateway. When the responseCode in the callback is 0, the operation is successful. Other values indicate a failure. The following table lists the detailed definitions:

responseCode Description
0 A device was added or removed successfully.
1 The number of groups exceeded the upper limit.
2 A timeout error occurred while processing sub-devices.
3 The specified value was out of range.
4 An error occurred while writing to files.
5 Other errors occurred while processing your request.

The responseCode in the callback is an array of response results, which is consistent with the order of the devices passed in when adding or removing. Example:

  1. Add or remove a device:
    • The request parameters: nodeList=[a, b, c]
    • The response parameters: responseCode=[0, 1, 0]
  2. Operation result:
    • Device a was added or removed successfully.
    • Device b was added or removed successfully.
    • Device c was added or removed successfully.

Objective-C:

#pragma mark - ThingSmartGroupDelegate

- (void)group:(ThingSmartGroup *)group addResponseCode:(NSArray <NSNumber *>*)responseCode {
    // Returns the result after Zigbee devices are added to a group through a gateway.
}

- (void)group:(ThingSmartGroup *)group removeResponseCode:(NSArray <NSNumber *>*)responseCode {
    // Returns the result after Zigbee devices are removed from a group through a gateway.
}

Swift:

// MARK: ThingSmartGroupDelegate
func group(_ group: ThingSmartGroup?, addResponseCode responseCode: [NSNumber]?) {
    // Returns the result after Zigbee devices are added to a group through a gateway.
}

func group(_ group: ThingSmartGroup?, removeResponseCode responseCode: [NSNumber]?) {
    // Returns the result after Zigbee devices are removed from a group through a gateway.
}

Update and save a group relationship

After devices are added or removed and the response callback is received, depending on the result of the response callback, this API method can be called at an appropriate time to update and save the group device relationship.

Example

There are devices [a, b, and c] in the original group:

  • Users operate on the UI:
    1. Add [e, f]
    2. Remove [a, b]
    3. Save the group
  • Procedure to develop an app:
    1. Call the API method to add devices to and remove devices from the group.

    2. A callback for adding devices is received.

      • responseCode [0, 1] indicates that device e was added successfully and the adding of device f failed.
      • responseCode [1, 0] indicates that the removal of device a failed and device b was removed successfully.
    3. Finally, the device list in this group is [a, c, e]. Call the API method of updating and saving the group relationship, and pass devList = [a, c, e].

      The API method of updating and saving the group relationship passes devId, rather than nodeId.

API description

- (void)updateGroupRelations:(NSArray <NSString *>*)devList
                     success:(nullable ThingSuccessHandler)success
                     failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
devList The list of device IDs in the group.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)updateGroupRelations {
    // self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];
    [self.smartGroup updateGroupRelations:@[@"deviceId 2", @"deviceId3", ....] success:^ {
        NSLog(@"update group relations success");
    } failure:^(NSError *error) {
        NSLog(@"update group relations failure: %@", error);
    }];
}

Swift:

func updateGroupRelations() {
    smartGroup?.updateRelations(["deviceId 2", "deviceId3", ....], success: {
        print("update group relations success")
    }, failure: { (error) in
        if let e = error {
            print("update group relations failure: \(e)")
        }
    })
}

Control groups

Initialize a group instance

Objective-C:

ThingSmartGroup *smartGroup = [ThingSmartGroup groupWithGroupId:groupId];

Swift:

let smartGroup = ThingSmartGroup(groupId: groupId);

Parameters

Parameter Description
groupId The group ID.

Rename a group

- (void)updateGroupName:(NSString *)name
                success:(nullable ThingSuccessHandler)success
                failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
name The name of the group.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)updateGroupName {
// self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];

    [self.smartGroup updateGroupName:@"your_group_name" success:^{
        NSLog(@"update group name success");
    } failure:^(NSError *error) {
        NSLog(@"update group name failure: %@", error);
    }];
}

Swift:

func updateGroupName() {
    smartGroup?.updateName("your_group_name", success: {
        print("updateGroupName success")
    }, failure: { (error) in
        if let e = error {
            print("updateGroupName failure: \(e)")
        }
    })
}

Dismiss a group

- (void)dismissGroup:(nullable ThingSuccessHandler)success failure:(nullable ThingFailureError)failure;

Parameters

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

Example

Objective-C:

- (void)dismissGroup {
// self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];

    [self.smartGroup dismissGroup:^{
      NSLog(@"dismiss group success");
    } failure:^(NSError *error) {
      NSLog(@"dismiss group failure: %@", error);
    }];
}

Swift:

func dismissGroup() {
    smartGroup?.dismiss({
        print("dismiss group success")
    }, failure: { (error) in
        if let e = error {
            print("dismiss group failure: \(e)")
        }
    })
}

Send group control commands

API description

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

Parameters

Parameter Description
dps The list of DPs to be sent for device control.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)publishDps {
//    self.smartGroup = [ThingSmartGroup groupWithGroupId:@"your_group_id"];

    NSDictionary *dps = @{@"1": @(YES)};
    [self.smartGroup publishDps:dps success:^{
        NSLog(@"publishDps success");
    } failure:^(NSError *error) {
        NSLog(@"publishDps failure: %@", error);
    }];
}

Swift:

func publishDps() {
    let dps = ["1" : true]
    smartGroup?.publishDps(dps, success: {
        print("publishDps success")
    }, failure: { (error) in
        print("publishDps failure")
    })
}

Execute callback

Returns the result of device control. The callback is triggered by ThingSmartHomeDelegate.

- (void)home:(ThingSmartHome *)home group:(ThingSmartGroupModel *)group dpsUpdate:(NSDictionary *)dps;

Example

Objective-C:

#pragma mark - ThingSmartHomeDelegate
- (void)home:(ThingSmartHome *)home group:(ThingSmartGroupModel *)group dpsUpdate:(NSDictionary *)dps {

}

Swift:

extension YourViewController: ThingSmartHomeDelegate {
    func home(_ home: ThingSmartHome!, group: ThingSmartGroupModel!, dpsUpdate dps: [AnyHashable : Any]!) {

    }
}

Query group list

Objective-C:

// Returns the details of a specified group.
ThingSmartGroupModel *smartGroupModel = [ThingSmartGroup groupWithGroupId:groupId].groupModel;

// Returns a list of devices in the group.
NSArray<ThingSmartDeviceModel *> *deviceList = [ThingSmartGroup groupWithGroupId:groupId].groupModel.deviceList;

Swift:

// Returns the details of a specified group.
let smartGroupModel = ThingSmartGroup(groupId: "groupId")?.groupModel

// Returns a list of devices in the group.
let deviceList = ThingSmartGroup(groupId: "groupId")?.groupModel.deviceList