Bluetooth Devices

Last Updated on : 2024-04-24 10:16:01download

The following Bluetooth solutions apply to app development.

Bluetooth type Description Example of smart devices
Bluetooth Low Energy (LE) A point-to-point connection is created between a Bluetooth or Bluetooth LE device and a mobile phone. Body fat scales, wrist-worn trackers, thermostats, electric toothbrushes, and smart locks.
Bluetooth mesh Enable many-to-many (m:m) device communications over a mesh network released by Bluetooth Special Interest Group (SIG). Cool white lights (C), cool and warm white lights (CW), white and colored lights (RGBCW), sockets, sensors, and other sub-devices.
Tuya mesh Tuya’s proprietary technology that enables Bluetooth devices to communicate over a mesh network. Similar to the products that use Bluetooth mesh, but with Tuya mesh.
Combo devices The devices that support Bluetooth and Wi-Fi combo can be paired over either Bluetooth or Wi-Fi. Bluetooth mesh gateways, IP cameras (IPCs), and devices that support Bluetooth and Wi-Fi combo.

In this case, Bluetooth LE technology is used when combo devices are paired over Bluetooth. For more information, see Pair combo devices.

Functional description

The following Bluetooth features are supported:

  • Device pairing
    • Scan and discover devices.
    • Pair devices.
  • Device management
    • Check the current device networking status.
    • Connect to devices.
    • Operate and remotely control devices.
    • Unbind devices.
  • Firmware OTA update
    • Check firmware versions.
    • Update firmware over the air.

Permissions

In iOS 13, Apple has replaced the original field NSBluetoothPeripheralUsageDescription that is used to request Bluetooth permissions with the field NSBluetoothAlwaysUsageDescription. The new field is added to info.plist.

<key>NSBluetoothAlwaysUsageDescription</key>
    <string></string>

<key>NSBluetoothPeripheralUsageDescription</key>
    <string></string>

Compatibility with iOS 12

For iOS 12, [[ThingSmartActivator sharedInstance] currentWifiSSID] cannot return a valid Wi-Fi service set identifier (SSID).

To query Wi-Fi information in Xcode 10, certain permissions are required. Set Access Wi-Fi Information to ON at Xcode > [Project Name] > Targets > [Target Name] > Capabilities.

Bluetooth Devices

Entry to the feature

Class name Description Capability
ThingSmartBLEManager Bluetooth LE class All features provided by Bluetooth LE SDKs, for example, device scanning, Bluetooth LE device pairing, combo device pairing, Bluetooth device operations, firmware update, and error codes.
ThingSmartBLEWifiActivator Combo device pairing class Methods required to pair combo devices.

A Bluetooth LE device is connected to a mobile phone through point-to-point connections over Bluetooth. Bluetooth wrist-worn trackers, Bluetooth headsets, and Bluetooth speakers can be connected in this way. Each device is concurrently connected to up to one mobile phone over Bluetooth. Each mobile phone is concurrently connected to up to six to seven Bluetooth LE devices.

Monitor Bluetooth status on mobile phones

API description

Sets a delegate to receive notifications of Bluetooth status changes on users’ mobile phones. For example, Bluetooth is enabled or disabled.

Example

Objective-C:

// Sets a delegate.
[ThingSmartBLEManager sharedInstance].delegate = self;

/**
 * The notification of the change in Bluetooth status.
 *
 * @param isPoweredOn The Bluetooth status. For example, it is enabled or disabled.
 */
- (void)bluetoothDidUpdateState:(BOOL)isPoweredOn {
    NSLog(@"Bluetooth status changes: %d", isPoweredOn ? 1 : 0);
}

Swift:

// Sets a delegate.
ThingSmartBLEManager.sharedInstance().delegate = self

/**
 * The notification of the change in Bluetooth status.
 *
 * @param isPoweredOn The Bluetooth status. For example, it is enabled or disabled.
 */
func bluetoothDidUpdateState(_ isPoweredOn: Bool) {

}

Scan for Bluetooth devices

Start scanning

API description

Scans for Bluetooth devices that keep broadcasting Bluetooth packets. When the app client finds these broadcast packets, it filters target devices based on the device information encoded by Tuya in the packets.

