HomeKit Device Pairing

Last Updated on : 2022-03-03 06:44:54

TuyaSmartAppleDeviceKit

The module TuyaSmartAppleDeviceKit includes the HomeKit data for Apple’s Home app. It provides the capabilities to connect Apple devices to the Tuya IoT Development Platform. This way, your project can quickly integrate with Apple’s HomeKit framework. Simple API methods can be called to bind Powered by Tuya (PBT) devices and query device information.

Class name Description
TuyaSmartHomeKitPermissionUtil Query the status of HomeKit-defined permissions.
TuyaSmartHomeKitUtil Query and manage the HomeKit sites and devices.
TuyaSmartHomeKitConfigUtil Pair HomeKit devices.
TuyaSmartHomeKitDeviceService Provide cloud APIs for HomeKit devices.
TuyaSmartHomeKitDevice Query and update HomeKit device features customized by Tuya.

HomeKit devices are compatible with both Tuya’s and Apple ecosystems based on the following capabilities:

  • Add devices: bind devices with an iPhone.
  • Bind devices: bind devices with the Tuya IoT Development Platform.
  • Remove devices: remove devices from your app or the Home app. Only the binding mapping is deleted.
  • Manual resetting: remove device binding status from both your app and the Home app. To reset a device, for example, users can press and hold a socket key or turn on a light consecutively three times.

Query permission status

API description

typedef void(^TuyaSmartHomeKitPermissionCompletionHandler)(BOOL granted, HMHomeManager * _Nullable manager);

- (void)checkHomeKitPermissionWithCompletionHandler:(TuyaSmartHomeKitPermissionCompletionHandler)completionHandler;

Parameters

Parameter Description
completionHandler The result callback. The permission status and current homeManager are returned.

Example

ObjC:

self.permissionUtil = [[TuyaSmartHomeKitPermissionUtil alloc] init];
[self.permissionUtil checkHomeKitPermissionWithCompletionHandler:^(BOOL granted, HMHomeManager * _Nullable manager) {
        if (granted) {
            NSLog(@"HomeKit Permission is on");
        } else {
            NSLog(@"HomeKit Permission is off");
        }
    }];

Swift:

let permissionUtil:TuyaSmartHomeKitPermissionUtil = TuyaSmartHomeKitPermissionUtil()
permissionUtil.checkHomeKitPermission(completionHandler: { granted, manager in
        if granted {
            print("HomeKit Permission is on")
        } else {
            print("HomeKit Permission is off")
        }
    })

Loaded HomeKit data

API description

After you create an object of home manager, HomeKit queries a list of homes and objects from the HomeKit databases. For example, the objects room and accessory are returned. During the query, the primaryHome property of home manager is nil and the homes property is an empty array. Your app must process the home to be created after HomeKit initialization.

typedef void(^TuyaSmartHomeKitDataCompletionHandler)(HMHomeManager * _Nullable manager);

- (void)homeKitDataCompletionHandler:(TuyaSmartHomeKitDataCompletionHandler)completionHandler;

Parameters

Parameter Description
completionHandler The callback of loaded data.

Query a list of sites

API description

/// The primary home in HomeKit.
- (HMHome *)primaryHome;

/// Enumerate all homes in HomeKit.
- (NSArray<HMHome *> *)homes;

Query devices

API description

/// Enumerate all Powered by Tuya (PBT) devices in HomeKit.
- (NSArray<TuyaSmartHomeKitDevice *> *)devices;

/// Enumerate single Home's devices in HomeKit.
- (NSArray<TuyaSmartHomeKitDevice *> *)devicesForHome:(HMHome *)home;

Parameters

Parameter Description
home The site object for Apple’s Home app.

Example

ObjC:

self.homeKitUtil = [[TuyaSmartHomeKitUtil alloc] init];
[self.homeKitUtil homeKitDataCompletionHandler:^(HMHomeManager * _Nullable manager) {
        // data loaded
  self.primaryHome = [self.homeKitUtil primaryHome];
  self.homes = [self.homeKitUtil homes];
  self.devices = [self.homeKitUtil devices];
  self.devicesForHome = [self.homeKitUtil devicesForHome:currentHome];
 }];

Swift:

let homeKitUtil:TuyaSmartHomeKitUtil = TuyaSmartHomeKitUtil()
homeKitUtil.homeKitDataCompletionHandler { (manager) in
    // data loaded
    primaryHome = homeKitUtil.primaryHome
    homes = homeKitUtil.homes()
    devices = homeKitUtil.devices()
    devicesForHome = homeKitUtil.devices(forHome: currentHome)
}

Add a device

API description

