Wi-Fi AP Mode

Last Updated on : 2024-08-21 10:02:48download

This topic describes the access point (AP) to pair devices. It is a connection capability for pairing over Wi-Fi. In the pairing process, a mobile phone connects to the AP of the smart device and broadcasts the Wi-Fi credentials and pairing token over the LAN to enable the smart device to get this information for network connection and pairing. 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.

The ThingSmartBusinessExtensionKit component offers more features than the ThingSmartActivator. If you are still using ThingSmartActivator, please refer to this document.

## Pairing process
AppBizBundle SDKCloudDeviceRouterSwitch to AP modeand wait for appconnection.Wi-Fi LED indicatorblinks slowly.Request a pairing token.1Request a pairing token.2Return the pairing token.3Return the pairing token.4User enters theWi-Fi password.Guide the user toconnect to thedevice's AP.5Connect to the device's AP.6AP is connected.7Send the Wi-Fi credentials(SSID and password) andpairing token.8Send the Wi-Fi credentials (SSID and password) andpairing token.9Disconnect the AP.10Indicator is off.Connect to the router.11Connected successfully.12Indicator is steadyon.Request device activation.13Device is activated.14Return the device list.15Return the device list.16AppBizBundle SDKCloudDeviceRouterWi-Fi AP Mode Pairing

Register the pairing type

When the device pairing service is initialized, register the pairing type, which is ThingSmartActivatorTypeAPModel.

API description

/// Initialize network configuration types
/// @param typeList Network configuration types
- (void)registerWithActivatorList:(NSArray<ThingSmartActivatorTypeModel *>*)typeList;

Parameter description

Parameters Description
typeList The list of pairing types.

Get a token

The SDK gets a pairing token from the cloud before it can start the pairing process. 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;

Parameter description

Parameters 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.

Start searching

Pass in the registered typeList to start searching.

API description

/// Start searching
/// @param typeList Network configuration types
- (void)startSearch:(NSArray <ThingSmartActivatorTypeModel *>*)typeList;

Parameter description

Parameters Description
typeList The list of pairing types.

Stop searching

API description

/// Stop searching
/// @param typeList Network configuration types
/// @param clearCache Whether to clear the cache
- (void)stopSearch:(NSArray <ThingSmartActivatorTypeModel *>*)typeList clearCache:(BOOL)clearCache;

Parameter description

Parameters Description
typeList The list of pairing types.
clearCache Specifies whether to clear the cache search result.

Device search callback

After the device is paired, the callback returns the device information. If the operation fails, the callback returns the error message.

Device discovery callback

API description

/// Device search callback
/// @param service Search instance
/// @param type Network configuration type
/// @param device Discovered device
/// @param errorModel Error callback
- (void)activatorService:(id<ThingSmartActivatorSearchProtocol>)service
            activatorType:(ThingSmartActivatorTypeModel *)type
             didFindDevice:(nullable ThingSmartActivatorDeviceModel *)device
                     error:(nullable ThingSmartActivatorErrorModel *)errorModel;

Parameter description

Parameters Description
service The pairing service.
type The pairing type. ThingSmartActivatorTypeAPModel is returned.
device The discovered device. The device model is returned on success. nil is returned on failure.
errorModel This model is returned if pairing fails or times out. nil is returned on success.

Device information update callback

API description

/// Device information update or device rediscovered on a different channel
/// @param service Search instance
/// @param type Network configuration type
/// @param device Device model
- (void)activatorService:(id<ThingSmartActivatorSearchProtocol>)service
            activatorType:(ThingSmartActivatorTypeModel *)type
           didUpdateDevice:(ThingSmartActivatorDeviceModel *)device;

Parameter description

Parameters Description
service The pairing service.
type The pairing type. ThingSmartActivatorTypeAPModel is returned.
device The updated device information.

Error codes

ThingSmartActivatorErrorModel is returned if pairing fails or times out.

@interface ThingSmartActivatorErrorModel : NSObject
@property (nonatomic, strong) ThingSmartActivatorDeviceModel *deviceModel;
@property (nonatomic) NSError *error;
@end

ThingSmartActivatorDiscoveryError includes the definition of error codes. The following table lists the common error codes.

Error codes Description
ThingSmartActivatorDiscoveryErrorTimeout Pairing timeout.
ThingSmartActivatorDiscoveryErrorDeviceAlreadyBound Strong binding error. The device is already bound with a user. Pairing can work only after the device is unbound from the current user.
ThingSmartActivatorDiscoveryErrorAPPUnsupportProduct The app used for pairing is not bound with the product.
ThingSmartActivatorDiscoveryErrorTokenExpired Token expired.
ThingSmartActivatorDiscoveryErrorGuestNotSupportStrongBind A guest account is not allowed to pair a device of strong binding.
ThingSmartActivatorDiscoveryErrorRemoteApiParamIllegal Invalid parameter.

