Device Pairing

Last Updated on : 2024-06-18 06:44:50download

Add a Bluetooth lock

API description

- (void)activeBLELock:(ThingBLEAdvModel *)deviceInfo
               siteId:(long long)siteId
              success:(nullable void(^)(ThingSmartDeviceModel *deviceModel))success
              failure:(nullable ThingFailureHandler)failure;

Parameters

Parameter Description
deviceInfo The data model of the discovered device.
siteId The site ID.
success The success callback.
failure The failure callback.

Discover device

Set the delegate and start searching for devices.

    [ThingSmartBLEManager sharedInstance].delegate = self;
    [ThingSmartBLEManager.sharedInstance startListening:YES];

Get device information in the callback and show it on the app.

- (void)didDiscoveryDeviceWithDeviceInfo:(ThingBLEAdvModel *)deviceInfo {
    NSUInteger index = [self.dataArray indexOfObjectPassingTest:^BOOL(ThingBLEAdvModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.uuid isEqualToString:deviceInfo.uuid];
    }];
    if (index != NSNotFound) {
        [self.dataArray replaceObjectAtIndex:index withObject:deviceInfo];
    } else {
        [self.dataArray addObject:deviceInfo];
    }
    [self.tableView reloadData];
}

Start pairing

Pair the discovered device.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ThingBLEAdvModel *deviceInfo = self.dataArray[indexPath.row];
    long long siteId = SiteManager.shared.siteId;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ThingBLELockActivator.shared activeBLELock:deviceInfo
                                         siteId:siteId
                                        success:^(ThingSmartDeviceModel * _Nonnull deviceModel) {

    } failure:^{

    }];
}

Stop pairing

    [ThingSmartBLEManager sharedInstance].delegate = nil;
    [ThingSmartBLEManager.sharedInstance stopListening:YES];

Add a Bluetooth gateway

When adding a Bluetooth gateway, users are asked to enter the name and password of the router.

API description

- (void)startConfigBLEWifiDeviceWithUUID:(NSString *)UUID
                                  homeId:(long long)homeId
                               productId:(NSString *)productId
                                    ssid:(NSString *)ssid
                                password:(NSString *)password
                                 timeout:(NSTimeInterval)timeout
                                 success:(ThingSuccessHandler)success
                                 failure:(ThingFailureHandler)failure;

Parameters

Parameter Description
UUID The unique ID of the discovered device.
homeId The site ID.
productId The product ID of the discovered device.
ssid The name of the Wi-Fi network.
password The password of the Wi-Fi network.
timeout The timeout, in seconds.
success The success callback.
failure The failure callback.

Discover device

Start searching for a device.

- (IBAction)searchClicked:(id)sender {
    ThingSmartBLEManager.sharedInstance.delegate = self;
    [ThingSmartBLEManager.sharedInstance startListening:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

Process data in the callback and show the discovered device.

#pragma mark - ThingSmartBLEManagerDelegate

- (void)didDiscoveryDeviceWithDeviceInfo:(ThingBLEAdvModel *)deviceInfo {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    // Discovered an inactive device.
    NSUInteger index = [self.dataArray indexOfObjectPassingTest:^BOOL(ThingBLEAdvModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.uuid isEqualToString:deviceInfo.uuid];
    }];
    if (index != NSNotFound) {
        [self.dataArray replaceObjectAtIndex:index withObject:deviceInfo];
    } else {
        [self.dataArray addObject:deviceInfo];
    }
    [self.tableView reloadData];
}

Start pairing

Determine if the device type is a Bluetooth gateway, and prompt the user to enter the name and password of their Wi-Fi network.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ThingBLEAdvModel *deviceInfo = self.dataArray[indexPath.row];

    if (deviceInfo.bleType == ThingSmartBLETypeUnknow ||
        deviceInfo.bleType == ThingSmartBLETypeBLE ||
        deviceInfo.bleType == ThingSmartBLETypeBLEPlus ||
        deviceInfo.bleType == ThingSmartBLETypeBLESecurity ||
        deviceInfo.bleType == ThingSmartBLETypeBLEZigbee ||
        deviceInfo.bleType == ThingSmartBLETypeBLEBeacon) {
        [Alert showBasicAlertOnVC:self withTitle:@"Please use BLE Mode to pair" message:deviceInfo.uuid];
        return;
    }


    NSString *title = NSLocalizedString(@"", nil);

    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil)
                                                           style:UIAlertActionStyleCancel
                                                         handler:NULL];

    [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"ssid";
    }];
    [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"password";
    }];

    UIAlertAction *confirmAction =[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil)
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * _Nonnull action) {
        NSString *ssid = alertC.textFields.firstObject.text;
        NSString *password = alertC.textFields.lastObject.text;
        [self startDualModeWithDevinfo:deviceInfo ssid:ssid password:password];
    }];

    [alertC addAction:cancelAction];
    [alertC addAction:confirmAction];
    [self presentViewController:alertC animated:YES completion:nil];
}