/**
 * Starts scanning.
 *
 * If inactivated devices are discovered, the result is returned by - (void)didDiscoveryDeviceWithDeviceInfo:(ThingBLEAdvModel *)deviceInfo in ThingSmartBLEManagerDelegate.
 *
 * If activated devices are discovered, they are automatically connected to the network and no scanning result is returned.
 *
 * @param clearCache Specifies whether to clear discovered devices.
 */
- (void)startListening:(BOOL)clearCache;

typedef NS_ENUM(NSInteger,ThingBLEScanType){
    ThingBLEScanTypeNoraml = 1 << 0, // 0001 1 indicates a common device.
    ThingBLEScanTypeQRCode = 1 << 1, // 0010 2 indicates a device that supports QR code pairing.
};

/**
 * Starts scanning.
 *
 * If inactivated devices are discovered, the result is returned by - (void)didDiscoveryDeviceWithDeviceInfo:(ThingBLEAdvModel *)deviceInfo in ThingSmartBLEManagerDelegate.
 *
 * If activated devices are discovered, they are automatically connected to the network and no scanning result is returned.
 *
 * @param scanType The type of scanning.
 * @param clearCache Specifies whether to clear discovered devices.
 */
- (void)startListeningWithType:(ThingBLEScanType)scanType cacheStatu:(BOOL)clearCache;

Parameters

Parameter Description
clearCache Specifies whether to clear discovered devices.
scanType The type of Bluetooth scanning.

Example

Objective-C:

// Sets a delegate.
[ThingSmartBLEManager sharedInstance].delegate = self;

// Starts scanning.
[[ThingSmartBLEManager sharedInstance] startListening:YES];

// Alternatively, starts scanning in the following way.
[[ThingSmartBLEManager sharedInstance] startListeningWithType:ThingBLEScanTypeNoraml cacheStatu:YES];

/**
 * An inactivated device is discovered.
 *
 * @param deviceInfo The model of the inactivated device information.
 */
- (void)didDiscoveryDeviceWithDeviceInfo:(ThingBLEAdvModel *)deviceInfo {
    // An inactivated device is discovered.
    // If an activated device is discovered, it is automatically connected without the current callback.
}

Swift:

ThingSmartBLEManager.sharedInstance().delegate = self

ThingSmartBLEManager.sharedInstance().startListening(true)
// Alternatively
ThingSmartBLEManager.sharedInstance().startListening(with: .normal, cacheStatu: true)

/**
 * An inactivated device is discovered.
 *
 * @param uuid The universally unique identifier (UUID) of the inactivated device.
 * @param productKey The product key of the inactivated device.
 */
func didDiscoveryDevice(withDeviceInfo deviceInfo: ThingBLEAdvModel) {
    // An inactivated device is discovered.
    // If an activated device is discovered, it is automatically connected without the current callback.
}

Properties of ThingBLEAdvModel

Property Type Description
uuid NSString The UUID that is used to uniquely identify the device.
productId NSString The product ID (PID).
mac NSString The media access control address (MAC address) of the device. It cannot be used as a unique code and is empty for iOS.
isActive Bool Indicates whether the device is activated. If a callback is invoked, the device is inactivated.
isSupport5G Bool Indicates whether the Bluetooth LE device supports connections to a router on the 5 GHz frequency band.
isProuductKey Bool Indicates whether productKey is supported.
bleProtocolV int The version of the Tuya Bluetooth protocol that is supported by the device.
isSupportMultiUserShare Bool Indicates whether a device is a shared device.
bleType Enum The type of device to distinguish different types of device protocols.

bleType indicates the type of device to be paired. If the value includes Wifi, a combo device is used. For more information, see Pair combo devices. Otherwise, a Bluetooth device is used. For more information, see Pair Bluetooth devices in this topic.

Value of bleType Device type
ThingSmartBLETypeBLE Bluetooth device
ThingSmartBLETypeBLEPlus Bluetooth device
ThingSmartBLETypeBLEWifi Wi-Fi and Bluetooth combo device
ThingSmartBLETypeBLESecurity Bluetooth device
ThingSmartBLETypeBLEWifiSecurity Wi-Fi and Bluetooth combo device
ThingSmartBLETypeBLEWifiPlugPlay Wi-Fi and Bluetooth combo device that supports pairing over Bluetooth if a Wi-Fi connection is unavailable.
ThingSmartBLETypeBLEZigbee Bluetooth Low Energy (LE) and Zigbee device
ThingSmartBLETypeBLELTESecurity LET Cat.1 and Wi-Fi comb device
ThingSmartBLETypeBLEBeacon Bluetooth LE beacon device
ThingSmartBLETypeBLEWifiPriorBLE Wi-Fi and Bluetooth combo device that supports pairing over Bluetooth if a Wi-Fi connection is unavailable.

