iOS Bluetooth-チェックサムの取得、Bluetooth指令データ構築例
2297 ワード
チェックサムメソッドの取得
- (Byte)CalCheckSum2:(NSData *)data{
Byte chksum = 0;
Byte *byte = (Byte *)[data bytes];
for (NSUInteger i = 0; i < [data length]; i++){
chksum += byte[i];
}
return chksum;
}
私の需要:命令は13ビットbyte配列で、最後の1位は前の12ビットのチェックサムで、3、4位は時間(24時間制)時間と分が変換されたbyteバイトで、その他は固定的な命令です。私の構造方法は
//
- (void)onTimeChargeByBlueWith:(NSString *)timeStr
{
NSArray *array = [timeStr componentsSeparatedByString:@":"];
Byte onTimeChargeOrder[13] = {0};
onTimeChargeOrder[0] = 0xB9;
onTimeChargeOrder[1] = 0x60;
onTimeChargeOrder[2] = [self getByteWithIntString:array[0]];
onTimeChargeOrder[3] = [self getByteWithIntString:array[1]];
onTimeChargeOrder[4] = 0x00;
onTimeChargeOrder[5] = 0x00;
onTimeChargeOrder[6] = 0x00;
onTimeChargeOrder[7] = 0x00;
onTimeChargeOrder[8] = 0x00;
onTimeChargeOrder[9] = 0x00;
onTimeChargeOrder[10] = 0x00;
onTimeChargeOrder[11] = 0x00;
onTimeChargeOrder[12] = [self CalCheckSum2:[NSData dataWithBytes:onTimeChargeOrder length:12]];
NSData *data = [NSData dataWithBytes:&onTimeChargeOrder length:sizeof(onTimeChargeOrder)];
NSLog(@" %@",data);
// data, peripheral writeValue
// [self.currPeripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
#pragma mark----------- ----------------
- (Byte)getByteWithIntString:(NSString *)intString
{
int hourInt = [intString intValue];
Byte hourByte[4] ={0};
hourByte[0] = (char)(hourInt >>24 & 0xff);
hourByte[1] = (char)((hourInt >> 16) & 0xff);
hourByte[2] = (char)((hourInt >> 8) & 0xff);
hourByte[3] = (char)((hourInt) & 0xff);
return (char)((hourInt) & 0xff);
}
//
- (Byte)CalCheckSum2:(NSData *)data{
Byte chksum = 0;
Byte *byte = (Byte *)[data bytes];
for (NSUInteger i = 0; i < [data length]; i++){
chksum += byte[i];
}
return chksum;
}
最後の呼び出し方法
[self onTimeChargeByBlueWith:@"13:45"];
得られたデータは
2017-03-11 11:23:21.211 test0227[92358:2093146]