简体   繁体   English

解析BLE制造商数据-Objective-C

[英]Parse BLE Manufacturer data - Objective-C

I'm working on a custom bluetooth product, the manufacturer has embeded data in the advertisement packet. 我正在开发定制的蓝牙产品,制造商已将数据嵌入广告包中。 How do I effectively parse this data so it's usable within an iOS app? 如何有效解析此数据,以便在iOS应用程序中可用?

I'm currently grabbing the data from the NSDictionary as follows: 我目前正在从NSDictionary获取数据,如下所示:

NSData *rawData = [advertisement objectForKey:@"kCBAdvDataManufacturerData"];

The data in the packet is structured like so: 数据包中的数据结构如下:

    uint8_t compId[2];
    uint8_t empty[6];
    uint8_t temperature[2];
    uint8_t rampRate[2];
    uint8_t dutyFactor[2];
    uint8_t alarms[2];
    uint8_t statusFlag;
    uint8_t speedRpm[2];
    uint8_t vib[2];
    uint8_t deviceTypeId;
    uint8_t radioStatus;
    uint8_t cycleTimer[2];
    uint8_t batteryLevel;

My first thought was to convert it to a string and parse out the data that I need, but this seems slow and really inefficient. 我的第一个想法是将其转换为字符串并解析出我需要的数据,但这似乎很慢并且效率很低。 There has to be a standard way developers deal with this. 开发人员必须有一种标准的处理方式。 I'm still pretty green when it comes to bitwise operators. 对于按位运算符,我还是很环保的。 All the data is formatted in little endian. 所有数据均以小端格式进行格式化。

Certainly don't convert it to a string, as it isn't one, and you'll have issues with encoding. 当然,不要将它转换为字符串,因为它不是一个,并且编码会遇到问题。

  1. Start by checking that the length of the data matches what you're expecting (26 bytes) 首先检查数据length是否符合您的期望(26字节)

  2. Use the bytes method to get a pointer to the data 使用bytes方法获取指向数据的指针

  3. Add a function or method to combine two bytes into a 16-bit integer. 添加一个函数或方法以将两个字节合并为一个16位整数。 You'll have to find out if those 2-byte fields are signed or unsigned. 您必须找出那些2字节字段是带符号的还是无符号的。

Something along these lines: 遵循以下原则:

- (int)getWordFromBuffer:(const unsigned char *)bytes atOffset:(int) offset
{
    return (int)bytes[offset] | (bytes[offset+1] << 8);
}

- (NSDictionary *)decodeData:(NSData *)data
{
    if (data.length != 26)
    {
       NSLog(@"wrong length %d instead of 26", data.length);
       return nil;
    }

    const unsigned char *bytes = (unsigned char *)data.bytes;

    return
    @{
        @"compId": @([self getWordFromBuffer:bytes atOffset:0]),
        @"temperature": @([self getWordFromBuffer:bytes atOffset:8]),
        @"rampRate": @([self getWordFromBuffer:bytes atOffset:10]),
     ....
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM