0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【CoreBluetooth】キャラクタリスティックの値取得について

Last updated at Posted at 2019-09-01

概要

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_成功");
    }   
}

参考
https://qiita.com/shu223/items/78614325ce25bf7f4379

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?