Parse Characterstic.Value to byte integer format

后端 未结 1 1952
南方客
南方客 2021-01-17 00:10

I am doing the Core Bluetooth application. I am able to connect the peripheral and read, write value from it.

I need to parse the data which I am receiving through <

相关标签:
1条回答
  • 2021-01-17 01:03
    NSData *initialData = [yourCharacteristic value];
    

    A way to parse your data is to use subdataWithRange: method of NSData.

    Example:

    NSData *startOfFrameData = [data subdataWithRange:NSMakeRange(0, 4)];
    NSLog(@"StartOfFrameData: %@", startOfFrameData);
    NSData *eventIDData = [data subdataWithRange:NSMakeRange(4, 2)];
    NSLog(@"eventIDData: %@", eventIDData);
    

    etc.

    Output:

    >StartOfFrame: <011f6d00>
    >eventIDData: <0001>
    

    Note that I may have reversed the order of eventIDData which range could be (6,2) (instead of (4,2)), but you'll get the whole idea.

    Then, you have to "understand" the meaning of the data and find the correct format, example (possible) for eventIDData:

    UInt16 eventID;
    [eventIDData getBytes:&eventID length:sizeof(eventID)];
    NSLog(@"eventID: %d", eventID);
    

    And so on...

    If you want to "play" with it without reading again and again the characteristic value each time (which means also connect, etc.), here is a method you can use:

    -(NSData *)dataWithStringHex:(NSString *)string
    {
        NSString *cleanString;
        cleanString = [string stringByReplacingOccurrencesOfString:@"<" withString:@""];
        cleanString = [cleanString stringByReplacingOccurrencesOfString:@">" withString:@""];
        cleanString = [cleanString stringByReplacingOccurrencesOfString:@" " withString:@""];
    
        NSInteger length = [cleanString length];
        uint8_t buffer[length/2];
        for (NSInteger i = 0; i < length; i+=2)
        {
            unsigned result = 0;
            NSScanner *scanner = [NSScanner scannerWithString:[cleanString substringWithRange:NSMakeRange(i, 2)]];
            [scanner scanHexInt:&result];
            buffer[i/2] = result;
        }
        return  [[NSMutableData alloc] initWithBytes:&buffer length:length/2];
    }
    

    Example use:

    NSData *initialData = [self dataWithStringHex:@"<011f6d00 00011100 00000000 04050701 05000569 07df0203 020b0d21 02ff33>"]; 
    

    That way, you can try parsing your data on an other example/project/beta test code.

    0 讨论(0)
提交回复
热议问题