Bluetooth Technology Stack

Last Updated on : 2024-06-26 09:48:29download

The following Bluetooth solutions apply to app development.

Bluetooth type Description Example
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 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 Devices that support both Bluetooth and other protocols, such as Wi-Fi and Bluetooth LE combo, can be paired over Bluetooth. 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 Bluetooth LE devices.

API 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 update
    • Check firmware versions
    • Update firmware over the air (OTA)

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 Technology Stack

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

Sample code

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.

Sample code

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

Description 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 bound. If a callback is invoked, the device is not paired.
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 LE 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 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.

Sample code

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.

Sample code

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

Join a network

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.

Sample code

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.

Sample code

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

Sample code

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.

Use the bleType of ThingBLEAdvModel to determine whether the discovered device can be paired 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.

Sample code

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.

Sample code

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 UUID
success The success callback.
failure The failure callback.

Sample code

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;

Sample code

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 network 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;

Sample code

Objective-C:

- (void)bleWifiActivator:(ThingSmartBLEWifiActivator *)activator didScanWifiList:(NSArray *)wifiList uuid:(NSString *)uuid error:(nonnull NSError *)error{
    if (error) {
    // Failed to scan for the list of Wi-Fi networks.
    } else {
    // A list of Wi-Fi networks is obtained.
    }
}

Swift:

func bleWifiActivator(_ activator: ThingSmartBLEWifiActivator, didScanWifiList wifiList: [Any]?, uuid: String?, error: Error?)  {
    if let e = error {
      // Failed to scan for the list of Wi-Fi networks.
    } else {
      // A list of Wi-Fi networks is obtained.
    }
}

Start pairing after Wi-Fi network 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 UUID
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.

Sample code

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

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

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 UUID
token The pairing token.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.

Sample code

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)

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.

Sample code

Objective-C:

BOOL isOnline = [ThingSmartBLEManager.sharedInstance deviceStatueWithUUID:uuid];

Swift:

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.
productKey The product ID (PID).
success The success callback.
failure The failure callback.

Sample code

Objective-C:

[[ThingSmartBLEManager sharedInstance] connectBLEWithUUID:@"your_device_uuid" productKey:@"your_device_productKey" success:success failure:failure];

Swift:

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.
success The success callback.
failure The failure callback.

Sample code

Objective-C:

  [[ThingSmartBLEManager sharedInstance] disconnectBLEWithUUID:@"your_device_uuid" success:success failure:failure];

Swift:

  ThingSmartBLEManager.sharedInstance().disconnectBLE(withUUID: @"your_device_uuid", success: success, failure: failure)

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.
productId The product ID (PID).
success The success callback.
failure The failure callback.

Sample code

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

A unified method for OTA firmware updates has been implemented in SDK v3.35.5 and later versions. For more information, see Firmware Update.

Query device update information

API description

- (void)getFirmwareUpgradeInfo:(nullable void (^)(NSArray <ThingSmartFirmwareUpgradeModel *> *upgradeModelList))success failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
success The success callback. A list of firmware updates is returned.
failure The failure callback.

Data model of ThingSmartFirmwareUpgradeModel

Field Type Description
desc NSString The description of the firmware update.
typeDesc NSString The type of device.
upgradeStatus NSInteger The update status. Valid values:
  • 0: No update available
  • 1: An update available
  • 2: Updating
  • 5: Wait for the device to wake up
version NSString The target firmware version.
upgradeType NSInteger The type of update. Valid values:
  • 0: Update notification
  • 2: Forced update
  • 3: Check for update
url NSString The URL to download a Bluetooth firmware update.
fileSize NSString The size of the firmware update package. Unit: bytes.
md5 NSString The MD5 (Message-Digest algorithm 5) hash value of the firmware.
upgradingDesc NSString The description of the firmware update in progress.

Sample code

Objective-C:

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

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

Swift:

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

Update firmware over the air

API description

Sends a firmware update package to a device to update it if a new OTA update is available. Before this call, an API request must be made to return firmware information from the cloud.

/**
 * Sends an OTA package to update the firmware. Before the update, the device must be connected over Bluetooth.
 */
- (void)sendOTAPack:(NSString *)uuid
                pid:(NSString *)pid
            otaData:(NSData *)otaData
            success:(ThingSuccessHandler)success
            failure:(ThingFailureHandler)failure;

Parameters

Parameter Description
uuid The universally unique identifier (UUID) of a specified device.
pid The product ID (PID).
otaData The data of the firmware update.
success The success callback.
failure The failure callback.

Sample code

Objective-C:

- (void)getFirmwareUpgradeInfo {
    // self.device = [ThingSmartDevice deviceWithDeviceId:@"your_device_id"];
    [self.device getFirmwareUpgradeInfo:^(NSArray<ThingSmartFirmwareUpgradeModel *> *upgradeModelList) {
        NSLog(@"getFirmwareUpgradeInfo success");
    } failure:^(NSError *error) {
        NSLog(@"getFirmwareUpgradeInfo failure: %@", error);
    }];
}

// The firmware update is available and the download URL is indicated by ThingSmartFirmwareUpgradeModel.url.
 // The downloaded firmware update package is converted into data and passed to the SDK to implement the update.
// deviceModel: the model of the device to be updated.
// data: the downloaded firmware update package.
[[ThingSmartBLEManager sharedInstance] sendOTAPack:deviceModel.uuid pid:deviceModel.pid otaData:data success:^{
       NSLog(@"OTA update is successful.");
    } failure:^{
       NSLog(@"OTA update failed.");
}];

Swift:

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

// The firmware update is available and the download URL is indicated by ThingSmartFirmwareUpgradeModel.url.
 // The downloaded firmware update package is converted into data and passed to the SDK to implement the update.
// deviceModel: the model of the device to be updated.
// data: the downloaded firmware update package.
ThingSmartBLEManager.sharedInstance().sendOTAPack(deviceModel.uuid, pid: deviceModel.pid, otaData: data, success: {
    print("OTA update is successful.");
}) {
    print("OTA update failed.");
}

Error code

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 has occurred while connecting to the device over Bluetooth.
102 An error has 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 An error has occurred while connecting to the device over Bluetooth.
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.