Group Management

Last Updated on : 2023-04-13 09:33:01download

A device group includes devices of the same type and gathers a series of devices. 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.

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