HomeKit Device Pairing

Last Updated on : 2023-08-22 08:02:04download

Smart Life App SDK enables HomeKit devices to be compatible with both Tuya’s and Apple’s ecosystems based on the following capabilities. Users add devices locally in Apple’s Home app, and the devices can be simultaneously bound with the Tuya IoT Development Platform.

Functional description

ThingSmartAppleDeviceKit 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 Tuya-enabled devices and query device information.

Class Description
ThingSmartHomeKitPermissionUtil Query the status of HomeKit-defined permissions.
ThingSmartHomeKitUtil Query and manage the HomeKit homes and devices.
ThingSmartHomeKitConfigUtil Pair HomeKit devices.
ThingSmartHomeKitDeviceService Provide cloud APIs for HomeKit devices.
ThingSmartHomeKitDevice Query and update HomeKit device features customized by Tuya.

The following operations are supported:

  • Add devices: Bind devices with an iPhone.
  • Bind devices: Bind devices with the Tuya IoT Development Platform.
  • Remove devices: Remove devices from Tuya’s app or the Home app. Only the binding status is cleared.
  • Reset devices: 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(^ThingSmartHomeKitPermissionCompletionHandler)(BOOL granted, HMHomeManager * _Nullable manager);

- (void)checkHomeKitPermissionWithCompletionHandler:(ThingSmartHomeKitPermissionCompletionHandler)completionHandler;

Parameters

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

Example

Objective-C:

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

Swift:

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

Load 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(^ThingSmartHomeKitDataCompletionHandler)(HMHomeManager * _Nullable manager);

- (void)homeKitDataCompletionHandler:(ThingSmartHomeKitDataCompletionHandler)completionHandler;

Parameters

Parameter Description
completionHandler The callback to invoke when data is loaded.

Query a list of homes

API description

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

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

Query devices

API description

/// Enumerate all Tuya devices in HomeKit.
- (NSArray<ThingSmartHomeKitDevice *> *)devices;

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

Parameters

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

Example

Objective-C:

self.homeKitUtil = [[ThingSmartHomeKitUtil 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:ThingSmartHomeKitUtil = ThingSmartHomeKitUtil()
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 the error is nil, the device is added.
home The site object.

Example

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

Swift:

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

Add a device and provide result callback

API description

Adds a device and sets the callback to invoke 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 to invoke when the HomeKit setting controller finishes the loading task.
completion The operation result callback. If the error is nil, the device is added.

Example

Objective-C:

// self.homeKitUtil = [[ThingSmartHomeKitUtil 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:ThingSmartHomeKitUtil = ThingSmartHomeKitUtil()
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 ThingSmartHomeKitDevice to query this object.
home The home object of HMHome.
completion The operation result callback. If the error is nil, the device is removed.

Example

Objective-C:

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

Swift:

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

Listen for home changes

API description

- (void)homesUpdatedHandler:(ThingSmartHomeKitHomesUpdatedHandler)updateHandler;

Parameters

Parameter Description
updateHandler The callback to invoke when homes have changes. For example, the main home is updated or a home is deleted.

Example

Objective-C:

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

Swift:

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

Bind a device with Tuya’s ecosystem

API description

- (void)startConfigDevice:(ThingSmartHomeKitDevice *)device
                  bleAdv:(NSData *)bleAdv
                  timeout:(NSTimeInterval)timeout
                   homeId:(long long)homeId
                  success:(void (^)(ThingSmartDeviceModel *deviceModel))success
                  failure:(void (^)(NSError *error))failure;

Parameters

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

Example

Objective-C:

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

Swift:

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

Stop binding

API description

- (void)stopConfigDevice;

Example

Objective-C:

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

Swift:

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

Query product information

API description

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

Parameters

Parameter Description
productId The product ID of the device.
uuid The universally unique identifier (UUID) of the device.
success The success callback. ThingSmartHomeKitProductInfo is returned.
failure The failure callback.

Example

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

}];

Query HomeKit setup code of associated cloud device

API description

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

Parameters

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

Example

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

Device information

ThingSmartHomeKitDevice encapsulates the Tuya-enabled 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

Objective-C:

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

Swift:

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

Property description

Property Description
reachable Indicates whether a device can be connected.
bridged Indicates whether a device is brideged.
isThingDevice Indicates whether a device is enabled by Tuya.
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 universally unique identifier (UUID) of the device.
token The pairing token.
active The status of cloud-based activation or binding for Tuya-enabled devices.
  • 0: The device is not activated.
  • 1: The device is activated.

A sub-device is only assigned productID. Its binding status follows the status of the associated bridging gateway.

The product ID returned by the productID characteristic is used to query the name and icon of the device.