HomeKit Device Pairing

Last Updated on : 2022-03-03 07:14:54download

TuyaSmartAppleDeviceKit

The TuyaSmartAppleDeviceKit module mainly includes the ability to manage HomeKit data from Apple’s ‘Home’ app and bind Apple devices directly to the Tuya IoT Development Platform. The advantages are faster integration with the Apple HomeKit framework and simple API calls to implement features such as binding devices to the Tuya IoT IoT Development Platform and getting device information.

Class Description
TuyaSmartHomeKitPermissionUtil Provides the ability to get the HomeKit permission on status
TuyaSmartHomeKitUtil Provides the ability to access and manage local homes and devices from HomeKit
TuyaSmartHomeKitConfigUtil Provides networking capabilities to serve HomeKit devices
TuyaSmartHomeKitDeviceService Provides cloud-based capabilities that serve HomeKit devices
TuyaSmartHomeKitDevice Provides the ability to obtain and update device Tuya custom HomeKit service features

Preface

HomeKit devices have the ability to connect to both the Tuya IoT Development Platform and the Apple ecosystem

‘Add Device’ means local association with Apple iPhones.

‘Binding Device’ means connection to the Tuya Tuya IoT IoT Development Platform.

Removing a device from the Tuya App or Home App will only remove the respective binding status.

A manual reset (usually a long press of the socket button or 3 consecutive lights on) will remove the binding status of both devices.

Get permission to open status

Description

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

- (void)checkHomeKitPermissionWithCompletionHandler:(TuyaSmartHomeKitPermissionCompletionHandler)completionHandler;

Parameters

Parameter Description
completionHandler Result callback, return permission open status and current homeManager

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")
        }
    })

HomeKit data loading completed

Description

When you create a home manager object, HomeKit starts fetching these homes and related objects, such as room and accessory objects, from the HomeKit database. While HomeKit is fetching those objects, the home manager’s primaryHome property is ni l, and the homes property is an empty array. Your App should handle the situation where the user has not finished creating the home, but the App should wait until HomeKit finishes initializing the home manager.

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

- (void)homeKitDataCompletionHandler:(TuyaSmartHomeKitDataCompletionHandler)completionHandler;

Parameters

Parameter Description
completionHandler data loading completed call back

Get home

Description

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

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

Get devices

Description

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

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

Parameters

Parameter Description
home Apple system home instance

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 device

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 Device add result callback, error is nil Description added successfully
home home instance

Example

Objc:

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 device, provide loading completion call back

Description

Calling the system’s Add Device method does not get the load completion callback for the system’s HomeKit settings controller, use this method to fix the problem.

/// @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 System HomeKit settings controller load completion callback
completion Device add result callback, error is nil Description added successfully

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 device

Description

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

Parameters

Parameter Description
accessory The system’s HMAccessory accessory object, available through the TuyaSmartHomeKitDevice object
home System’s HMHome Object
completion Removal result callback, error is nil Description Removal successful

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
        }
    }

Observer homes update

Description

- (void)homesUpdatedHandler:(TuyaSmartHomeKitHomesUpdatedHandler)updateHandler;

Parameters

Parameter Description
updateHandler System homes update callbacks (primary home changes, add or remove home)

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()
   }

Associate to Tuya

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 Bindable TuyaSmartHomeKitDevice device objects
timeout Binding timeout time, usually 90~120 seconds
homeId The home ID to be bound with the Tuya IoT Development Platform
success Binding success
failure Binding failed

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

Description

- (void)stopConfigDevice;

Example

Objc:

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

Swift:

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

Get device product information

Description

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

Parameters

Parameter Description
productId Identification of equipment categories
uuid Unique identification of the device
success Successful callback, returns TuyaSmartHomeKitProductInfo information
failure 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) {

   }];

Get the HomeKit setup code for an associated cloud device

Description

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

Parameters

Parameter Description
deviceId identification of the device
success Successful callback, returns TuyaSmartHomeKitSetupCodeInfo information
failure 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 is a Tuya device model that specifically encapsulates Apple accessory objects, providing the ability to create devices, get device status, and get and update device Tuya custom service features.

Description

- (instancetype)initWithAccessory:(HMAccessory *)accessory;
Parameter Description
accessory System’s accessory

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)
}

Description

Property Description
reachable Is the device reachable
bridged Whether the device is bridged
isTuyaDevice Whether Tuya device
accessory System accessory

Characteristics Description

Characteristic Description
devId Device id, only for binded devices
productID Product id of the device
UUID Unique device identification
token Pairing token
active The activation or binding status in the cloud. Valid values: 0: unactivated. 1: activated.

The sub-device only has a productID and the binding status of the sub-device follows the bridge gateway

The product id is read by the productID characteristic to get the name and icon of the device.