蓝牙设备

更新时间:2022-03-03 06:45:28

涂鸦蓝牙有三种技术方案:

蓝牙类型 说明 设备应用示例
蓝牙单点 蓝牙设备与手机一对一相连单点设备(蓝牙或蓝牙 LE) 体脂秤、手环、温控器、电动牙刷、门锁等
蓝牙 Mesh 蓝牙技术联盟发布的蓝牙拓扑通信 一路、二路、五路等灯泡、插座、传感器等子设备
涂鸦 Mesh 涂鸦自研的蓝牙拓扑通信 与蓝牙 Mesh 产品类似,通信协议为涂鸦自研
双模设备 一些多协议设备也会使用到蓝牙技术,例如同时具备 Wi-Fi 能力和蓝牙能力的 双模设备 蓝牙 Mesh 网关、IPC 设备、新版多协议 Wi-Fi 设备等

双模配网的蓝牙配网部分,使用的是蓝牙单点技术为设备配网,将放到 蓝牙单点章节 进行说明。

功能描述

蓝牙部分所具备的功能如下:

  • 设备配网
    • 扫描并发现设备
    • 设备配网
  • 设备管理
    • 检查设备当前联网状态
    • 连接设备
    • 设备操作和远程控制
    • 解绑设备
  • 固件升级
    • 检测设备版本
    • 升级设备固件 OTA

所需权限

在 iOS 13 中,苹果将原来蓝牙申请权限用的 NSBluetoothPeripheralUsageDescription 字段,替换为 NSBluetoothAlwaysUsageDescription 字段。在 info.plist 中添加新字段:

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

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

iOS12 适配

iOS 12 使用 [[TuyaSmartActivator sharedInstance] currentWifiSSID] 无法查询到 SSID。

在 Xcode 10 中查询 Wi-Fi 信息需要开启相关权限,解决方法:Xcode > [Project Name] > Targets > [Target Name] > Capabilities > Access WiFi Information > ON

蓝牙设备

功能入口

类名 说明 能力
TuyaSmartBLEManager 单点蓝牙相关类 包含单点蓝牙 SDK 的所有相关功能,包含扫描设备、单点设备配网、双模设备配网、蓝牙设备操作、固件升级、错误码等。
TuyaSmartBLEWifiActivator 双模设备配网相关类 包含设备双模配网所需方法。

单点蓝牙设备指的是具有和手机终端 通过蓝牙一对一连接 的设备,例如蓝牙手环、蓝牙耳机、蓝牙音箱等。每个设备最多同时和一个手机进行蓝牙连接,每个手机终端目前 同时连接的蓝牙数量控制在 6 ~ 7 个 内。

监测手机蓝牙状态

接口说明

在用户手机的蓝牙发生状态变化时,如开启或关闭,可以通过设置代理收到具体的消息。

示例代码

Objc:

// 设置代理
[TuyaSmartBLEManager sharedInstance].delegate = self;

/**
 * 蓝牙状态变化通知
 *
 * @param isPoweredOn 蓝牙状态,开启或关闭
 */
- (void)bluetoothDidUpdateState:(BOOL)isPoweredOn {
    NSLog(@"蓝牙状态变化: %d", isPoweredOn ? 1 : 0);
}

Swift:

// 设置代理
TuyaSmartBLEManager.sharedInstance().delegate = self

/**
 * 蓝牙状态变化通知
 *
 * @param isPoweredOn 蓝牙状态,开启或关闭
 */
func bluetoothDidUpdateState(_ isPoweredOn: Bool) {

}

扫描蓝牙设备

开始扫描

接口说明

处于待连接的蓝牙设备都会不停的向四周发蓝牙广播包。客户端作为终端可以发现这些广播包,然后根据广播包中包含涂鸦设备信息规则作为目标设备的过滤条件。

/**
 * 开始扫描
 *
 * 如果扫描到未激活设备,结果会通过 TuyaSmartBLEManagerDelegate 中的 `- (void)didDiscoveryDeviceWithDeviceInfo:(TYBLEAdvModel *)deviceInfo` 返回;
 *
 * 如果扫描到激活设备,会自动进行连接入网,不会返回扫描结果
 *
 * @param clearCache 是否清理已扫描到的设备
 */
- (void)startListening:(BOOL)clearCache;

参数说明

参数 说明
clearCache 是否清理已扫描到的设备

示例代码

Objc:

// 设置代理
[TuyaSmartBLEManager sharedInstance].delegate = self;

// 开始扫描
[[TuyaSmartBLEManager sharedInstance] startListening:YES];


/**
 * 扫描到未激活的设备
 *
 * @param deviceInfo 未激活设备信息 Model
 */
