Device Management (iOS)

Last Updated on : 2024-04-03 08:18:36download

The SDK supports operations to manage devices after they are paired. For example, listen for changes in device status, rename devices, update device firmware, remove devices, and restore default settings.

Before performing operations, make sure you have obtained the list of devices and groups in a home.

Functional description

  • The following table lists the classes for device management.

    Class name Description
    ThingSmartDevice Devices
    ThingSmartDeviceModel The device data model class.
  • The following table describes the data model specified by ThingSmartDeviceModel.

    Property Type Description
    devId NSString The unique ID of a device.
    name NSString The name of a device.
    iconUrl NSString The URL of a device icon.
    isOnline Boolean Indicates whether a device is online. The device is online when it is connected to a Wi-Fi network, a local area network (LAN), or a Bluetooth network.
    isCloudOnline Boolean Indicates whether a device is connected to a Wi-Fi network.
    isLocalOnline Boolean Indicates whether a device is connected to a LAN.
    isShare Boolean Indicates whether a device is a shared device.
    dps NSDictionary The data points (DPs) of a device.
    dpCodes NSDictionary The DPs in the code-value format.
    schemaArray NSArray The schema array of DP rules.
    productId NSString The product ID (PID) of a device.
    capability NSUInteger The product capability of a device.
    deviceType ThingSmartDevice
    ModelType
    The type of device.
    supportGroup Boolean Indicates whether groups can be created.
    gwType NSString A value of v indicates a virtual device, and an empty value indicates a real device for pairing.
    pv NSString The protocol version of a device. A Wi-Fi protocol version or a Bluetooth protocol version is supported.
    lpv NSString The LAN protocol version of a device. By default, this parameter is empty. The value is specified after the device is connected to a LAN.
    latitude NSString The latitude.
    longitude NSString The longitude.
    localKey NSString The key that a device uses for communication.
    uuid NSString The universally unique identifier (UUID) of a device.
    homeId LongLong The ID of the home that a device belongs to.
    roomId LongLong The ID of the room that a device belongs to.
    upgrading Boolean Indicates whether an update is in progress.
    timezoneId NSString The time zone of a device.
    nodeId NSString Each sub-device of a gateway is assigned a unique short URL. This parameter is empty for non-sub-devices.
    parentId NSString The ID of a parent device. This parameter is empty for non-sub-devices. Sub-devices search for the gateway ID based on this parameter. For Bluetooth mesh sub-devices, this parameter means the mesh ID or gateway ID.
    isMeshBleOnline Boolean Indicates whether a Bluetooth mesh device is connected to a LAN.
    devKey NSString The Bluetooth communication key for a standard Bluetooth mesh device.
    standard Boolean Indicates whether a device is a standard device. Standard DPs are available to control standard devices.
    standSchemaModel ThingSmartStand
    SchemaModel
    The schema array of standard DP rules.
    activeTime NSTimeInterval The time when a device is activated.
    homeDisplayOrder NSInteger The serial number of a device. When a list of devices is returned for a home, the devices can be sorted by this parameter.
    sharedTime LongLong The time when a device is shared.
    accessType NSInteger The method that is used to connect devices. Valid values:
    • 0: Tuya’s DP
    • 1: Matter
    • 2: TuyaLink
    thingModel ThingSmart
    ThingModel
    The things data model of the device. This parameter is required when accessType is set to 2.
    You can call - getThingModelWithSuccess:failure: or + getThingModelWithProductId:productVersion:success:failure: to get the things data model.
    category NSString The code of the device category. For example, dj indicates a light. For more information, see the List of category codes.

Initialize device

Initializes the device control class by device ID.

  • You must use ThingSmartHome to initialize a home instance and call getHomeDetailWithSuccess:failure: to get home details. The device is initialized only after home details are synchronized.

  • An incorrect device ID might cause failed initialization. In this case, the device instance returns nil.

API description

/**
* Returns the device instance. If the current user does not have the device, nil is returned.
*
* @param devId Device ID
* @return instance
*/
+ (nullable instancetype)deviceWithDeviceId:(NSString *)devId;

Parameters

Parameter Description
devId The device ID.

Sample code

ThingSmartDevice *device = [ThingSmartDevice deviceWithDeviceId:devId];
device.delegate = self;