/// Adding accessory to primary home.
- (void)addAccessoryToPrimaryHomeCompletionHandler:(void (^)(NSError * __nullable error))completion;

/// Adding accessory to designated home.
- (void)addAccessoryToHome:(HMHome *)home completionHandler:(void (^)(NSError * __nullable error))completion;

Parameters

Parameter Description
completion The operation result callback. If error is nil, the device is added.
home The site object.

Example

self.homeKitUtil = [[TuyaSmartHomeKitUtil alloc] init];
[self.homeKitUtil addAccessoryToHome:self.home completionHandler:^(NSError * _Nullable error) {
        if (!error) {
            [self reloadDevices];
        }
 }];

Swift:

let homeKitUtil:TuyaSmartHomeKitUtil = TuyaSmartHomeKitUtil()
homeKitUtil.addAccessory(to: home) { (error) in
    if error == nil {
        reloadDevices()
    }
}

Add a device and provide result callback

API description

Adds a device and executes the callback that is executed when the HomeKit setting controller finishes the loading task.

/// @param viewControllerDidLoad HomeKit Accessory setup view controller did load.
- (void)addAccessoryToPrimaryHomeWithSetupViewControllerDidLoadHandler:(void (^)(void))viewControllerDidLoad completionHandler:(void (^)(NSError * __nullable error))completion;

/// @param viewControllerDidLoad HomeKit Accessory setup view controller did load.
- (void)addAccessoryToHome:(HMHome *)home setUpViewControllerDidLoadHandler:(void (^)(void))viewControllerDidLoad completionHandler:(void (^)(NSError * __nullable error))completion;

Parameters

Parameter Description
viewControllerDidLoad The callback that is executed when the HomeKit setting controller finishes the loading task.
completion The operation result callback. If error is nil, the device is added.

Example

ObjC:

// self.homeKitUtil = [[TuyaSmartHomeKitUtil alloc] init];
[self.homeKitUtil addAccessoryToPrimaryHomeWithSetupViewControllerDidLoadHandler:^{
            // do something when setup view controller did load
        } completionHandler:^(NSError * _Nullable error) {
            if (!error) {
                // accessory add successed.
            }
 }];

Swift:

// let homeKitUtil:TuyaSmartHomeKitUtil = TuyaSmartHomeKitUtil()
homeKitUtil.addAccessoryToPrimaryHome {
        // do something when setup view controller did load
    } completionHandler: { (error) in
        if error == nil {
            // accessory add successed.
        }
    }

Remove a device

API description

- (void)removeAccessory:(HMAccessory *)accessory fromHome:(HMHome *)home completionHandler:(void (^)(NSError * __nullable error))completion;

Parameters

Parameter Description
accessory The accessory object HMAccessory. You can call TuyaSmartHomeKitDevice to query this object.
home The site object of HMHome.
completion The operation result callback. If error is nil, the device is added.

Example

ObjC:

// self.homeKitUtil = [[TuyaSmartHomeKitUtil alloc] init];
[self.homeKitUtil removeAccessory:device.accessory fromHome:self.home completionHandler:^(NSError * _Nullable error) {
            if (!error) {
                // remove success
            }
        }];

Swift:

// let homeKitUtil:TuyaSmartHomeKitUtil = TuyaSmartHomeKitUtil()
homeKitUtil.remove(accessory, from: home) { (error) in
        if error == nil {
            // remove success
        }
    }

Listen for site changes

API description

- (void)homesUpdatedHandler:(TuyaSmartHomeKitHomesUpdatedHandler)updateHandler;

Parameters

Parameter Description
updateHandler The callback that is executed in the case of site changes. For example, the main site is updated or a site is deleted.

Example

ObjC:

// self.homeKitUtil = [[TuyaSmartHomeKitUtil alloc] init];
[self.homeKitUtil homesUpdatedHandler:^(HMHomeManager * _Nullable manager) {
        self.homes = [self.homeKitUtil homes];
        [self.tableView reloadData];
    }];

Swift:

// let homeKitUtil:TuyaSmartHomeKitUtil = TuyaSmartHomeKitUtil()
homeKitUtil.homesUpdatedHandler { (manager) in
      homes = homeKitUtil.homes()
      tableView.reloadData()
   }

Bind a device with Tuya’s ecosystem

API description

- (void)startConfigDevice:(TuyaSmartHomeKitDevice *)device
                  timeout:(NSTimeInterval)timeout
                   homeId:(long long)homeId
                  success:(void (^)(TuyaSmartDeviceModel *deviceModel))success
                  failure:(void (^)(NSError *error))failure;

Parameters