- (void)didDiscoveryDeviceWithDeviceInfo:(TYBLEAdvModel *)deviceInfo {
    // 成功扫描到未激活的设备
    // 若设备已激活,则不会走此回调,且会自动进行激活连接
}

Swift:

TuyaSmartBLEManager.sharedInstance().delegate = self
TuyaSmartBLEManager.sharedInstance().startListening(true)

/**
 * 扫描到未激活的设备
 *
 * @param uuid 未激活设备 uuid
 * @param productKey 未激活设备产品 key
 */
func didDiscoveryDevice(withDeviceInfo deviceInfo: TYBLEAdvModel) {
    // 成功扫描到未激活的设备
    // 若设备已激活,则不会走此回调,且会自动进行激活连接
}

TuyaBLEAdvModel 说明

属性 类型 说明
uuid NSString 设备 uuid,可以唯一区别设备
productId NSString 产品 ID
mac NSString 设备 Mac,不可作为唯一码,iOS 为空
isActive Bool 是否被绑定,能回调的均为未配网的设备
isSupport5G Bool 表示蓝牙 LE 设备是否支持通过路由器在 5GHz 频段上的连接
isProuductKey Bool 是否支持 productKey
bleProtocolV int 设备支持的涂鸦蓝牙协议版本
bleType Enum 设备类型,用于区分不同协议的设备

bleType 表示待配网设备的类型。若取值中带有 Wifi,则表示为双模设备,此时参考下文 双模配网部分。否则为蓝牙设备,此时参考下文对应的蓝牙配网部分。

bleType 取值 设备类型
TYSmartBLETypeBLE 蓝牙设备
TYSmartBLETypeBLEPlus 蓝牙设备
TYSmartBLETypeBLEWifi Wi-Fi 和蓝牙双模设备
TYSmartBLETypeBLESecurity 蓝牙设备
TYSmartBLETypeBLEWifiSecurity Wi-Fi 和蓝牙双模设备
TYSmartBLETypeBLEWifiPlugPlay Wi-Fi 和蓝牙双模设备,并具备 双模设备蓝牙兜底激活 能力

停止扫描

停止扫描设备,比如退出配网页面或者完成配网流程时,建议停止扫描,以防止扫描影响到配网过程。

接口说明

/**
 * 停止扫描
 *
 * @param clearCache 是否清理已扫描到的设备
 */
- (void)stopListening:(BOOL)clearCache;

参数说明

参数 说明
clearCache 是否清理已扫描到的设备

示例代码

Objc:

[[TuyaSmartBLEManager sharedInstance] stopListening:YES];

Swift:

TuyaSmartBLEManager.sharedInstance().stopListening(true)

蓝牙单点配网

接口说明

扫描到未激活的设备后,可以进行设备激活并且注册到云端,并记录在站点下。

/**
 * 激活设备
 * 激活过程会将设备信息注册到云端
 */
- (void)activeBLE:(TYBLEAdvModel *)deviceInfo
           homeId:(long long)homeId
          success:(void(^)(TuyaSmartDeviceModel *deviceModel))success
          failure:(TYFailureHandler)failure;

参数说明

参数 说明
deviceInfo 设备信息 Model,来源于扫描代理方法返回的结果
homeId 当前站点 ID
success 成功回调
failure 失败回调

示例代码

Objc:

[[TuyaSmartBLEManager sharedInstance] activeBLE:deviceInfo homeId:homeId success:^(TuyaSmartDeviceModel *deviceModel) {
        // 激活成功

    } failure:^{
        // 激活中的错误
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().activeBLE(<deviceInfo: deviceInfo, homeId: homeId, success: { (deviceModel) in
        // 激活成功
        }) {
        // 激活中的错误
        }

双模设备配网

双模设备入网

接口说明

扫描到未激活的设备后,可以使用该方法将配网信息通过蓝牙通道下发给设备,并等待配网结果回调。

/**
 *  connect BLE and Wi-Fi device
 *  连接蓝牙 Wi-Fi 设备
 */
- (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;

参数说明

参数 说明
UUID 设备 uuid
homeId 当前站点 ID
productId 产品 ID
ssid Wi-Fi 路由器热点名称
password Wi-Fi 路由器热点密码
timeout 轮询时间
success 成功回调
failure 失败回调

示例代码

Objc:

[[TuyaSmartBLEWifiActivator sharedInstance] startConfigBLEWifiDeviceWithUUID:TYBLEAdvModel.uuid homeId:homeId productId:TYBLEAdvModel.productId ssid:ssid password:password  timeout:100 success:^{
    // 下发成功
    } failure:^{
    // 下发失败
    }];

Swift:

TuyaSmartBLEWifiActivator.sharedInstance() .startConfigBLEWifiDevice(withUUID: TYBLEAdvModel.uuid, homeId: homeId, productId:TYBLEAdvModel.productId, ssid: ssid, password: password, timeout: 100, success: {
        // 下发成功
    }) {
        // 下发失败
    }

双模设备激活回调

接口说明

配网的结果通过 delegate 方法回调。

示例代码

Objc:

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

    if (error) {
        // 配网失败
    }
}

Swift:

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

    if (error) {
        // 配网失败
    }
}

取消双模设备入网

示例代码

Objc:

//在配网结束后调用
[[TuyaSmartBLEWifiActivator sharedInstance] stopDiscover];

Swift:

//在配网结束后调用
TuyaSmartBLEWifiActivator.sharedInstance() .stopDiscover

双模设备蓝牙兜底激活

部分双模设备拥有蓝牙兜底激活能力。可在设备无法连接 Wi-Fi 路由器,或者 Wi-Fi 路由器无法连接互联网时,将这类设备当成普通蓝牙设备。调用本方法激活设备的蓝牙通道。

判断扫描到的设备是否拥有蓝牙兜底配网能力,可以通过 TYBLEAdvModelbleType 进行判断。若值为 TYSmartBLETypeBLEWifiPlugPlay,则表示该设备拥有蓝牙兜底配网能力,其它结果则表示没有该能力。

接口说明

/**
 *  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;

参数说明

参数 说明
advModel 设备信息 Model,来源于扫描代理方法返回的结果
homeId 当前站点 ID
token 配网 Token
success 成功回调
failure 失败回调

示例代码

Objc:

[[TuyaSmartBLEManager sharedInstance] activatorDualDeviceWithBleChannel:advModel homeId:homeId token:token success:^(TuyaSmartDeviceModel * _Nonnull device) {
                    // 兜底配网成功
    } failure:^(NSError *error) {
                    // 兜底配网失败
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().activatorDualDevice(withBleChannel: advModel, homeId: homeId, token: token) { (TuyaSmartDeviceModel) in
            // 兜底配网成功
        } failure: { (Error?) in
            // 兜底配网失败
        }

双模设备连云激活

通过蓝牙兜底方法激活成功的设备,若想重新尝试让设备 Wi-Fi 通道进行云端激活,可以调用本接口实现。

调用时需要确保设备和 App 处于蓝牙连接状态。可通过 deviceModel.meta 中的 wifiEnable 字段判断设备是否连云激活成功。默认值为 false,表示设备 Wi-Fi 通道未激活。

接口说明

/**
 *  activates the Wi-Fi channel of a dual-mode device for which the Bluetooth channel is activated.
 *  当双模设备蓝牙通道激活成功时,连云激活该设备 Wi-Fi 通道
 */
- (void)activeDualDeviceWifiChannel:(NSString *)devId
                               ssid:(NSString *)ssid
                           password:(NSString *)password
                            timeout:(NSTimeInterval)timeout
                            success:(void(^)(TuyaSmartDeviceModel *deviceModel))success
                            failure:(TYFailureError)failure;

参数说明

参数 说明
devId 设备 ID
ssid Wi-Fi 路由器热点名称
password Wi-Fi 路由器热点密码
timeout 轮询时间
success 成功回调
failure 失败回调

示例代码

Objc:

[[TuyaSmartBLEManager sharedInstance] activeDualDeviceWifiChannel:devId ssid:ssid password:password timeout:timeout success:^(TuyaSmartDeviceModel * _Nonnull device) {
                    // 连云激活成功
    } failure:^(NSError *error) {
                    // 连云激活失败
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().activeDualDeviceWifiChannel(devId, ssid: ssid, password: password, timeout: timeout) { (TuyaSmartDeviceModel) in
            // 连云激活成功
        } failure: { (Error?) in
            // 连云激活失败
        }

蓝牙设备管理

判断设备在线状态

接口说明

查询设备蓝牙是否本地连接。

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

如果是双模设备,可根据 TuyaSmartDeviceModel 里的 isOnline 是否为 true,来判断设备在线:

  • TuyaSmartDeviceModel 里的 isOnlinetrue,且上述方法返回 true 判断双模设备为蓝牙在线。
  • TuyaSmartDeviceModel 里的 isOnlinetrue,且上述方法返回 false 判断双模设备为 Wi-Fi 在线。

参数说明

参数 说明
uuid 设备 UUID

示例代码

Objc:

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

Swift:

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

连接离线中的设备

接口说明

若设备处于离线状态,可以调用连接方法进行设备连接。

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

参数说明

参数 说明
uuid 设备 UUID
productKey 产品 ID
success 成功回调
failure 失败回调

示例代码

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)

断开已连接的设备

接口说明

若设备处于连接状态 可以调用该方法断开与设备连接。

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

参数说明

参数 说明
uuid 设备 uuid
success 成功回调
failure 失败回调

示例代码

Objc:

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

Swift:

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

下发设备 DP

控制发送详情,请参考 设备功能发送

查询设备名称

接口说明

当扫描到设备广播包,并拿到设备广播包对象后,可以通过该方法查询设备名称。

/**
 * 查询设备名称
 */
- (void)queryDeviceInfoWithUUID:(NSString *)uuid
                      productId:(NSString *)productId
                        success:(TYSuccessDict)success
                        failure:(TYFailureError)failure;

参数说明

参数 说明
uuid 设备 uuid
productId 产品 ID
success 成功回调
failure 失败回调

示例代码

Objc:

[[TuyaSmartBLEManager sharedInstance] queryNameWithUUID:bleAdvInfo.uuid productId:bleAdvInfo.productId success:^(NSDictionary *dict) {
        // 查询设备名称成功

    } failure:^{
        // 查询设备名称失败
    }];

Swift:

TuyaSmartBLEManager.sharedInstance().queryName(withUUID: bleAdvInfo.uuid, productId: bleAdvInfo.productId, success: { (dict) in
        // 查询设备名称成功
}, failure: { (error) in
        // 查询设备名称失败
})

设备固件升级

查询设备升级信息

接口说明

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

参数说明

参数 说明
success 成功回调,设备的固件升级信息列表
failure 失败回调

TuyaSmartFirmwareUpgradeModel 数据模型

字段 类型 说明
desc NSString 固件升级的描述文案
typeDesc NSString 设备类型说明
upgradeStatus NSInteger 升级状态:
  • 0:无新版本
  • 1:有新版本
  • 2:在升级中
  • 5:等待设备唤醒
version NSString 新版本使用的固件版本
upgradeType NSInteger 升级类型:
  • 0:App 提醒升级
  • 2:App 强制升级
  • 3:检测升级
url NSString 蓝牙设备的升级固件包下载 URL
fileSize NSString 固件包的大小,单位为字节(byte)
md5 NSString 固件的 MD5
upgradingDesc NSString 固件升级中的提示文案

示例代码

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)")
        }
    })
}