Listen for a device delegate

After you implement the delegate protocol ThingSmartDeviceDelegate, you can process the callback of changes in device status and refresh the UI of the control panel on your app.

Sample code

Objective-C:

- (void)initDevice {
    self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];
    self.device.delegate = self;
}

#pragma mark - ThingSmartDeviceDelegate

- (void)device:(ThingSmartDevice *)device dpsUpdate:(NSDictionary *)dps {
     // The UI is refreshed when device DPs are changed.
}

- (void)deviceInfoUpdate:(ThingSmartDevice *)device {
     // The current device data such as the device name and online or offline status is updated.
}

- (void)deviceRemoved:(ThingSmartDevice *)device {
     // The current device is removed.
}

- (void)device:(ThingSmartDevice *)device signal:(NSString *)signal {
     // The Wi-Fi signal strength.
}

- (void)device:(ThingSmartDevice *)device otaUpdateStatusChanged:(ThingSmartFirmwareUpgradeStatusModel *)statusModel {
    // The callback for the status and progress of the firmware update.
    // Recommended for use with -startFirmwareUpgrade:
 }

- (void)device:(ThingSmartDevice *)device firmwareUpgradeProgress:(NSInteger)type progress:(double)progress {
    // The progress of the firmware update.
    // Will be deprecated and recommended for use with -upgradeFirmware:success:failure:
}

- (void)device:(ThingSmartDevice *)device firmwareUpgradeStatusModel:(ThingSmartFirmwareUpgradeStatusModel *)upgradeStatusModel {
    // The callback of the device update status.
    // Will be deprecated and recommended for use with -upgradeFirmware:success:failure:
}

Swift:

func initDevice() {
    device = ThingSmartDevice(deviceId: "your_device_id")
device?.delegate = self }

// MARK: - ThingSmartDeviceDelegate
 func device(_ device: ThingSmartDevice?, dpsUpdate dps: [AnyHashable : Any]?)  {
    // The UI is refreshed when device DPs are changed.
}

func deviceInfoUpdate(_ device: ThingSmartDevice?)  {
    // The current device data such as the device name and online or offline status is updated.
}

func deviceRemoved(_ device: ThingSmartDevice?)  {
    // The current device is removed.
}
func device(_ device: ThingSmartDevice?, signal: String?)  {
    // The Wi-Fi signal strength.
}
func device(_ device: ThingSmartDevice?, otaUpdateStatusChanged statusModel: ThingSmartFirmwareUpgradeStatusModel) {     
    // The callback for the status and progress of the firmware update. Generic firmware update and PID-specific firmware update are supported. Bluetooth Low Energy (LE) and Bluetooth mesh sub-devices can be updated in this way.
    // Recommended for use with -startFirmwareUpgrade:
    // For more information about OTA updates, see the documentation on firmware update.
}
func device(_ device: ThingSmartDevice?, firmwareUpgradeProgress type: Int, progress: Double) {     
    // The progress of the generic firmware update. Bluetooth LE and Bluetooth mesh sub-devices are not involved.
    // Will be deprecated and recommended for use with -upgradeFirmware:success:failure:
}
func device(_ device: ThingSmartDevice?, firmwareUpgradeStatusModel upgradeStatusModel: ThingSmartFirmwareUpgradeStatusModel?)  {
    // The status of the generic firmware update. Bluetooth LE and Bluetooth mesh sub-devices are not involved.
    // Will be deprecated and recommended for use with -upgradeFirmware:success:failure:
}

Get device information

Get the data of a single DP. The response is returned by the callback of the delegate - (void)device:(ThingSmartDevice *)device dpsUpdate:(NSDictionary *)dps.

  • This API method applies to DPs that do not initiate data transmission. For example, query countdown information. For regular DP queries, we recommend that you call ThingSmartDeviceModel.dps.
  • Example of sending an instruction

Sample code

Objective-C:

- (void)queryDP {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];
    // Returns the data of DP "1".
    NSDictionary *queryDpInfo = @{
         @"1": [NSNull null]
    };
    [self.device publishDps:queryDpInfo mode:ThingDevicePublishModeAuto success:^{
        NSLog(@"query dp success");
    } failure:^(NSError *error) {
        NSLog(@"query dp failure: %@", error);
    }];
}

Swift:

func queryDP() {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];
    // Returns the data of DP "1".
    let queryDpInfo = [
        "1": NSNull()
    ]
    device.publishDps(queryDpInfo, mode: ThingDevicePublishModeAuto, success: {
        print("query dp success")
    }, failure: { error in
        if let error = error {
            print("query dp failure: \(error)")
        }
    })
}

Rename a device

API description

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

Parameters

Parameter Description
name The device name.
success The success callback.
failure The failure callback.

Sample code

Objective-C:

- (void)modifyDeviceName:(NSString *)mame {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];
    [self.device updateName:name success:^{
        NSLog(@"updateName success");
    } failure:^(NSError *error) {
        NSLog(@"updateName failure: %@", error);
    }];
}

Swift:

func modifyDeviceName(_ name: String) {
    device?.updateName(name, success: {
        print("updateName success")
    }, failure: { (error) in
        if let e = error {
            print("updateName failure: \(e)")
        }
    })
}

Remove a device

After a device is removed, it enters the state ready for pairing. By default, the Wi-Fi device enters the Wi-Fi EZ mode.

API description

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

Parameters

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

Sample code

Objective-C:

- (void)removeDevice {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];

    [self.device remove:^{
        NSLog(@"remove success");
    } failure:^(NSError *error) {
        NSLog(@"remove failure: %@", error);
    }];
}

Swift:

func removeDevice() {
    device?.remove({
        print("remove success")
    }, failure: { (error) in
        if let e = error {
            print("remove failure: \(e)")
        }
    })
}

Factory reset

After default settings are restored for a device, it enters the state ready for pairing. By default, the Wi-Fi device enters the Wi-Fi EZ mode. In this case, device data is cleared.

API description

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

Parameters

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

Sample code

Objective-C:

- (void)removeDevice {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];

    [self.device resetFactory:^{
        NSLog(@"reset success");
    } failure:^(NSError *error) {
        NSLog(@"reset failure: %@", error);
    }];
}

Swift:

func removeDevice() {
    device?.resetFactory({
        print("reset success")
    }, failure: { (error) in
        if let e = error {
            print("reset failure: \(e)")
        }
    })
}

Query the Wi-Fi signal strength

After the Wi-Fi signal of a device is queried, the response is returned by the callback of the method device:signal: of ThingSmartDeviceDelegate.

API description

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

Parameters

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

Sample code

Objective-C:

- (void)getWifiSignalStrength {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];
    // self.device.delegate = self;

    [self.device getWifiSignalStrengthWithSuccess:^{
        NSLog(@"get wifi signal strength success");
    } failure:^(NSError *error) {
        NSLog(@"get wifi signal strength failure: %@", error);
    }];
}

#pragma mark - ThingSmartDeviceDelegate

- (void)device:(ThingSmartDevice *)device signal:(NSString *)signal {
    NSLog(@" signal : %@", signal);
}

Swift:

func getWifiSignalStrength() {
    self.device?.getWifiSignalStrength(success: {
        print("get wifi signal strength success")
    }, failure: { (error) in
        if let e = error {
            print("get wifi signal strength failure: \(e)")
        }
    })
}

// MARK: - ThingSmartDeviceDelegate
func device(_ device: ThingSmartDevice!, signal: String!) {
    print(" signal : \(signal)")
}

Query a list of sub-devices for a gateway

Returns a list of sub-devices for a specific gateway.

API description

- (void)getSubDeviceListFromCloudWithSuccess:(nullable void (^)(NSArray <ThingSmartDeviceModel *> *subDeviceList))success failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
success The success callback. A list of sub-devices for the gateway is returned.
failure The failure callback.

Sample code

Objective-C:

- (void)getSubDeviceList {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];

    [self.device getSubDeviceListFromCloudWithSuccess:^(NSArray<ThingSmartDeviceModel *> *subDeviceList) {
        NSLog(@"get sub device list success");
    } failure:^(NSError *error) {
        NSLog(@"get sub device list failure: %@", error);
    }];
}

Swift:

func getSubDeviceList() {
    device?.getSubDeviceListFromCloud(success: { (subDeviceList) in
        print("get sub device list success")
    }, failure: { (error) in
        if let e = error {
            print("get sub device list failure: \(e)")
        }
    })
}