Parameter Description
device The device object TuyaSmartHomeKitDevice to be bound.
timeout The timeout value of a binding task. Valid values: 90 to 120. Unit: seconds.
homeId The ID of the site with which the device is bound.
success The success callback.
failure The failure callback.

Example

ObjC:

self.configUtil = [[TuyaSmartHomeKitConfigUtil alloc] init];
[self.configUtil startConfigDevice:self.device timeout:120 homeId:homeId success:^(TuyaSmartDeviceModel * _Nonnull deviceModel) {
        // bind success
        [self.device updateWithCompletionHandler:^(NSError * _Nullable error) {
            // update device info
            [self setDeviceInfo];
        }];
        } failure:^(NSError * _Nonnull error) {
        // bind fail
        }];

Swift:

let configUtil:TuyaSmartHomeKitConfigUtil = TuyaSmartHomeKitConfigUtil()
configUtil.startConfigDevice(device, timeout: 120, homeId: 68) { (tuyaDevice) in
        // bind success
        device.update { (error) in
            // update device info
            setDeviceInfo()
        }
    } failure: { (error) in
        // bind fail
    }

Stop binding

API description

- (void)stopConfigDevice;

Example

ObjC:

// self.configUtil = [[TuyaSmartHomeKitConfigUtil alloc] init];
[configUtil stopConfigDevice];

Swift:

// let configUtil:TuyaSmartHomeKitConfigUtil = TuyaSmartHomeKitConfigUtil()
configUtil.stopConfigDevice()

Query product information

API description

+ (void)requestProductInfoWithProductId:(NSString *)productId
                                   uuid:(NSString *)uuid
                                   success:(void (^)(TuyaSmartHomeKitProductInfo *info))success
                                failure:(void(^)(NSError *error))failure;

Parameters

Parameter Description
productId The product ID of the device.
uuid The unique ID of a device.
success The success callback. TuyaSmartHomeKitProductInfo is returned.
failure The failure callback.

Example

// TuyaSmartHomeKitDevice *homekitDevice
NSString *productID = homekitDevice.productID.value;
NSString *uuid = homekitDevice.UUID.value;
[TuyaSmartHomeKitDeviceService requestProductInfoWithProductId:productID uuid:uuid success:^(TuyaSmartHomeKitProductInfo * _Nonnull info) {
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:info.iconURL] placeholderImage:[UIImage imageNamed:@"ty_device_empty"]];
} failure:^(NSError * _Nonnull error) {

}];

Query HomeKit setup code of associated cloud device

API description

+ (void)requestDeviceHomeKitSetupCodeWithDeviceId:(NSString *)deviceId
                                          success:(void (^)(TuyaSmartHomeKitSetupCodeInfo *info))success
                                          failure:(void(^)(NSError *error))failure;

Parameters

Parameter Description
deviceId The device ID bound with the cloud.
success The success callback. TuyaSmartHomeKitSetupCodeInfo is returned.
failure The failure callback.

Example

[TuyaSmartHomeKitDeviceService requestDeviceHomeKitSetupCodeWithDeviceId:deviceId success:^(TuyaSmartHomeKitSetupCodeInfo * _Nonnull info) {
        self.homeKitCodeLabel.text = info.homeKitSetupCode;
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        [self.tableView reloadData];
    }];

Device information

TuyaSmartHomeKitDevice encapsulates the PBT device model for an Apple’s accessory object. Users can create devices, query device status, and query and update device features customized by Tuya.

API description

- (instancetype)initWithAccessory:(HMAccessory *)accessory;
Parameter Description
accessory The accessory object.

Example

ObjC:

#pragma mark - HMHomeDelegate
- (void)home:(HMHome *)home didAddAccessory:(HMAccessory *)accessory {
  TuyaSmartHomeKitDevice *deviceNew = [[TuyaSmartHomeKitDevice alloc] initWithAccessory:accessory];
}

Swift:

func home(_ home: HMHome, didAdd accessory: HMAccessory) {
    let deviceNew = TuyaSmartHomeKitDevice(accessory: accessory)
}

Properties

Property Description
reachable Indicates whether a device can be connected.
bridged Indicates whether a device is brideged.
isTuyaDevice Indicates whether a PBT device is bridged.
accessory The existing accessory object.

Characteristics

Parameter Description
devId The device ID. Only an associated device has the value.
productID The product ID of the device.
UUID The unique identifier of the device.
token The pairing token.
active The status of cloud-based activation or binding for PBT devices.
  • 0: inactive
  • 1: activated
  • A sub-device is only assigned productID. Its binding status follows the status of the associated bridging gateway.
  • The product ID returned by productID characteristic is used to query the name and icon of the device.