固件 OTA 升级

接口说明

对于有固件升级的设备,可以通过发送升级固件数据包对设备进行升级。其中升级固件包需要先请求云端接口进行查询固件信息。

/**
 * 发送 OTA 包,升级固件。升级前请务必保证设备已通过蓝牙连接
 */
- (void)sendOTAPack:(NSString *)uuid
                pid:(NSString *)pid
            otaData:(NSData *)otaData
            success:(TYSuccessHandler)success
            failure:(TYFailureHandler)failure;

参数说明

参数 说明
uuid 设备 UUID
pid 产品 ID
otaData 升级固件的数据
success 成功回调
failure 失败回调

示例代码

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);
    }];
}

// 如果有升级,其中 TuyaSmartFirmwareUpgradeModel.url 是固件升级包的下载地址
// 根据 URL 下载固件后,将数据转成 data,传给 SDK 进行固件升级
// deviceModel:需要升级的设备 model
// data:下载的固件包
[[TuyaSmartBLEManager sharedInstance] sendOTAPack:deviceModel.uuid pid:deviceModel.pid otaData:data success:^{
       NSLog(@"OTA 成功");
    } failure:^{
       NSLog(@"OTA 失败");
}];

Swift:

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

// 如果有升级,其中 TuyaSmartFirmwareUpgradeModel.url 是固件升级包的下载地址
// 根据 URL 下载固件后,将数据转成 data,传给 SDK 进行固件升级
// deviceModel:需要升级的设备 model
// data:下载的固件包
TuyaSmartBLEManager.sharedInstance().sendOTAPack(deviceModel.uuid, pid: deviceModel.pid, otaData: data, success: {
    print("OTA 成功");
}) {
    print("OTA 失败");
}

错误码

错误码 说明
1 设备接收的数据包格式错误
2 设备找不到路由器
3 Wi-Fi 密码错误
4 设备连不上路由器
5 设备 DHCP 失败
6 设备连云失败
100 用户取消配网
101 蓝牙连接错误
102 发现蓝牙服务错误
103 打开蓝牙通讯通道失败
104 蓝牙查询设备信息失败
105 蓝牙配对失败
106 配网超时
107 Wi-Fi 信息发送失败
108 Token 失效
109 查询蓝牙加密密钥失败
110 设备不存在
111 设备云端注册失败
112 设备云端激活失败
113 云端设备已被绑定
114 主动断开
115 云端查询设备信息失败
116 设备此时正被其他方式配网
117 OTA 升级失败
118 OTA 升级超时
119 Wi-Fi 配网传参校验失败