Bluetooth Series

Last Updated on : 2024-03-08 09:37:36download

The single Bluetooth (Bluetooth LE) device is able to one-to-one connect to mobile applications through Bluetooth. Such as Bluetooth bracelets, Bluetooth headsets, Bluetooth speakers, and more. Each device can connect to the mobile applications by Bluetooth at most at the same time. At present, the number of Bluetooth connections for each mobile phone terminal cannot exceed 6 or 7.

Class Description
TuyaSmartBLEManager Bluetooth device class
TuyaSmartBLEWifiActivator Dual-mode device class
  • TuyaSmartBLEManager contains all the features of the Bluetooth SDK, includes scanning device, single Bluetooth device activation, dual-mode device activation, Bluetooth device function, Bluetooth OTA, error code, and so forth.

  • TuyaSmartBLEWifiActivator supports a dual-mode device activator.

Preparation

Bluetooth status monitor

Bluetooth SDK provides the method of Bluetooth status monitor, while Bluetooth state-changing (turn on or turn off), you can receive the notification by setting the delegate

Example

Objc:

// Set delegate
[TuyaSmartBLEManager sharedInstance].delegate = self;

/**
 * Notification of Bluetooth state change
 *
 * @param isPoweredOn   Bluetooth state, turn on or turn off
 */
- (void)bluetoothDidUpdateState:(BOOL)isPoweredOn {
    NSLog(@"bluetooth state: %d", isPoweredOn ? 1 : 0);
}

Swift:

// Set delegate
TuyaSmartBLEManager.sharedInstance().delegate = self

/**
  * Notification of Bluetooth state change
  *
  * @param isPoweredOn   Bluetooth state, turn on or turn off
 */
func bluetoothDidUpdateState(_ isPoweredOn: Bool) {
   print("bluetooth state: \(isPoweredOn ? 1 : 0)");
}

Scanning device

Start scanning

The Bluetooth device to be active will continuously send Bluetooth broadcast packets to the surrounding area, and the client can discover these broadcast packet, Bluetooth SDK will filter the target device by the rule of Tuya Bluetooth device information in the broadcast packet

/**
 * Start scan
 *
 * @param clearCache   whether clean up the caches of scanned devices
 */
- (void)startListening:(BOOL)clearCache;

Parameters

Parameter Description
clearCache Wheather clean up the caches of scanned devices

Example

Objc:

// Set delegate
[TuyaSmartBLEManager sharedInstance].delegate = self;
// Start scan
[[TuyaSmartBLEManager sharedInstance] startListening:YES];

/**
 * The inactive device that discovered
 *
 * @param deviceInfo 	inactive device Model
 */
- (void)didDiscoveryDeviceWithDeviceInfo:(TYBLEAdvModel *)deviceInfo {
    // scaned inactive device successfully
    // if the device has actived, it will not in this callback, Bluetooth SDK will connect and active this device automatically
}

Swift:

// set delegate
TuyaSmartBLEManager.sharedInstance().delegate = self
// Start scan
TuyaSmartBLEManager.sharedInstance().startListening(true)

/**
 * The inactive device that discovered
 *
 * @param deviceInfo 	inactive device Model
 */
func didDiscoveryDevice(withDeviceInfo deviceInfo: TYBLEAdvModel) {
    // scanned inactive device successfully
    // if the device has activated, it will not in this callback, Bluetooth SDK will connect and active this device automatically
}

TuyaBLEAdvModel Description

Attributes Type Description
uuid NSString The UUID of the Bluetooth LE device.
productId NSString The product ID of the Bluetooth LE device.
mac NSString The MAC address of the Bluetooth LE device. Empty for iOS.
isActive Bool The activation state of the Bluetooth LE device.
bleType Enum The type of Bluetooth LE device.
isSupport5G Bool Indicates whether the Bluetooth LE device supports connections through the router on a 5 GHz band.
isProuductKey Bool Indicates whether the Bluetooth LE device supports the product key.
bleProtocolV int The Tuya Bluetooth protocol version of the device.

The bleType indicates the type of device to be activated, no special attention is needed. If dual-mode devices with Wi-Fi see dual-mode activation, Bluetooth devices see Bluetooth activation.

