AP Mode

Last Updated on : 2024-06-07 06:50:14download

This topic describes the access point (AP) or hotspot mode to pair devices. It is a connection capability for pairing over Wi-Fi. After a mobile phone is connected to the Wi-Fi hotspot of a target device, the app is paired and communicates with the mobile phone over Wi-Fi. With a high success rate and good reliability, this mode adapts to 2.4 GHz and 5 GHz dual-band routers. However, users need to manually switch between the Wi-Fi bands connected to the mobile phone.

Pairing methods

Cube App SDK supports the following AP pairing processes:

  • Legacy AP pairing: Get the pairing token from the cloud and implement a connection between the device and the cloud.

    Prerequisite: suitable for all devices.

  • New AP pairing: Users connect the device with the app first. Then, access the device on the app and scan for available Wi-Fi networks. Only compatible Wi-Fi networks are discovered. This way, the unsupported 5 GHz Wi-Fi networks are automatically filtered out. Users do not need to manually handle them and can enjoy a higher success rate of pairing.

    Prerequisite:

    • The TuyaOS version of the firmware built into the target device must be v3.6.1 or later.
    • Log in to the Apple Developer platform and enable Hotspot.
    • Integrate the ThingSmartHotspotCredentialKit library into your project.

Get the token

Before the AP pairing process, the SDK 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. An error message is returned.

Example

Objective-C:

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

Swift:

func getToken() {
    let ezActivator = ThingSmartActivator()
    ezActivator.getTokenWithHomeId(homeId, success: { token in
        print("getToken success: \(token)")
        // TODO: startConfigWiFi
    }, failure: { error in
        print("getToken failure: \(error.localizedDescription)")
    })
}

Callback of pairing delegate

- (void)activator:(ThingSmartActivator *)activator didReceiveDevice:(ThingSmartDeviceModel *)deviceModel error:(NSError *)error;

Parameters

Parameter Description
activator The instance of the ThingSmartActivator object for pairing.
deviceModel The paired device model that is returned if the request is successful. nil is returned if the request failed.
error The error message that is returned if the request failed. nil is returned if the request is successful.

Start pairing

API description

- (void)startConfigWiFi:(ThingActivatorMode)mode
                   ssid:(NSString *)ssid
               password:(NSString *)password
                  token:(NSString *)token
                timeout:(NSTimeInterval)timeout;

Parameters

Parameter Description
mode The pairing mode.
ssid The name of the target Wi-Fi network.
password The password of the target Wi-Fi network.
token The pairing token.
timeout The timeout period.

Example

Objective-C:

- (void)startConfigWiFi:(NSString *)ssid password:(NSString *)password token:(NSString *)token {
    // Implements the delegate method of ThingSmartActivator.
    self.apActivator.delegate = self;

    // Starts AP pairing, in which mode is set to ThingActivatorModeEZ.
    [self.apActivator startConfigWiFi:ThingActivatorModeAP ssid:ssid password:password token:token timeout:100];
}

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

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

    if (!error && deviceModel) {
        // The device is paired.
    }

    if (error) {
        // Failed to pair the device.
    }
}

// Added to v4.0.0: The callback for the intermediate process is triggered in the task of pairing a certain security device.
- (void)activator:(ThingSmartActivator *)activator didPassWIFIToSecurityLevelDeviceWithUUID:(NSString *)uuid {
        // Then, you can guide users to connect to the specified Wi-Fi network.
    // This way, the mobile is connected to the Wi-Fi network with the same SSID as specified by - startConfigWiFi:password:token:.

      // You can get the same SSID and call - continueConfigSecurityLevelDevice to continue with the pairing task.

//    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"SecurityLevelDevice" message:@"continue pair? (Please check you phone connected the same Wi-Fi as you Inputed)" preferredStyle:UIAlertControllerStyleAlert];
//    [vc addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:nil]];
//    [vc addAction:[UIAlertAction actionWithTitle:@"continue" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//
//        NSString *wifi = [self getCurrentWiFi];
//        if ([wifi isEqualToString:self.inputSSID]) {
//            [self.apActivator continueConfigSecurityLevelDevice];
//        }
//    }]];
//    [self presentViewController:vc animated:YES completion:nil];
}

Swift:

func startConfigWiFi(withSsid ssid: String, password: String, token: String) {
    // Implements the delegate method of ThingSmartActivator.
    apActivator.delegate = self

    // Starts pairing.
    apActivator.startConfigWiFi(ThingActivatorModeAP, ssid: ssid, password: password, token: token, timeout: 100)
}

lazy var apActivator: ThingSmartActivator = {
    let activator = ThingSmartActivator()
    return activator
}()

#pragma mark - ThingSmartActivatorDelegate
func activator(_ activator: ThingSmartActivator!, didReceiveDevice deviceModel: ThingSmartDeviceModel!, error: Error!) {
    if deviceModel != nil && error == nil {
        // The device is paired.
    }

    if let e = error {
        // Failed to pair the device.
        print("\(e)")
    }
}

