Copied!
Private Cloud
  • Application Development Services
    • Quick Start
    • API Gateway
      • API Request
        • Request Structure
        • Authorization Method
        • Sign Requests
        • Global Error Codes
      • Best Practice
        • Set Postman Environment and Call API Operations
      • API List
        • Basic API
          • Authorization Token Management
            • Refresh Token
            • Get a Token
        • IoT Core
          • Device Management
            • Query Devices in Space
            • Get Status Reporting Log
            • Get Update Progress
            • Query Device Details in Bulk
            • Delete Device
            • Get Update Information
            • Query Device Details
            • Confirm Start of Update
            • Get Device State
            • Get Operation Log
            • Modify Basic Properties
            • Freeze/Unfreeze Device
            • Transfer Device
            • Restore Factory Defaults
            • Query Pairing Result
          • Device Control
            • Send Property
            • Query Properties
            • Modify Properties
            • Set Desired Property
            • Query Desired Properties
            • Query Things Data Model
            • Device Control (Standard Instruction Set)
              • Get Status Set
              • Send Commands
              • Get Specifications and Properties of the Device
              • Get Instruction Set of the Device
              • Get Instruction Set of the Category
              • Get Status of a Single Device
              • Get Latest Status of Multiple Devices
          • Device Group
            • Create Group
            • Delete Group
            • Query Group
            • Rename Group
            • Get Group in Space
            • Add Device
            • Delete Devices
            • Get Device Group
            • Query Group Properties
            • Send Group Properties
            • Query Group Devices
    • Message Gateway
      • Preparations
      • Development Guide
        • Integrate with Message Service
        • Data Signature
        • Message Types
      • Best Practices
        • Get Push Messages by Pulsar (Java SDK)
        • Get Push Messages by Pulsar (Python SDK)
        • Get Push Messages by Pulsar (Go SDK)
        • Get Push Messages by Pulsar (Node.js SDK)
        • Get Push Messages by Pulsar (C# SDK)
  • App Development
    • Preparation
    • Developer Guide for iOS
      • Fast Integration with Cube App SDK for iOS
      • Upgrade Guide
      • Quick Start with Cube App SDK for iOS
      • iOS App: Implement User Account Features
      • User Account Management (iOS)
        • Register and Login with Phone Number
        • Register and Login with Email Address
        • Login with UID
        • Login with Third-Party Account
        • Register and Login with Anonymous Account
        • QR Code-Based Login Authorization
        • Manage User Accounts
      • Home Management
        • Home Information Management
        • Room Information Management
        • Member Information Management
      • Device Pairing (iOS)
        • Wi-Fi EZ Mode
        • AP Mode
        • Wired Mode
        • Sub-Device Pairing
        • NB-IoT Device Pairing
        • HomeKit Device Pairing
        • Pegasus Pairing
        • CPPLUS Link-Based Device Binding
        • Matter Devices
          • Prepare for Integration with Matter Device
          • Pair Matter Device
        • Pair with QR Code on Device
      • Bluetooth Devices
        • Bluetooth Mesh
        • CPPLUS Mesh
      • Device Management
        • Firmware Update
        • Query Reported DP Logs
        • Device Sharing
        • Backup Wi-Fi Networks
        • Offline Device Alerts
        • CPPLUS Link-Based Devices
        • Manage Matter Devices
      • Device Control
        • Multi-Control Linkage
        • Scheduled Tasks
        • Group Management
        • All Category Control Panel
        • Air Conditioning Category Control Panel
        • Switch Control Panel
        • Device DP Parser
      • Smart Scenes
        • Scene Recommendation
      • Common API Methods
      • Integrate with Push Notifications
      • Message Management
        • Configure Push Notifications
        • Message Capabilities
      • Configure Widget Project
      • Error Codes
      • FAQ
      • Extension SDK
        • IPC SDK
          • SDK Architecture
          • Fast Integration with IPC SDK for iOS
          • Quick Start with IPC SDK for iOS
          • IPCs
          • Device Pairing
          • IPC Control (iOS)
          • Live Video Streaming
          • Playback of Video Stored on SD Card
          • SD Card Management
          • Audio and Video Features
          • Low Power Doorbell
          • PTZ Control
          • Doorbell Call Service
          • Cloud Storage
          • Cloud Storage Debugging Tool
          • Detection Alerts
          • Encrypted Images
          • Timeline View
          • Offline Log
          • Migrate IPC UI BizBundles
          • P2P Capabilities
          • IPC SDK Automated Test Tool
          • IPC SDK Test Cases (Reference)
          • FAQ
          • Error Codes
        • Sweeper SDK
          • P2P Download from Robot Vacuums
          • Gyroscope and Visual Robot Vacuums
          • Laser Robot Vacuum
          • Voice Package Download
          • Error Codes
          • Sample Code
        • Smart Lock SDK
          • Wi-Fi Lock
          • Bluetooth Lock
          • Wi-Fi Lock Audio and Video Capability
          • Smart Lock Basic API
      • What is UI BizBundle SDK for iOS?
        • Preparation
        • Integrate with Framework
        • Home Management UI BizBundle
        • Device Pairing UI BizBundle
        • Scene UI BizBundle
        • Multi-Control Linkage UI BizBundle
        • Device Control UI BizBundle
        • OTA UI BizBundle
        • Group Management UI BizBundle
        • Device Details UI BizBundle
        • Panel Multilingual BizBundle
        • IPC UI BizBundles
        • Cloud Storage UI BizBundle
        • FAQ UI BizBundle
        • Message Center UI BizBundle
        • Voice Skills Account Linking UI BizBundle
        • Theme Color Configuration BizBundle
        • Sharing UI BizBundle
      • Changelog
    • Developer Guide for Android
      • Fast Integration with Cube App SDK for Android
      • Upgrade Guide
      • User Account Management
        • Register and Login with Phone Number
        • Register and Login with Email Address
        • Login with UID
        • Login with Third-Party Account
        • Register and Login with Anonymous Account
        • QR Code-Based Login Authorization
        • Manage User Accounts
      • Home Management
        • Home Information Management
        • Room Information Management
        • Member Information Management
      • Device Pairing (iOS)
        • Wi-Fi EZ Mode
        • AP Mode
        • Wired Mode
        • Pair with QR Code on Device
        • Pegasus Pairing
        • Sub-Device Pairing
        • NB-IoT Device Pairing
        • CPPLUS Link-Based Device Binding
        • Matter Devices
          • Prepare for Integration with Matter Device
          • Pair Matter Device
        • Pair with QR Code on Device
      • Bluetooth Devices
        • Bluetooth LE Devices
        • Bluetooth Mesh
        • CPPLUS Mesh
      • Device Management
        • Firmware Update
        • Query Reported DP Logs
        • Device Sharing
        • Backup Wi-Fi Networks
        • Notifications of Devices Getting Offline
        • CPPLUS Link-Based Devices
        • Manage Matter Devices
      • Device Control
        • Sub-Device Control Through Zigbee Gateway
        • Multi-Control Linkage
        • Scheduled Tasks
        • Group Management
        • Device DP Parser
      • Smart Scenes
        • Scene Recommendation
      • Common API Methods
      • Integrate with Push Notifications
        • Integrate with FCM Push
        • Integrate with Xiaomi Push Notifications
        • Integrate with Huawei Push Notifications
      • Message Management
        • Configure Push Notifications
        • Message Capabilities
      • Error Codes
      • FAQ
      • Extension SDK
        • IPC SDK
          • IPC SDK Architecture
          • Fast Integration with IPC SDK for Android
          • IPCs
          • Device Pairing
          • Live Video Streaming
          • SD Card-Stored Video Playback
          • SD Card Management
          • Audio and Video Features
          • Cloud Storage
          • Cloud Storage Debugging Tool
          • Alert List
          • Video Alerts
          • Low Power Doorbell
          • Encrypted Images
          • Timeline View
          • P2P Capabilities
          • IPC SDK Automated Test Tool
          • IPC SDK Test Cases (Reference)
          • Error Codes
          • SDK Log
          • Changelog
        • Sweeper SDK
          • P2P Download from Robot Vacuums
          • Gyroscope and Visual Robot Vacuums
          • Laser Robot Vacuum
          • Voice Package Download
          • Changelog
          • Error Codes
          • Sample Code
        • Smart Lock SDK
          • Wi-Fi Smart Lock
          • Bluetooth Smart Lock
          • Wi-Fi Smart Lock Audio and Video Capabilities
          • Zigbee Lock
          • Smart Lock Basic API
          • Changelog
      • What is UI BizBundle SDK for iOS?
        • Preparation
        • Integrate with Framework
        • Home Management UI BizBundle
        • Device Pairing UI BizBundle
        • Generic Pairing BizBundle
        • Device Control UI BizBundle
        • Multi-Control Linkage UI BizBundle
        • Scene UI BizBundle
        • Group Management UI BizBundle
        • Device Details UI BizBundle
        • OTA UI BizBundle
        • IPC UI BizBundles
        • Cloud Storage UI BizBundle
        • Message Center UI BizBundle
        • FAQ UI BizBundle
        • Maps Service UI BizBundle
        • Voice Skills Account Linking UI BizBundle
        • Panel Multilingual BizBundle
        • Theme Color Configuration BizBundle
        • Sharing UI BizBundle
        • FAQ
      • Changelog
  1. Home
  2. App Development
  3. I OS
  4. AP Mode

AP Mode

Last Updated on: 2024-06-07 12:20:14

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.

Important

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.
  • Prev Doc Wi-Fi EZ Mode
  • Next Doc Wired Mode
This page contains content