IOS Core蓝牙:为特性编写NSData

时间:2015-10-02 11:36:07

标签: ios core-bluetooth

我使用以下代码使用IOS Core蓝牙为蓝牙特性(重置设备)写入0xDE值:

...
NSData *bytes = [@"0xDE" dataUsingEncoding:NSUTF8StringEncoding];
[peripheral writeValue:bytes
            forCharacteristic:characteristic
            type:CBCharacteristicWriteWithResponse];
...

我的代码中是否有任何错误,因为该值未正确写入?

5 个答案:

答案 0 :(得分:5)

尝试使用单字节值数组创建数据。

const uint8_t bytes[] = {0xDE};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];

这是创建任意常量数据的有用方法。更多字节,

const uint8_t bytes[] = {0x01,0x02,0x03,0x04,0x05};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];

如果要创建要使用变量发送的数据,我建议使用NSMutableData并附加所需的字节。它不是很漂亮,但它易于阅读/理解,尤其是当您在嵌入式方面匹配打包结构时。以下示例来自BLE项目,我们正在制作一个简单的通信协议。

NSMutableData *data = [[NSMutableData alloc] init];

//pull out each of the fields in order to correctly
//serialize into a correctly ordered byte stream
const uint8_t start     = PKT_START_BYTE;
const uint8_t bitfield  = (uint8_t)self.bitfield;
const uint8_t frame     = (uint8_t)self.frameNumber;
const uint8_t size      = (uint8_t)self.size;

//append the individual bytes to the data chunk
[data appendBytes:&start    length:1];
[data appendBytes:&bitfield length:1];
[data appendBytes:&frame    length:1];
[data appendBytes:&size     length:1];

答案 1 :(得分:4)

Swift 3.0:如果有人想知道Swift的格式略有不同,因为writeValue可以从数组中获取计数。

jConfiguracoesParametros1

答案 2 :(得分:0)

实际上,你在这里做的是将字符串“0xDE”写入特征。如果你想使用二进制/八进制表示法,你需要远离字符串。

int integer = 0xDE;
NSData *data = [[NSData alloc] initWithBytes:&integer length:sizeof(integer)];
[peripheral writeValue:data
     forCharacteristic:characteristic
                  type:CBCharacteristicWriteWithResponse];

答案 3 :(得分:0)

bensarz的回答几乎是正确的。除了一件事:你不应该使用sizeof(int)作为NSData的长度。 int的大小为4或8个字节(取决于体系结构)。由于您要发送1个字节,请改为使用uint8_tByte

uint8_t byteToWrite = 0xDE;
NSData *data = [[NSData alloc] initWithBytes:&byteToWrite length:sizeof(&byteToWrite)];
[peripheral writeValue:data
     forCharacteristic:characteristic
                  type:CBCharacteristicWriteWithResponse];

您也可以使用int作为变量的类型,但必须初始化NSData,长度为1。

答案 4 :(得分:0)

此代码将解决问题:

NSData * data = [self  dataWithHexString: @"DE"];
[peripheral writeValue:data forCharacteristic:characteristic                                       
                            type:CBCharacteristicWriteWithResponse];

dataWithHexString实现:

- (NSData *)dataWithHexString:(NSString *)hexstring
{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= hexstring.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [hexstring substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}