Example

Swift:

class APmodeConfigurationVC: UITableViewController {
    @IBOutlet weak var ssidTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    private var token: String = ""
    private var apType: ThingSmartActivatorTypeAPModel = {
        let type = ThingSmartActivatorTypeAPModel()
        type.type = ThingSmartActivatorType.AP
        type.typeName = NSStringFromThingSmartActivatorType(ThingSmartActivatorType.AP)
        type.timeout = 120
        return type
    }()

    lazy var discovery: ThingSmartActivatorDiscovery = {
        let discovery = ThingSmartActivatorDiscovery()
        discovery.register(withActivatorList: [self.apType])
        discovery.setupDelegate(self)
        discovery.loadConfig()
        return discovery
    }()

    private func startConfiguration() {
        guard let homeID = Home.current?.homeId else { return }
        SVProgressHUD.show(withStatus: NSLocalizedString("Requesting for Token", comment: ""))

        ThingSmartActivator.sharedInstance()?.getTokenWithHomeId(homeID, success: { [weak self] (token) in
            guard let self = self else { return }
            self.token = token ?? ""
            self.startConfiguration(with: self.token)
        }, failure: { (error) in
            let errorMessage = error?.localizedDescription ?? ""
            SVProgressHUD.showError(withStatus: errorMessage)
        })
    }

    private func startConfiguration(with token: String) {
        SVProgressHUD.show(withStatus: NSLocalizedString("Configuring", comment: ""))
        guard let homeID = Home.current?.homeId else { return }
        let ssid = ssidTextField.text ?? ""
        let password = passwordTextField.text ?? ""
        apType.ssid = ssid;
        apType.password = password;
        apType.token = self.token;
        apType.spaceId = homeID
        discovery.startSearch([apType])
    }
}
extension APmodeConfigurationVC: ThingSmartActivatorSearchDelegate {

    func activatorService(_ service: ThingSmartActivatorSearchProtocol, activatorType type: ThingSmartActivatorTypeModel, didFindDevice device: ThingSmartActivatorDeviceModel?, error errorModel: ThingSmartActivatorErrorModel?) {
        if (errorModel != nil) {
            // Error
            SVProgressHUD.showError(withStatus: errorModel?.error.localizedDescription)
            return
        }

        if (device != nil) {
            if device?.step == ThingActivatorStep.found {
                // device find
            }
        }
    }

    func activatorService(_ service: ThingSmartActivatorSearchProtocol, activatorType type: ThingSmartActivatorTypeModel, didUpdateDevice device: ThingSmartActivatorDeviceModel) {
        if device.step == ThingActivatorStep.intialized {
            // Success
            let name = device.name
            SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Successfully Added \(name)", comment: "Successfully added one device."))
            navigationController?.popViewController(animated: true)
        }
    }
}

Objective-C:

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

/// Start config
- (void)startConfigWifi:(NSString *)token {
  ThingSmartActivatorTypeAPModel *apModel  = [[ThingSmartActivatorTypeAPModel alloc] init];
  apModel.type = ThingSmartActivatorTypeAP;
  apModel.typeName = NSStringFromThingSmartActivatorType(ThingSmartActivatorTypeAP);
  apModel.timeout = 120;
  apModel.ssid = ssid;
  apModel.password = password;
  apModel.token = token;
  apModel.spaceId = homeId;

  [self.discovery registerWithActivatorList:@[apModel]];
  [self.discovery setupDelegate:self];

  [self.discovery startSearch:@[apModel]];
}

- (void)activatorService:(id<ThingSmartActivatorSearchProtocol>)service activatorType:(ThingSmartActivatorTypeModel *)type didFindDevice:(ThingSmartActivatorDeviceModel *)device error:(ThingSmartActivatorErrorModel *)errorModel {

    if (errorModel) {
        [self _connectWifiError:errorModel];
        return;
    }

    if (device) {
        [self _handleDevice:device];
    }
}

- (void)activatorService:(id<ThingSmartActivatorSearchProtocol>)service activatorType:(ThingSmartActivatorTypeModel *)type didUpdateDevice:(ThingSmartActivatorDeviceModel *)device {
    if (device) {
        [self _handleDevice:device];
    }
}

- (void)_handleDevice:(ThingSmartActivatorDeviceModel *)device {
    ThingActivatorStep step = device.step;

    if (step == ThingActivatorStepFound) {
      // discover the device
    } else if (step == ThingActivatorStepRegisted) {
      // device registration
    } else if (step == ThingActivatorStepIntialized) {
        /// activated successfully
    }
}

- (ThingSmartActivatorDiscovery *)discovery {
    if (!_discovery) {
        _discovery = [[ThingSmartActivatorDiscovery alloc] init];
    }
    return _discovery;
}