Start pairing.

- (void)startDualModeWithDevinfo:(ThingBLEAdvModel *)deviceInfo ssid:(NSString *)ssid password:(NSString *)password {
    long long homeId = SiteManager.shared.siteId;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    ThingSmartBLEWifiActivator.sharedInstance.bleWifiDelegate = self;
    [ThingSmartBLEWifiActivator.sharedInstance startConfigBLEWifiDeviceWithUUID:deviceInfo.uuid
                                                                         homeId:homeId
                                                                      productId:deviceInfo.productId
                                                                           ssid:ssid
                                                                       password:password
                                                                        timeout:100
                                                                        success:^{

    } failure:^{

    }];
}

The callback returns the pairing result.

#pragma mark - ThingSmartBLEWifiActivatorDelegate

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator didReceiveBLEWifiConfigDevice:(ThingSmartDeviceModel *)deviceModel error:(NSError *)error {
    if (error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@", error);
        return;
    }

    NSString *name = deviceModel.name ?: NSLocalizedString(@"Unknown Name", @"Unknown name device.");
    NSLog(@"%@", name);
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
    [NSNotificationCenter.defaultCenter postNotificationName:@"UpateDeviceList" object:nil];
}

Stop pairing

- (void)stopScan{

    ThingSmartBLEManager.sharedInstance.delegate = nil;
    [ThingSmartBLEManager.sharedInstance stopListening:YES];

    ThingSmartBLEWifiActivator.sharedInstance.bleWifiDelegate = nil;
    [ThingSmartBLEWifiActivator.sharedInstance stopDiscover];
}

When pairing a Bluetooth gateway, ensure that the connected Wi-Fi network is accessible and operates on the 2.4 GHz band.

Add a wired Zigbee gateway

A wired device connects to a router over an Ethernet cable. During the pairing process, users do not need to enter the name and password of the router.

  1. Before pairing
    Guide the user to reset the device to activate pairing mode.

  2. Get pairing token
    The app gets the pairing token by calling the method in the SDK.

  3. Get device information
    The app gets the device information by calling the method in the SDK.

  4. Start pairing
    The app calls the pairing method in the SDK to set the required parameters.

  5. Finish pairing
    The app receives a callback from the SDK and finishes the pairing process.

Discover device

The SDK provides the capability to discover a wired device ready for pairing. The mobile phone and device must be on the same network. Register the notification for discovering wired devices. When the SDK receives the packet advertised by a wired device, it forwards the device information through notifications. Alternatively, implement the delegate for ThingSmartActivator to get the device information.

Forward notification

// After receiving the broadcast from the wired device, this notification will be sent. The object is dictionary, @{@"productId":productId, @"gwId":gwId}
extern NSString *const ThingSmartActivatorNotificationFindGatewayDevice;

Device discovery callback

- (void)activator:(ThingSmartActivator *)activator didFindGatewayWithDeviceId:(nullable NSString *)deviceId productId:(nullable NSString *)productId;

Callback parameters

Parameter Description
activator The ThingSmartActivator object for pairing.
deviceId The device ID.
productId The product ID.

Get token

Before the pairing process, the app must get a pairing token from the cloud in the networked state. The token is valid for 10 minutes and expires immediately after the device is paired. A new token must be generated if the device needs to be paired again.

