在核心蓝牙框架中创建可写特性的问题

issues in creating Writable characteristic in Core Bluetooth Framework

我是核心蓝牙框架的新手。我正在开发一个充当外围设备的应用程序。我需要应用程序将特征值通知订阅的中心,并通过连接的中心写入特征值。我在创建特性时设置特性的值。问题是当我设置特征的 属性 以通知或写入时显示错误 "Characteristics with cached values must be read-only"。有人可以帮我吗?

 var charValue = characteristicDetail["value"] as String
 var charProperties:CBCharacteristicProperties = getProperty(characteristicDetail["properties"] as String )
 let data = charValue.dataUsingEncoding(NSUTF8StringEncoding)
 var characteristic = CBMutableCharacteristic(type: charId, properties: charProperties, value: data, permissions: CBAttributePermissions.Readable)



func getProperty(string:String) -> CBCharacteristicProperties
    {
    var propertyString:CBCharacteristicProperties?
    switch string{
    case "r","R":
        propertyString = CBCharacteristicProperties.Read
    case "w","W":
        propertyString = CBCharacteristicProperties.Write
    case "n","N":
        propertyString = CBCharacteristicProperties.Notify
    case "i","I":
        propertyString = CBCharacteristicProperties.Indicate
    case "rw","wr","WR","RW":
        propertyString = CBCharacteristicProperties.Read|CBCharacteristicProperties.Write
    case "rn","nr","NR","RN":
        propertyString = CBCharacteristicProperties.Read|CBCharacteristicProperties.Notify
    case "wn","nw","NW","WN":
        propertyString = CBCharacteristicProperties.Write|CBCharacteristicProperties.Notify
    default:
        propertyString = CBCharacteristicProperties.Read
    }
    return propertyString!

}

如果您在创建 CBMutableCharacteristic 时指定了一个非零 value,则它是一个 'cached characteristic',正如错误消息所说,您以后无法更改该值。

来自 CBMutableCharacteristic init 方法的文档 -

value - The characteristic value to be cached. If nil, the value is dynamic and will be requested on demand.

在创建 CBMutableCharacteristic 时指定 nil- 您在 didReceiveReadRequest CBPeripheralManagerDelegate 方法中请求时提供值。

如果您有订阅该特征的中心,那么只要值发生变化,您还应该在 CBPeripheralManager 上调用 updateValue

请务必阅读 Core Bluetooth Programming Guide

中的 执行通用外设角色任务 部分

我找到了一个可靠的 post 媒体,其中包含大量关于 BLE 的不同任务的精彩片段:

创建服务:

let serviceUUID = CBUUID(string: kServiceUUID)
let service = CBMutableService(type: serviceUUID, primary: true)

创造特征:

let characteristicUUID = CBUUID(string: kCharacteristicUUID)
let properties: CBCharacteristicProperties = [.Notify, .Read, .Write]
let permissions: CBAttributePermissions = [.Readable, .Writeable]
let characteristic = CBMutableCharacteristic(
    type: characteristicUUID,
    properties: properties,
    value: nil,
    permissions: permissions)

向服务添加特征:

service.characteristics = [characteristic1, characteristic2]

向外设管理器添加服务:

peripheralManager.addService(service)

Source