Group Management

Last Updated on : 2024-01-30 05:38:53download

Group devices with the same features and control them all in one go. This topic describes how to implement the basic features of group control.

User interface

This section describes how to implement a simple UI. The isGroup field determines whether the device or group is displayed on this UI. The home data is refreshed in viewDidLoad, and then the UI will be updated.

Implement the home delegate method. A home event will trigger a UI refresh. Tapping the cell will invoke handle(device:) or handle(group:).

class DeviceListVC: UITableViewController {

    var home: ThingSmartHome
    var isGroup: Bool = false

    init(home: ThingSmartHome, isGroup: Bool = false) {
        self.home = home
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DeviceDetailListViewControllerReuseIdentifier")
        home.delegate = self
        loadData()
    }


    private func loadData() {
        home.getDataWithSuccess({ (model) in
            self.tableView.reloadData()
        }, failure: { [weak self] (error) in
            guard let self = self else { return }
            let errorMessage = error?.localizedDescription ?? ""
            Alert.showBasicAlert(on: self, with: NSLocalizedString("Failed to Fetch Home", comment: ""), message: errorMessage)
        })
    }


    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.isGroup ? self.home.groupList.count : self.home.deviceList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .value1, reuseIdentifier: "DeviceDetailListViewControllerReuseIdentifier")

        let title = self.isGroup ? self.home.groupList[indexPath.row].name : self.home.deviceList[indexPath.row].name
        cell.textLabel?.text = title

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if (self.isGroup) {
            handle(group: self.home.groupList[indexPath.row])
        }else{
            handle(device: self.home.deviceList[indexPath.row])
        }
    }

    func handle(device: ThingSmartDeviceModel) {}
    func handle(group: ThingSmartGroupModel) {}
}

extension DeviceListVC: ThingSmartHomeDelegate {
    func homeDidUpdateInfo(_ home: ThingSmartHome!) {
        tableView.reloadData()
    }

    func home(_ home: ThingSmartHome!, didAddDeivice device: ThingSmartDeviceModel!) {
        tableView.reloadData()
    }

    func home(_ home: ThingSmartHome!, didRemoveDeivice devId: String!) {
        tableView.reloadData()
    }

    func home(_ home: ThingSmartHome!, deviceInfoUpdate device: ThingSmartDeviceModel!) {
        tableView.reloadData()
    }

    func home(_ home: ThingSmartHome!, device: ThingSmartDeviceModel!, dpsUpdate dps: [AnyHashable : Any]!) {
        tableView.reloadData()
    }
}

Create a group

When isGroup is false, devices are displayed. A group can be created when the cell is tapped.

  1. Get the group type through ThingGroupMakerHelper.groupBizType(fromDeviceId:).

  2. Build the parameters based on the group type. If the device is a Bluetooth mesh, Bluetooth beacon, or Tuya proprietary mesh, the current list of devices in the home should be included as a parameter.

  3. Create a service for adding a group.

  4. Get the list of eligible devices.

  5. Create a group.

    class DeviceListVC: UITableViewController {
    
        var addGroupService: ThingGroupServiceProtocol?
    
        func handle(device: ThingSmartDeviceModel) {
            // Query group type by device ID.
            let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: device.devId)
    
            // Construct parameters based on group type.
            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
            }
    
            // Create service.
            self.addGroupService = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)
    
    
            SVProgressHUD.show()
            // Get the list of eligible devices.
            self.addGroupService?.fetchDeviceList?(success: { list in
    
                guard let listIds = list?.compactMap({ return $0.devId }) else {
                    SVProgressHUD.dismiss()
                    return
                }
    
                // Create a group.
                self.addGroupService?.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
            })
        }
    }
    

Update a group

When isGroup is true, groups are displayed. A group can be updated when the cell is tapped. Display and handle events using actionSheet.

  1. Get the group type through ThingGroupMakerHelper.groupBizType(fromDeviceId:).

  2. Build the parameters based on the group type. If the device is a Bluetooth mesh, Bluetooth beacon, or Tuya proprietary mesh, the current list of devices in the home should be included as a parameter.

  3. Create a service for updating a group.

  4. Get the list of eligible devices.

  5. Update a group.

    class DeviceListVC: UITableViewController {
    
        func handle(group: ThingSmartGroupModel) {
            let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
            alert.addAction(UIAlertAction(title: "Edit Group", style: .default, handler: { action in
                self.editGroup(with: group)
            }))
    
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            self.present(alert, animated: true)
        }
    
        var editService: ThingGroupServiceProtocol?
        func editGroup(with group: ThingSmartGroupModel) {
            // Query group type by group ID.
            let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: group.groupId)
    
            // Construct parameters based on group type.
            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
            }
    
    
            // Create service.
            self.editService = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)
    
            SVProgressHUD.show()
            // Get the list of eligible devices.
            self.editService?.fetchDeviceList?(success: { list in
    
                guard let listIds = list?.compactMap({ return $0.devId }) else {
                    SVProgressHUD.dismiss()
                    return
                }
    
    
                // Update the devices in the group.
                self.editService?.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

When isGroup is true, groups are displayed. A group can be deleted when the cell is tapped. Display and handle events using actionSheet.

  1. Get the group type through ThingGroupMakerHelper.groupBizType(fromDeviceId:).

  2. Build the parameters based on the group type. If the device is a Bluetooth mesh, Bluetooth beacon, or Tuya proprietary mesh, the current list of devices in the home should be included as a parameter.

  3. Create a service for deleting a group.

  4. Delete a group.

    class DeviceListVC: UITableViewController {
    
        func handle(group: ThingSmartGroupModel) {
            let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
            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)
            }))
    
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
            self.present(alert, animated: true)
    
        }
    
        var deleteService: ThingGroupServiceProtocol?
    
        func deleteGroup(with group: ThingSmartGroupModel) {
            // Query group type by group ID.
            let groupType = ThingGroupMakerHelper.groupBizType(fromDeviceId: group.groupId)
    
            // Construct parameters based on group type.
            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
            }
    
    
            // Create service.
            self.deleteService = ThingGroupServiceMaker.groupServiceMaker(withBuildQuery: params)
    
            // Delete a group.
            SVProgressHUD.show()
            self.deleteService?.removeGroup?(withGroupId: group.groupId, success: {
                SVProgressHUD.dismiss()
                self.tableView.reloadData()
                return
            }, failure: { e in
                SVProgressHUD.dismiss()
                return
            })
        }
    
    }