// Added to v4.0.0: The callback for the intermediate process is triggered in the task of pairing a certain security device.
func activator(_ activator: ThingSmartActivator!, didPassWIFIToSecurityLevelDeviceWithUUID uuid: String!) {
        // Then, you can guide users to connect to the specified Wi-Fi network.
    // This way, the mobile is connected to the Wi-Fi network with the same SSID as specified by - startConfigWiFi:password:token:.

      // You can get the same SSID and call - continueConfigSecurityLevelDevice to continue with the pairing task.

//        let alert = UIAlertController(title: "SecurityLevelDevice", message: "continue pair? (Please check you phone connected the same Wi-Fi as you Inputed)", preferredStyle: .alert);
//        alert.addAction(UIAlertAction(title: "cancel", style: .cancel))
//        alert.addAction(UIAlertAction(title: "continue", style: .destructive, handler: { _ in
//            let wifi = getCurrentWiFi()
//            if wifi == inputSSID {
//                apActivator.continueConfigSecurityLevelDevice()
//            }
//        }))
//        present(alert, animated: true)
}

The AP mode is similar to the EZ mode, except that the first parameter of [self.apActivator startConfigWiFi:ssid:password:token:timeout:] is set to ThingActivatorModeAP for the AP mode.

ssid and password respectively specify the hotspot name and password of the router rather than that of the device.

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 allow users to cancel or complete pairing during the process, you must call the API method [ThingSmartActivator stopConfigWiFi] to stop pairing.

API description

- (void)stopConfigWiFi;

Example

Objective-C:

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

Swift:

func stopConfigWifi() {
    apActivator.delegate = nil
    apActivator.stopConfigWiFi()
}

Get device security configurations

API description

- (void)getDeviceSecurityConfigs:(ThingSuccessDict)success
                         failure:(ThingFailureError)failure;

Example

Objective-C:

self.activator = [[ThingSmartActivator alloc] init];
self.activator.delegate = self;
[self.activator getDeviceSecurityConfigs:^(NSDictionary *dict) {
  // Security configurations are obtained.
} failure:^(NSError *error) {
  // Failed to get security configurations.
}];

Swift:

activator.getDeviceSecurityConfigs { res in
  // Security configurations are obtained.
} failure: { error in
  // Failed to get security configurations.
}

Query Wi-Fi networks discovered by device

Before this call, the SDK checks the device status first. If the device has a status exception, for example, an unknown state, the system will not query the Wi-Fi networks discovered by the device.

API description

- (void)connectDeviceAndQueryWifiListWithTimeout:(NSTimeInterval)timeout;

Parameters

Parameter Description
timeout This parameter is optional. If the value is larger than 0, the countdown for timeout is enabled. Unit: seconds.

Example

Objective-C:

[self.activator connectDeviceAndQueryWifiListWithTimeout:120];

Swift:

activator.connectDeviceAndQueryWifiList(withTimeout: 120)

Start pairing

You can display the returned list of Wi-Fi networks for users to choose from.

API description

- (void)resumeAPPlusWithSSID:(NSString *)ssid
                    password:(NSString *)password
                       token:(NSString *)token
                     timeout:(NSTimeInterval)timeout;

Parameters

Parameter Description
ssid The name of the Wi-Fi network to which a paired device is connected.
password The password of the Wi-Fi network to which a paired device is connected.
token The pairing token.
timeout The timeout value of a pairing task. This parameter is required. Unit: seconds.

Example

Objective-C:

[self.activator resumeAPPlusWithSSID:@"SSID" password:@"password" token:@"token" timeout:120];

Swift:

activator.resumeAPPlus(withSSID: "SSID", password: "password", token: "token", timeout: 120)

Restart pairing

Asks users to provide the correct Wi-Fi name and password, and restarts pairing if the entered password is incorrect.

During the pairing process, the SDK automatically connects to the device within a certain period. After the device is connected, the SDK gets and reports the device status. This feature is supported by the latest firmware version only.

API description

- (int)resumeConfigWiFi:(ThingSmartPairingResumeConfigWiFiParam*)param error:(NSError**)error;

Parameters

ThingSmartPairingResumeConfigWiFiParam

Parameter Description
ThingActivatorMode The pairing mode. Set the value to ThingActivatorModeAPPlus.
ssid The SSID of the router.
password The password of the router.

Example

Objective-C:

ThingSmartPairingResumeConfigWiFiParam *param = [ThingSmartPairingResumeConfigWiFiParam new];
param.ssid = activatorParam.apActivatorParams.ssid;
param.password = activatorParam.apActivatorParams.pwd;
param.mode = ThingActivatorModeAPPlus;
[self.activator resumeConfigWiFi:param error:nil];

Swift:

let param = ThingSmartPairingResumeConfigWiFiParam()
param.mode = .apPlus
param.ssid = "ssid"
param.password = "password"
activator.resumeConfigWiFi(param, error: nil)

Stop pairing

You need to manually call this API method when the pairing task is stopped or resources are destroyed.

Example

Objective-C:

[self.activator stopConfigWiFi];

Swift:

activator.stopConfigWiFi()

Error codes

The following error codes occur while processing device connection. The error messages can be obtained from the device.

Error code Description
207201 Failed to create a connection channel with the device.
207206 An unknown state is returned during the query of device status.
207207 The device does not support the feature of getting Wi-Fi networks discovered.
207209 The pairing information received by the device is incorrect.
207210 The device failed to find a router after receiving the pairing information.
207211 The password in the pairing information received by the device is incorrect.
207212 The device failed to connect to a router after receiving the pairing information.
207213 Failed to get a Dynamic Host Configuration Protocol (DHCP)-assigned IP address after receiving the pairing information.
207214 An error has occurred while activating the device in the cloud.
207215 Failed to connect the device to the cloud.
207216 The request to activate the device failed.
207218 The request to activate the device in the cloud failed.
207219 Failed to connect to iot-dns in the cloud during device activation.
207220 The pairing task timed out.
207222 Failed to get the Wi-Fi networks of the device.