Stop scanning

Stops device scanning. For example, if a pairing page is exited or a pairing process is completed, scanning can be stopped, so that the overall process will not be slowed down by the scanning task.

API description

/**
 * Stops scanning.
 *
 * @param clearCache Specifies whether to clear discovered devices.
 */
- (void)stopListening:(BOOL)clearCache;

Parameters

Parameter Description
clearCache Specifies whether to clear discovered devices.

Example

Objective-C:

[[ThingSmartBLEManager sharedInstance] stopListening:YES];

Swift:

ThingSmartBLEManager.sharedInstance().stopListening(true)

Pair Bluetooth LE devices

API description

Scans for and pairs inactivated devices, registers them to the cloud, and then records them in the list for the current home.

/**
 * Activates the device.
 * Registers the device to the cloud during pairing.
 */
- (void)activeBLE:(ThingBLEAdvModel *)deviceInfo
           homeId:(long long)homeId
          success:(void(^)(ThingSmartDeviceModel *deviceModel))success
          failure:(ThingFailureHandler)failure;

Parameters

Parameter Description
deviceInfo The information model of the device. It is the result returned by the scanning delegate method.
homeId The home ID.
success The success callback.
failure The failure callback.

Example

Objective-C:

[[ThingSmartBLEManager sharedInstance] activeBLE:deviceInfo homeId:homeId success:^(ThingSmartDeviceModel *deviceModel) {
        // The device is activated.

    } failure:^{
        // The failure callback.
    }];

Swift:

ThingSmartBLEManager.sharedInstance().activeBLE(<deviceInfo: deviceInfo, homeId: homeId, success: { (deviceModel) in
        // The device is activated.
        }) {
        // The failure callback.
        }

Pair combo devices

Pair a combo device

API description

Sends pairing data to an inactivated device through a Bluetooth channel after the device is discovered. The pairing result callback will be executed.

/**
 * Connects to the Bluetooth and Wi-Fi combo device.
 */