Value Device type name
TYSmartBLETypeBLE Bluetooth device
TYSmartBLETypeBLEPlus Bluetooth device
TYSmartBLETypeBLEWifi Wi-Fi + Bluetooth dual-mode device
TYSmartBLETypeBLESecurity Bluetooth device
TYSmartBLETypeBLEWifiSecurity Wi-Fi + Bluetooth dual-mode device
TYSmartBLETypeBLEWifiPlugPlay Wi-Fi + Bluetooth dual-mode device

Stop scanning

Stop scanning devices, such as exiting the activation page

/**
 * Stop scan
 *
 * @param clearCache   whether clean up the caches of scanned devices
 */
- (void)stopListening:(BOOL)clearCache;

Parameters

Parameter Description
clearCache Wheather clean up the caches of scanned devices

Example

Objc:

[[TuyaSmartBLEManager sharedInstance] stopListening:YES];

Swift:

TuyaSmartBLEManager.sharedInstance().stopListening(true)

Bluetooth device activation

Start activation

After scanning an inactive device, the device can be activated and registered to the Tuya IoT.

/**
 * Active device
 * The activation process will register the device to the Tuya IoT.
 */
- (void)activeBLE:(TYBLEAdvModel *)deviceInfo
           homeId:(long long)homeId
          success:(void(^)(TuyaSmartDeviceModel *deviceModel))success
          failure:(TYFailureHandler)failure;

Parameters

Parameter Description
deviceInfo The device model is from the delegate of scan method
homeId Current home Id
success Success callback
failure Failure callback

Example

Objc:

[[TuyaSmartBLEManager sharedInstance] activeBLE:deviceInfo homeId:homeId success:^(TuyaSmartDeviceModel *deviceModel) {
        // active success

    } failure:^{
        // active fail
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().activeBLE(<deviceInfo: deviceInfo, homeId:homeId, success: { (deviceModel) in
        // active success
        }) {
        // active fail
        }

Dual-mode device activation

Start dual-mode device activation

After scanning an inactive device, the device can be activated and registered to the Tuya IoT.

After scanning an inactive device, you can use this method to send the active information to the device through the Bluetooth channel and wait for the result callback

/**
 *  connect Bluetooth or Wi-Fi devices
 */
- (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 Device UUID
homeId Current home Id
productId Product Id
ssid Router hotspot name
password Router hotspot password
timeout Scan timeout
success Success callback
failure Failure callback

Example

Objc:

  [[TuyaSmartBLEWifiActivator sharedInstance] startConfigBLEWifiDeviceWithUUID:TYBLEAdvModel.uuid homeId:homeId productId:TYBLEAdvModel.productId ssid:ssid password:password  timeout:100 success:^{
     // send success
        } failure:^{
     // send fail
        }];

Swift:

  TuyaSmartBLEWifiActivator.sharedInstance() .startConfigBLEWifiDevice(withUUID: TYBLEAdvModel.uuid, homeId: homeId, productId:TYBLEAdvModel.productId, ssid: ssid, password: password, timeout: 100, success: {
     // send success
        }) {
     // send fail
        }

Callback of dual-mode device activator

You can get the result of the device activator by setting the delegate.

Example

Objc:

- (void)bleWifiActivator:(TuyaSmartBLEWifiActivator *)activator didReceiveBLEWifiConfigDevice:(TuyaSmartDeviceModel *)deviceModel error:(NSError *)error {
    if (!error && deviceModel) {
		// activator success
    }

    if (error) {
    // activator fail
    }
}

Swift:

func bleWifiActivator(_ activator: TuyaSmartBLEWifiActivator, didReceiveBLEWifiConfigDevice deviceModel: TuyaSmartDeviceModel?, error: Error?) {
    if (!error && deviceModel) {
		// activator success
    }

    if (error) {
    // activator fail
    }
}

Cancel dual-mode device activation

Stop discover device

Example

Objc:

// use after activator finished
[[TuyaSmartBLEWifiActivator sharedInstance] stopDiscover];

Swift:

// use after activator finished
TuyaSmartBLEWifiActivator.sharedInstance().stopDiscover

Dual-mode device Bluetooth channel activator

Some dual-mode devices have Bluetooth capability. You can treat such devices as normal Bluetooth devices and call this method to activate the Bluetooth communication channel of the device when the device cannot connect to the router, or the router cannot connect to the Internet.

If the TYBLEAdvModel.bleType value is TYSmartBLETypeBLEWifiPlugPlay, it means the device has the capability of Bluetooth protection activation, other result means no such capability.

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

Parameters

Parameter Description
advModel Device UUID
homeId Current home Id
token Config token
success Success callback
failure Failure callback

Example

Objc:

[[TuyaSmartBLEManager sharedInstance] activatorDualDeviceWithBleChannel:advModel homeId:homeId token:token success:^(TuyaSmartDeviceModel * _Nonnull device) {
					//active success        
    } failure:^(NSError *error) {
					//active fail
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().activatorDualDevice(withBleChannel: advModel, homeId: homeId, token: token) { (TuyaSmartDeviceModel) in
            //active success
        } failure: { (Error?) in
            //active fail
        }

Dual-mode device Wi-Fi channel activator

Device that has been successfully activated by it’s Bluetooth channel can call this interface if it wants to retry to get the device Wi-Fi channel for cloud activation.

Make sure the device and APP are connected by Bluetooth when use this method.

The wifiEnable field in deviceModel.meta can be used to determine if the device is successfully connected to the cloud. Defalut is false, which means device Wi-Fi channel isn’t active.

/**
 *  activates the Wi-Fi channel of a dual-mode device for which the Bluetooth channel is activated.
 */
- (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 Device devId
ssid Router hotspot name
password Router hotspot password
timeout Scan timeout
success Success callback
failure Failure callback

Example

Objc:

[[TuyaSmartBLEManager sharedInstance] activeDualDeviceWifiChannel:devId ssid:ssid password:password timeout:timeout success:^(TuyaSmartDeviceModel * _Nonnull device) {
					//active success        
    } failure:^(NSError *error) {
					//active fail
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().activeDualDeviceWifiChannel(devId, ssid: ssid, password: password, timeout: timeout) { (TuyaSmartDeviceModel) in
            //active success
        } failure: { (Error?) in
            //active fail
        }

Bluetooth device management

Device status query

Query if the device is locally connected

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

Note: In the case of dual-mode devices, you can determine that the dual-mode device is Bluetooth online based on the fact that isOnline in TuyaSmartDeviceModel is true and the above method returns true; the method isOnline in TuyaSmartDeviceModel is true and the above method returns false to determine that the dual-mode device is Wi-Fi online.

Parameters

Parameter Description
uuid Device UUID

Example

Objc:

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

Swift:

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

Connect device

If the device is offline, you can call the connection method to connect the device.

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

Parameters

Parameter Description
uuid Device UUID
productKey Product Id
success Success callback
failure 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 device

If the device is online, you can call this method to disconnect the device.

- (void)disconnectBLEWithUUID:(NSString *)uuid
                      success:(TYSuccessHandler)success
                      failure:(TYFailureError)failure;

Parameters

Parameter Description
uuid Device UUID
success Success callback
failure 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)

Device DP publish

Dp publish refer to Functions of device

Query device name

After receiving the device broadcast package, the device name can be queried by this method

/**
 * Query device name
 */
- (void)queryNameWithUUID:(NSString *)uuid
               productKey:(NSString *)productKey
                  success:(void(^)(NSString *name))success
                  failure:(TYFailureError)failure;

Parameters

Parameter Description
uuid Device UUID
productKey Product Id
success Success callback
failure Failure callback

Example

Objc:

[[TuyaSmartBLEManager sharedInstance] queryNameWithUUID:bleAdvInfo.uuid productKey:bleAdvInfo.productId success:^(NSString *name) {
        // query device name success

    } failure:^{
        // query device name failure
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().queryName(withUUID: bleAdvInfo.uuid, productKey: bleAdvInfo.productId, success: { (name) in
        // query device name success
}, failure: { (error) in
        // query device name failure
})

Error code

Code Description
1 Format of the packet received by the device is incorrect
2 The device cannot find the router
3 Wi-Fi password error
4 Device cannot connect to router
5 Device DHCP failed
6 The device fails to connect to the cloud
100 User cancels activation
101 Bluetooth connection error
102 Bluetooth service error found
103 Failed to open Bluetooth communication channel
104 Bluetooth failed to get device information
105 Bluetooth pairing failed
106 Activation timeout
107 Wi-Fi information transmission failed
108 Token is invalid
109 Failed to get Bluetooth encryption key
110 Device does not exist
111 Device cloud registration failed
112 Device cloud activation failed
113 Cloud device has been bound
114 Active disconnect
115 Failed to get device information in the cloud
116 The device is being networked by other methods at this time
117 OTA upgrade failed
118 OTA upgrade timeout
119 Wi-Fi parameter verification failed