API description

- (void)getTokenWithHomeId:(long long)homeId
                   success:(ThingSuccessString)success
                   failure:(ThingFailureError)failure;

Parameters

Parameter Description
homeId The ID of the home with which the device is bound.
success The success callback. A pairing token is returned.
failure The failure callback, returning an error message.

Example

- (void)getToken {
        ThingSmartActivator *wiredActivator = [[ThingSmartActivator alloc] init];
    [wiredActivator getTokenWithHomeId:homeId success:^(NSString *token) {
        NSLog(@"getToken success: %@", token);
        // TODO: startConfigWiFi
    } failure:^(NSError *error) {
        NSLog(@"getToken failure: %@", error.localizedDescription);
    }];
}

Start pairing

API description

- (void)startConfigWiFiWithToken:(NSString *)token timeout:(NSTimeInterval)timeout

Parameters

Parameter Description
token The pairing token.
timeout The timeout period.

Example

- (void)startConfigWiFiToken:(NSString *)token {
    // Set delegate for ThingSmartActivator and implement the delegate method.
    self.wiredActivator.delegate = self;

    // Start pairing.
    [self.wiredActivator startConfigWiFiWithToken:token timeout:100];
}

- (ThingSmartActivator *)wiredActivator {
    if (!_wiredActivator) {
        _wiredActivator = [[ThingSmartActivator alloc] init];
    }
    return _wiredActivator;
}

#pragma mark - ThingSmartActivatorDelegate
- (void)activator:(ThingSmartActivator *)activator didReceiveDevice:(ThingSmartDeviceModel *)deviceModel error:(NSError *)error {

    if (!error && deviceModel) {
        // Pairing succeeded.
    }

    if (error) {
        // Pairing failed.
    }

}

Stop pairing

After the pairing process is started, the app continuously broadcasts the pairing data until a device is paired or the process times out. To stop or finish pairing, call [ThingSmartActivator stopConfigWiFi].

API description

- (void)stopConfigWiFi;

Example

- (void)stopConfigWifi {
    self.wiredActivator.delegate = nil;
    [self.wiredActivator stopConfigWiFi];
}

Add a Zigbee lock

A sub-device is connected to the cloud through a gateway such as a Zigbee gateway or Bluetooth gateway. Therefore, the pairing mode depends on a specific gateway that processes device activation and notifications.

API description

- (void)activeSubDeviceWithGwId:(NSString *)gwId timeout:(NSTimeInterval)timeout

Parameters

Parameter Description
gwId The gateway ID.
timeout The timeout, in seconds.

Example

Start pairing

- (void)activeSubDevice {
    ThingSmartActivator.sharedInstance.delegate = self;
    [ThingSmartActivator.sharedInstance activeSubDeviceWithGwId:self.gwId timeout:100];
}

The callback invoked when pairing is successful.

#pragma mark - ThingSmartActivatorDelegate
- (void)activator:(ThingSmartActivator *)activator didReceiveDevice:(ThingSmartDeviceModel *)deviceModel error:(NSError *)error {
    if (error || deviceModel == nil) {
        NSLog(@"%@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        return;
    }
    [ThingLockDevice activeCallbackWithSiteId:SiteManager.shared.siteId
                                       devIds:@[deviceModel.devId]
                                      success:^(id result) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.navigationController popViewControllerAnimated:YES];
        [NSNotificationCenter.defaultCenter postNotificationName:@"UpateDeviceList" object:nil];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

On successful pairing, call the following method to activate the device.

+ (void)activeCallbackWithSiteId:(long long)siteId
                          devIds:(NSArray<NSString *> *)devIds
                         success:(ThingSuccessID)success
                         failure:(ThingFailureError)failure;

Stop activating a sub-device

API description

- (void)stopActiveSubDeviceWithGwId:(NSString *)gwId

Parameters

Parameter Description
gwId The gateway ID.

Example

- (void)stopActiveSubDevice {
    ThingSmartActivator.sharedInstance.delegate = nil;
    [ThingSmartActivator.sharedInstance stopActiveSubDeviceWithGwId:self.gwId];
}