- (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 universally unique identifier (UUID) of a specified device.
homeId The home ID.
productId The product ID (PID).
ssid The name of the target Wi-Fi network.
password The password of the target Wi-Fi network.
timeout The interval at which polling is performed.
success The success callback.
failure The failure callback.

Example

Objective-C:

[[ThingSmartBLEWifiActivator sharedInstance] startConfigBLEWifiDeviceWithUUID:ThingBLEAdvModel.uuid homeId:homeId productId:ThingBLEAdvModel.productId ssid:ssid password:password timeout:100 success:^{
    // Pairing data is sent.
    } failure:^{
    // Failed to send pairing data.
    }];

Swift:

ThingSmartBLEWifiActivator.sharedInstance() .startConfigBLEWifiDevice(withUUID: ThingBLEAdvModel.uuid, homeId: homeId, productId:ThingBLEAdvModel.productId, ssid: ssid, password: password, timeout: 100, success: {
        // Pairing data is sent.
    }) {
        // Failed to send pairing data.
    }

Callback for an activated combo device

API description

Returns the pairing result by using the delegate method.

During the process of pairing multiple combo devices, they are paired one by one. In this case, after these devices are paired in the same call, only one successful callback is invoked.

Example

Objective-C:

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator didReceiveBLEWifiConfigDevice:(ThingSmartDeviceModel *)deviceModel error:(NSError *)error {
    if (!error && deviceModel) {
            // The device is paired.
    }

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

Swift:

func bleWifiActivator(_ activator: ThingSmartBLEWifiActivator, didReceiveBLEWifiConfigDevice deviceModel: ThingSmartDeviceModel?, error: Error?) {
    if (!error && deviceModel) {
            // The device is paired.
    }

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

Disable polling

Example

Objective-C:

// Called at the end of pairing.
[[ThingSmartBLEWifiActivator sharedInstance] stopDiscover];

Swift:

// Called at the end of pairing.
ThingSmartBLEWifiActivator.sharedInstance() .stopDiscover

Pair over Bluetooth due to unavailable Wi-Fi

Certain combo devices support pairing over Bluetooth if Wi-Fi connections are unavailable. In case a combo device cannot connect to a Wi-Fi router or the target router cannot connect to the internet, the device can be paired as a Bluetooth device. This method provides the channel to pair the device over Bluetooth.

The bleType field of ThingBLEAdvModel can be used to check whether a combo device supports pairing over Bluetooth if Wi-Fi connections are unavailable. If the value is ThingSmartBLETypeBLEWifiPlugPlay or ThingSmartBLETypeBLEWifiPriorBLE, the device supports this capability. Otherwise, it does not support this capability.

API description

/**
 * The channel to pair the combo device over Bluetooth.
 */
- (void)activatorDualDeviceWithBleChannel:(ThingBLEAdvModel *)advModel
                                   homeId:(long long)homeId
                                    token:(NSString *)token
                                  success:(void(^)(ThingSmartDeviceModel *deviceModel))success
                                  failure:(ThingFailureError)failure;

Parameters

Parameter Description
advModel The information model of the device. It is the result returned by the scanning delegate method.
homeId The home ID.
token The pairing token.
success The success callback.
failure The failure callback.

Example

Objective-C:

[[ThingSmartBLEManager sharedInstance] activatorDualDeviceWithBleChannel:advModel homeId:homeId token:token success:^(ThingSmartDeviceModel * _Nonnull device) {
                    // The device is paired.
    } failure:^(NSError *error) {
                    // Failed to pair the device.
    }];

Swift:

ThingSmartBLEManager.sharedInstance().activatorDualDevice(withBleChannel: advModel, homeId: homeId, token: token) { (ThingSmartDeviceModel) in
            // The device is paired.
        } failure: { (Error?) in
            // Failed to pair the device.
        }

Pass in the substring [token substringWithRange:NSMakeRange(2, 8)] of the returned token value. Otherwise, an error message will be returned to indicate that the length of the token string exceeds the upper limit.

Activate a combo device paired over Bluetooth in the cloud

Activates a combo device paired over Bluetooth in the cloud through a Wi-Fi channel.

In this call, the device must be connected to the app over Bluetooth. The wifiEnable field of deviceModel.meta indicates whether the device is activated in the cloud. The default value false indicates that the Wi-Fi channel of the device is not activated.

API description

/**
 * Activates the combo device through a Wi-Fi channel in the cloud after it is paired over Bluetooth.
 */
- (void)activeDualDeviceWifiChannel:(NSString *)devId
                               ssid:(NSString *)ssid
                           password:(NSString *)password
                            timeout:(NSTimeInterval)timeout
                            success:(void(^)(ThingSmartDeviceModel *deviceModel))success
                            failure:(ThingFailureError)failure;

Parameters

Parameter Description
devId The device ID.
ssid The name of the target Wi-Fi network.
password The password of the target Wi-Fi network.
timeout The interval at which polling is performed.
success The success callback.
failure The failure callback.

Example

Objective-C:

[[ThingSmartBLEManager sharedInstance] activeDualDeviceWifiChannel:devId ssid:ssid password:password timeout:timeout success:^(ThingSmartDeviceModel * _Nonnull device) {
                    // The device is activated in the cloud.
    } failure:^(NSError *error) {
                    // Failed to activate the device in the cloud.
    }];

Swift:

ThingSmartBLEManager.sharedInstance().activeDualDeviceWifiChannel(devId, ssid: ssid, password: password, timeout: timeout) { (ThingSmartDeviceModel) in
            // The device is activated in the cloud.
        } failure: { (Error?) in
            // Failed to activate the device in the cloud.
        }

Optimize pairing of combo devices

In the optimized pairing solution, 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.

Prerequisites

The TuyaOS version of the firmware built into the target device must be v3.6.1 or later.

Scan for Wi-Fi networks

API description

Connects to a Bluetooth device by UUID and scans for Wi-Fi networks for the supported ones.

- (void)connectAndQueryWifiListWithUUID:(NSString *)UUID
                                success:(ThingSuccessHandler)success
                                failure:(ThingFailureError)failure;

Parameters

Parameter Description
uuid The universally unique identifier (UUID) of the device.
success The success callback.
failure The failure callback.

Example

Objective-C:

[[ThingSmartBLEWifiActivator sharedInstance] connectAndQueryWifiListWithUUID:UUID success:^{
  // The command is sent.
} failure:^(NSError *error) {
  // Failed to send the command.
}];

Swift:

ThingSmartBLEWifiActivator.sharedInstance().connectAndQueryWifiList(UUID: UUID) { _ in
  // The command is sent.
} failure: { (Error?) in
  // Failed to send the command.
}

Callback for exceptional device status

API description

Invokes the callback by using the delegate method if the device is not ready for pairing.

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator notConfigStateWithError:(NSError *)error;

Example

Objective-C:

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator notConfigStateWithError:(NSError *)error {
  // The device is not ready for pairing.
}

Swift:

func bleWifiActivator(_ activator: ThingSmartBLEWifiActivator, notConfigStateWithError error: Error) {
  // The device is not ready for pairing.
}

Callback for Wi-Fi networks scanning

API description

Returns the result of discovered Wi-Fi networks by using the delegate method.

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator didScanWifiList:(nullable NSArray *)wifiList uuid:(nullable NSString *)uuid error:(nullable NSError *)error;

Example

Objective-C:

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator didScanWifiList:(NSArray *)wifiList uuid:(NSString *)uuid error:(nonnull NSError *)error{
    if (error) {
    // The failure callback.
    } else {
    // The success callback.
    }
}

Swift:

func bleWifiActivator(_ activator: ThingSmartBLEWifiActivator, didScanWifiList wifiList: [Any]?, uuid: String?, error: Error?) {
    if let e = error {
      // The failure callback.
    } else {
      // The success callback.
    }
}

Start pairing after Wi-Fi networks scanning

API description

Starts pairing after the device is connected to a discovered Wi-Fi network. This API method is designed to minimize resource usage and avoid repeated connections.

- (void)pairDeviceWithUUID:(NSString *)UUID
                     token:(NSString *)token
                      ssid:(NSString *)ssid
                       pwd:(NSString *)pwd
                   timeout:(long)timeout;

Parameters

Parameter Description
uuid The UUID of the device.
token The pairing token.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.
timeout The pairing timeout period.

Example

Objective-C:

        [[ThingSmartBLEWifiActivator sharedInstance] pairDeviceWithUUID:@"uuid"
                                                                  token:@"token"
                                                                   ssid:@"ssid"
                                                                    pwd:@"password"
                                                                timeout:120];

Swift:

let activator = ThingSmartBLEWifiActivator.sharedInstance()
activator.pairDevice(withUUID: "UUID", token: "token", ssid: "ssid", pwd: "password", 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)resumeConfigBLEWifiDeviceWithActionType:(ThingBLEWifiConfigResumeActionType)actionType
                                   configModel:(ThingBLEWifiConfigModel *)configModel;

Parameters

Parameter Description
actionType The pairing mode to be restarted.
configModel The pairing token.

ThingBLEWifiConfigModel

Parameter Description
uuid The UUID.
token The pairing token.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.

Example

Objective-C:

ThingBLEWifiConfigModel *configModel = [ThingBLEWifiConfigModel new];
configModel.uuid = @"UUID";
configModel.ssid = @"ssid";
configModel.password = @"password";
self.uuid = activatorParam.bleWifiActivatorParams.uuid;
[[ThingSmartBLEWifiActivator sharedInstance] resumeConfigBLEWifiDeviceWithActionType:ThingBLEWifiConfigResumeActionTypeSetWifi configModel:configModel];

Swift:

let model = ThingBLEWifiConfigModel()
model.uuid = "uuid"
model.ssid = "ssid"
model.password = "password"
activator.resumeConfigBLEWifiDevice(with: .setWifi, configModel: model)

Bulk pair combo devices

When pairing a combo device in the traditional way, the SDK maintains the Bluetooth connection with the device throughout the process where the device will report the pairing status.

When bulk pairing devices, the SDK will disconnect the Bluetooth connection from a device after the device acknowledges the receipt of the pairing information. The SDK then proceeds to pair the next device.

Entry to the feature

Class name Description Capability
ThingSmartBLEWifiMultier The management class for bulk pairing combo devices Bulk add and remove devices to pair. Start and stop bulk pairing.

Add devices to pair

API description

Add a device to the pairing queue.

- (void)appendDevice:(ThingBLEAdvModel *)adv;

Parameters

Parameter Description
adv The model object returned by Bluetooth scan.

Example

Objective-C:

- (void)selectDeviceInfo:(ThingBLEAdvModel *)deviceInfo {
    [self.bleWifiMultier appendDevice:deviceInfo];
}

Swift:

func select(deviceInfo: ThingBLEAdvModel) {
    bleWifiMultier.appendDevice(deviceInfo)
}

Remove devices to pair

API description

Remove a device from the pairing queue.

If the removal operation is triggered after the SDK has been connected to the device, it will not work, and the device will continue pairing.

- (void)removeDevice:(ThingBLEAdvModel *)adv;

Parameters

Parameter Description
adv The model object returned by Bluetooth scan.

Example

Objective-C:

- (void)removeDevice:(ThingBLEAdvModel *)advModel {
    [self.bleWifiMultier removeDevice:advModel];
}

Swift:

func remove(advModel: ThingBLEAdvModel) {
    bleWifiMultier.removeDevice(advModel)
}

Set pairing information and start bulk pairing

API description

Set the Wi-Fi SSID, password, and pairing token for bulk pairing.

@property (nonatomic, strong) ThingSmartBLEWifiConfiguration *config;

- (void)startConfigWifi;

Parameters

Parameter Description
config The pairing information configurations.

ThingSmartBLEWifiConfiguration

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

Example

Objective-C:

- (void)startConfigWifiSsid:(NSString *)ssid
                   password:(NSString *)password
                      token:(NSString *)token {
    ThingSmartBLEWifiConfiguration *config = [ThingSmartBLEWifiConfiguration new];
    config.ssid = ssid;
    config.pwd = password;
    config.token = token;

    self.bleWifiMultier.config = config;
		self.bleWifiMultier.delegate = self;
    [self.bleWifiMultier startConfigWifi];
}

Swift:

func startConfig(ssid: String, pwd: String, token: String) {
    let config = ThingSmartBLEWifiConfiguration()
    config.ssid = ssid
    config.pwd = pwd
    config.token = token

    bleWifiMultier.delegate = self
    bleWifiMultier.config = config
    bleWifiMultier.startConfigWifi()
}

Stop bulk pairing

API description

Stop a bulk pairing task.

Tasks that have already started cannot be stopped. Only pending tasks can be stopped.

- (void)stopConfigWifi;

Example

Objective-C:

- (void)stopConfigWifi {
    [self.bleWifiMultier stopConfigWifi];
}

Swift:

func stopConfigWifi() {
    bleWifiMultier.stopConfigWifi()
}

Device pairing callback

API description

This delegate method will be triggered when a device is paired successfully.

- (void)bleWifiMuliter:(ThingSmartBLEWifiMultier *)muliter didReceiveBLEWifiConfigDevice:(nullable ThingSmartDeviceModel *)deviceModel error:(nullable NSError *)error;

Manage Bluetooth devices

Check online status of a device

API description

Checks whether a device is locally connected over Bluetooth.

- (BOOL)deviceStatueWithUUID:(NSString *)uuid;

For a combo device, if the isOnline field of ThingSmartDeviceModel is true, the device is online.

  • If the isOnline field of ThingSmartDeviceModel is true and the current method returns true, the combo device is running over Bluetooth.
  • If the isOnline field of ThingSmartDeviceModel is true and the current method returns false, the combo device is running over Wi-Fi.

Parameters

Parameter Description
uuid The universally unique identifier (UUID) of a specified device.
ThingSmartDeviceModel.uuid

Example

Objective-C:

NSString *uuid = self.deviceModel.uuid;
BOOL isOnline = [ThingSmartBLEManager.sharedInstance deviceStatueWithUUID:uuid];

Swift:

let uuid = self.deviceModel.uuid;
var isOnline:BOOL = ThingSmartBLEManager.sharedInstance().deviceStatue(withUUID: uuid)

Connect to an offline device

API description

Connects to an offline device.

- (void)connectBLEWithUUID:(NSString *)uuid
                productKey:(NSString *)productKey
                   success:(ThingSuccessHandler)success
                   failure:(ThingFailureHandler)failure;

Parameters

Parameter Description
uuid The universally unique identifier (UUID) of a specified device.
ThingSmartDeviceModel.uuid
productKey The product ID (PID).
success The success callback.
failure The failure callback.

Example

Objective-C:

NSString *uuid = self.deviceModel.uuid;
[[ThingSmartBLEManager sharedInstance] connectBLEWithUUID:uuid productKey:@"your_device_productKey" success:success failure:failure];

Swift:

let uuid = self.deviceModel.uuid;
ThingSmartBLEManager.sharedInstance().connectBLE(withUUID: @"your_device_uuid", productKey: @"your_device_productKey", success: success, failure: failure)

Disconnect a device

API description

Disconnects from an online device.

- (void)disconnectBLEWithUUID:(NSString *)uuid
                      success:(ThingSuccessHandler)success
                      failure:(ThingFailureError)failure;

Parameters

Parameter Description
uuid The universally unique identifier (UUID) of a specified device.
ThingSmartDeviceModel.uuid
success The success callback.
failure The failure callback.

Example

Objective-C:

NSString *uuid = self.deviceModel.uuid;
  [[ThingSmartBLEManager sharedInstance] disconnectBLEWithUUID:uuid success:success failure:failure];

Swift:

  let uuid = self.deviceModel.uuid;
  ThingSmartBLEManager.sharedInstance().disconnectBLE(withUUID: uuid, success: success, failure: failure)

Send device DPs

Sends data point (DP) data to control devices. For more information, see Device Control.

Query a device name

API description

Returns a device name after the broadcast packet of the device is discovered and the broadcast packet object is obtained.

/**
 * Returns the device name.
 */
- (void)queryDeviceInfoWithUUID:(NSString *)uuid
                      productId:(NSString *)productId
                        success:(ThingSuccessDict)success
                        failure:(ThingFailureError)failure;

Parameters

Parameter Description
uuid The universally unique identifier (UUID) of a specified device.
ThingBLEAdvModel.uuid
productId The product ID (PID).
success The success callback.
failure The failure callback.

Example

Objective-C:

[[ThingSmartBLEManager sharedInstance] queryNameWithUUID:bleAdvInfo.uuid productId:bleAdvInfo.productId success:^(NSDictionary *dict) {
        // The device name is returned.

    } failure:^{
        // Failed to return the device name.
    }];

Swift:

ThingSmartBLEManager.sharedInstance().queryName(withUUID: bleAdvInfo.uuid, productId: bleAdvInfo.productId, success: { (dict) in
        // The device name is returned.
}, failure: { (error) in
        // Failed to return the device name.
})

Update device firmware

Starting from v3.35.5, the device firmware update is optimized and simplified. For more information, see Firmware Update.

If you do not opt for the simplified OTA process, continue with the section below.

Query device update information

For more information, see Get Firmware Update Information.

OTA firmware update

API description

Sends a firmware update package over the air to install on a device. Before this call, an API request must be made to return firmware information from the cloud.

/**
 * Send the OTA update package over Bluetooth to update the firmware. Make sure the device has been connected over Bluetooth before the update.
 */
- (void)sendOTAPack:(NSData *)otaData
        deviceModel:(ThingSmartDeviceModel *)deviceModel
       upgradeModel:(ThingSmartFirmwareUpgradeModel *)upgradeModel
            success:(ThingSuccessHandler)success
            failure:(ThingFailureError)failure;

Parameters

Parameter Description
otaData The data of the firmware update.
deviceModel The device model.
upgradeModel The firmware information model.
success The success callback.
failure The failure callback.

Example

Objective-C:

- (void)getFirmwareUpgradeInfo {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];

    [self.device checkFirmwareUpgrade:^(NSArray<ThingSmartFirmwareUpgradeModel *> *upgradeModelList) {
        NSLog(@"checkFirmwareUpgrade success");
    } failure:^(NSError *error) {
        NSLog(@"checkFirmwareUpgrade failure: %@", error);
    }];
}

// If an update is available, ThingSmartFirmwareUpgradeModel.url is the URL to download the update package.
// Download the update from the specified URL, convert the download to data, and then send it to the SDK for installation.
// deviceModel: The model of the device to be updated.
// data: The downloaded update package.
// upgradeModel: The information about the firmware update.
[[ThingSmartBLEManager sharedInstance] sendOTAPack:data deviceModel:deviceModel upgradeModel:upgradeModel success:^{
       NSLog(@"OTA successful");
    } failure:^{
       NSLog(@"OTA failed");
}];

Swift:

func getFirmwareUpgradeInfo() {
    device?.checkFirmwareUpgrade({ (upgradeModelList) in
        print("checkFirmwareUpgrade success");
    }, failure: { (error) in
        if let e = error {
            print("checkFirmwareUpgrade failure: \(e)");
        }
    })
}

// If an update is available, ThingSmartFirmwareUpgradeModel.url is the URL to download the update package.
// Download the update from the specified URL, convert the download to data, and then send it to the SDK for installation.
// deviceModel: The model of the device to be updated.
// data: The downloaded update package.
// upgradeModel: The information about the firmware update.
ThingSmartBLEManager.sharedInstance().sendOTAPack(data, deviceModel: deviceModel, upgradeModel: upgradeModel, success: {
    print("OTA successful");
}) {
    print("OTA failed");
}

Error codes

Error code Description
1 The format of the packet received by the device is wrong.
2 The device failed to find a router.
3 The password of the target Wi-Fi network is wrong.
4 The device failed to connect to a router.
5 Failed to get a Dynamic Host Configuration Protocol (DHCP)-assigned IP address.
6 Failed to connect the device to the cloud.
100 The pairing process is canceled by the user.
101 An error occurred while connecting to the device over Bluetooth.
102 An error occurred while scanning for Bluetooth devices.
103 Failed to enable a Bluetooth channel.
104 Failed to query Bluetooth device information.
105 Failed to pair devices over Bluetooth.
106 The pairing task timed out.
107 Failed to send Wi-Fi information.
108 The token has expired.
109 Failed to query the key with which Bluetooth connections are encrypted.
110 The specified device does not exist.
111 Failed to register the device in the cloud.
112 Failed to activate the device in the cloud.
113 The specified device has been bound in the cloud.
114 The current connection is manually closed.
115 Failed to query device information in the cloud.
116 The specified device is being paired in another mode.
117 The OTA update failed.
118 The OTA update timed out.
119 Failed to verify the parameters for Wi-Fi pairing.
120 Failed to send the key information.
121 Failed to find an object to be connected over Bluetooth.
122 No Bluetooth object is found.
123 The visitor account does not support strong binding.
124 A generic Bluetooth error occurred while processing your request.
125 Failed to enable Notify.
126 A device error occurred while processing hardware encryption.
127 A cloud error occurred while processing hardware encryption.
128 Failed to pair the non-LTE Cat.1 combo device. The password is not entered.
129 Failed to get the pairing token.
130 A pairing parameter error occurred while processing your request.
131 Failed to get the Wi-Fi information of the device.
132 The API request for Plug-and-Play (PnP) pairing has failed.
133 Failed to send the device activation information.
134 A timeout error was caused by the failure to get the device online in the cloud.
135 A timeout error occurred while querying device information.
136 A timeout error occurred while processing the pairing command.
137 A timeout error occurred while querying the Wi-Fi information.
138 A timeout error occurred while sending device activation information.
139 Failed to query device information from the cloud during activation.
140 Unauthorized to get the binding status.
141 Failed to pull configuration certificate information for PSK3.0 devices.
142 Failed to send Wi-Fi commands to PSK3.0 combo devices.
143 Failed to send the command for PSK3.0 PnP activation in the cloud.
200 An error occurred when the device responded to the OTA update command.
201 Failed to verify the OTA file for the device.
202 The OTA update offset has an exception.
203 Failed to acknowledge the reception of a single OTA update package.
204 Failed to send the firmware for OTA update.
205 The device finally reported an OTA update failure.
206 The OTA update timed out.
207 Failed to transfer big data.
300 A Media Transfer Protocol (MTP) error occurred while transmitting Bluetooth packets.
301 Failed to send PnP product information to the device.
400 Bluetooth connection timed out.
401 An error occurred while receiving the information about a Zigbee sub-device.
402 An error occurred while receiving the command about a Zigbee sub-device.
403 The Zigbee gateway reported a pairing error.
404 The Zigbee gateway reported a data parsing error.
405 Failed to send gateway information during Zigbee combo pairing.
406 The device reported invalid gateway information during Zigbee combo pairing.
407 Parameter errors.
600 Failed to control the device. The device is being updated over the air.
601 Failed to control the device. The device is offline.