Reputation: 99
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 characteristic.value
to integer format.
I had the characteristic value as <011f6d00 00011100 00000000 04050701 05000569 07df0203 020b0d21 02ff33>
.
I have divided the data as per understanding. Please help me with the sample code for converting the data. As I am new to iOS observed many links but did not find the exact answer
<011f6d00
11 00 event id //2 bytes
00 event type //1 byte
00 No of packets //1 byte
00 00 record count //2 byte
04 05 total duration //2 byte
07 sensitivity //1 byte
01 recording sensitivity //1 byte
05 expected seizure duration //1 byte
00 Not used parameter //1 byte
05 Expected recorded duration //1 byte
69 not used parameters //1 byte
07 snooze duration //1 byte
df disable watch help button //1 byte
02 03 year //2 byte
02 date of month //1 byte
0b day of week //1 byte
0d hour //1 byte
21 minute //1 byte
02 second //1 byte
ff33> crc //2 byte
Upvotes: 0
Views: 1025
Reputation: 26026
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.
Upvotes: 3