概要
Bluetooth接続後のキャラクタリスティック探索結果から取得した
キャラクタリスティックを使用し値の書き込みと読み込み処理についてまとめました。
Read
キャラクタリスティックの値の取得処理
[peripheral readValueForCharacteristic:キャラクタリスティック];
で指定したキャラクタリスティックの値を取得できます。
[self.get_peripheral readValueForCharacteristic:service.characteristics[i]];
//Read_結果
- (void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"error: %@", error);
return;
}
NSLog(@"read: %@", characteristic);
}
Write
キャラクタリスティックの値に書込処理
Write処理を追加すれば、キャラクタリスティックに値を書き込むことがきます。
例えば、0x01を書き込みたい場合には、中身が0x01のNSData型のデータを作り、
[peripheral writeValue:データ forCharacteristic:キャラクタリスティック type:Property];
で書き込み処理を行います。
propertyはWrite Without Response(Bluetooth機器からレスポンスなし) か Write(Bluetooth機器からレスポンスあり) になります。
int value = 0x01;
NSData *data = [[NSData alloc] initWithBytes:&value length:1];
[self.get_peripheral writeValue:data forCharacteristic:service.characteristics[i] type:CBCharacteristicWriteWithoutResponse];
//Write_結果
-(void) peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"error: %@", error);
return;
}
NSLog(@"write: %@", characteristic);
}
Notify
キャラクタリスティックの値の更新時の処理
[peripheral setNotifyValue:YES forCharacteristic:キャラクタリスティック];
でBluetooth機器からデータの更新があった場合に通知を送れるようになります。
更新があった場合、Readが呼び出されます。
//データの更新通知_開始
[self.get_peripheral setNotifyValue:YES forCharacteristic:service.characteristics[i]];
//データの更新通知_終了
[self.get_peripheral setNotifyValue:NO forCharacteristic:service.characteristics[i]];
//通知の設定を変更した場合のみ実行
- (void) peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"error: %@", error);
} else {
NSLog(@"Notify_成功");
}
}