Bluetooth Devices

Last Updated on : 2022-03-03 06:45:28download

Tuya provides the following Bluetooth solutions.

Bluetooth type Description Example of smart devices
Bluetooth Low Energy (LE) A peer-to-peer connection is created between a Bluetooth or Bluetooth Low Energy (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
    • Start paring
  • Device Management
    • Check current device networking status
    • Connect to devices
    • Remotely control and operate devices
    • Unbind devices
  • Firmware update
    • Check firmware version
    • 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, [[TuyaSmartActivator 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 WiFi Information to ON at Xcode > [Project Name] > Targets > [Target Name] > Capabilities.

Bluetooth Devices

Entry to the feature

Class name Description Capabilities
TuyaSmartBLEManager 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.
TuyaSmartBLEWifiActivator Combo device pairing class Methods required to pair combo devices.

A Bluetooth LE device is connected with a mobile phone through peer-to-peer 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

ObjC:

// Sets a delegate.
[TuyaSmartBLEManager 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.
TuyaSmartBLEManager.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:(TYBLEAdvModel *)deviceInfo` in `TuyaSmartBLEManagerDelegate`.
 *
 * 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;

Parameters

Parameter Description
clearCache Specifies whether to clear discovered devices.

Example

ObjC:

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

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


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

Swift:

TuyaSmartBLEManager.sharedInstance().delegate = self
TuyaSmartBLEManager.sharedInstance().startListening(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: TYBLEAdvModel) {
    // An inactivated device is discovered.
    // If an activated device is discovered, it is automatically connected without the current callback.
}

TuyaBLEAdvModel

Property Type Description
uuid NSString The UUID that is used to uniquely identify the device.
productId NSString The product ID.
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 executed, 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 supported by the device.
bleType Enum The type of device to distinguish different types of device protocols.

bleType indicates the type of device pending pairing. 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
TYSmartBLETypeBLE Bluetooth Devices
TYSmartBLETypeBLEPlus Bluetooth Devices
TYSmartBLETypeBLEWifi Wi-Fi and Bluetooth combo device
TYSmartBLETypeBLESecurity Bluetooth Devices
TYSmartBLETypeBLEWifiSecurity Wi-Fi and Bluetooth combo device
TYSmartBLETypeBLEWifiPlugPlay 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

ObjC:

[[TuyaSmartBLEManager sharedInstance] stopListening:YES];

Swift:

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

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

Parameters

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

Example

ObjC:

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

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

Swift:

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

Pair combo devices

Connect a combo device to 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:(TYSuccessHandler)success
                                 failure:(TYFailureHandler)failure;

Parameters

Parameter Description
UUID The UUID of a device.
homeId The current site ID.
productId The product 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

ObjC:

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

Swift:

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

Callback of an activated combo device

API description

Returns the pairing result by using the delegate method.

Example

ObjC:

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

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

Swift:

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

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

Disconnect a combo device from the network

Example

ObjC:

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

Swift:

// Called at the end of pairing.
TuyaSmartBLEWifiActivator.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 that 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 TYBLEAdvModel can be used to check whether a combo device supports pairing over Bluetooth if Wi-Fi connections are unavailable. If the value is TYSmartBLETypeBLEWifiPlugPlay, the device supports this capability. Otherwise, it does not support this capability.

API description

/**
 *  activates the Bluetooth mode for a dual-mode device
 * The channel to pair the combo device over Bluetooth.
 */
- (void)activatorDualDeviceWithBleChannel:(TYBLEAdvModel *)advModel
                                   homeId:(long long)homeId
                                    token:(NSString *)token
                                  success:(void(^)(TuyaSmartDeviceModel *deviceModel))success
                                  failure:(TYFailureError)failure;

Parameters

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

Example

ObjC:

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

Swift:

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

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 Wi-Fi channel of a dual-mode device for which the Bluetooth channel is activated.
 * Activates the combo device paired over Bluetooth in the cloud through a Wi-Fi channel.
 */
- (void)activeDualDeviceWifiChannel:(NSString *)devId
                               ssid:(NSString *)ssid
                           password:(NSString *)password
                            timeout:(NSTimeInterval)timeout
                            success:(void(^)(TuyaSmartDeviceModel *deviceModel))success
                            failure:(TYFailureError)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

ObjC:

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

Swift:

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

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 TuyaSmartDeviceModel istrue, the device is online.

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

Parameters

Parameter Description
uuid The UUID of the device.

Example

ObjC:

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

Swift:

var isOnline:BOOL = TuyaSmartBLEManager.sharedInstance().deviceStatue(withUUID: "uuid")

Connect to an offline device

API description

Connects to an offline device.

- (void)connectBLEWithUUID:(NSString *)uuid
                productKey:(NSString *)productKey
                   success:(TYSuccessHandler)success
                   failure:(TYFailureHandler)failure;

Parameters

Parameter Description
uuid The UUID of the device.
productKey The product ID.
success The success callback.
failure The failure callback.

Example

ObjC:

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

Swift:

TuyaSmartBLEManager.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:(TYSuccessHandler)success
                      failure:(TYFailureError)failure;

Parameters

Parameter Description
uuid The UUID of a device.
success The success callback.
failure The failure callback.

Example

ObjC:

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

Swift:

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

Send device DPs

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

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 name of the device.
 */
- (void)queryDeviceInfoWithUUID:(NSString *)uuid
                      productId:(NSString *)productId
                        success:(TYSuccessDict)success
                        failure:(TYFailureError)failure;

Parameters

Parameter Description
uuid The UUID of a device.
productId The product ID.
success The success callback.
failure The failure callback.

Example

ObjC:

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

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

Swift:

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

Query device update information

API description

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

Parameters

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

Data model of TuyaSmartFirmwareUpgradeModel

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 updates
  • 1: updates 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: app notification of updates
  • 2: forced updates
  • 3: check for updates
url NSString The URL at which the firmware update package of the Bluetooth device can be downloaded.
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.

Example

ObjC:

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

    [self.device getFirmwareUpgradeInfo:^(NSArray<TuyaSmartFirmwareUpgradeModel *> *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 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:(TYSuccessHandler)success
            failure:(TYFailureHandler)failure;

Parameters

Parameter Description
uuid The UUID of the device.
pid The product ID.
otaData The data of firmware update.
success The success callback.
failure The failure callback.

Example

ObjC:

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

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

// The firmware update is available and the download URL is indicated by `TuyaSmartFirmwareUpgradeModel.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.
[[TuyaSmartBLEManager 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 `TuyaSmartFirmwareUpgradeModel.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.
TuyaSmartBLEManager.sharedInstance().sendOTAPack(deviceModel.uuid, pid: deviceModel.pid, otaData: data, success: {
    print("OTA update is successful.");
}) {
    print("OTA update 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 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 specified token is invalid.
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.