//
表示中
モノづくり, Computer - コンピューター, Electronics - 電子工作

CoreBluetoothでKonashiを扱ってみる


KonashiはBluetooth LEに準拠したモジュールなので当然のようにiOSのCoreBluetoothフレームワークを利用してプログラムを作成することができます。
「車輪を発明する」という言葉がありますが、すでにKonashiを利用するためのフレームワーク(konashi-ios-sdk)があるのでこれをやる意味をあまり感じませんが、仕組みを知るということは大事ですのでやってみました。

以下のコードはKonashiを探し、接続を確立し、デバイス情報とバッテリーレベルを読み取るものです。
CBCentralManagerの起動する、Konashiを探す、Konashiに接続する、Konashiのサービスを全て表示する、利用するサービスを特定する、利用するサービスの機能(Characteristic)を全て表示する、利用するサービスの機能を特定して値を読み出す、と1ステップずつ機能を確認しながらここに辿り着きました。

ViewController.h

#import <UIKit/UIKit.h>

@import CoreBluetooth;

#define KONASHI_DEVICE_INFO_SERVICE_UUID @"180A"
#define KONASHI_BATTERY_SERVICE_UUID @"180F"

#define KONASHI_MANUFACTURER_NAME_UUID @"2A29"
#define KONASHI_FIRMWARE_REVISION_UUID @"2A26"
#define KONASHI_HARDWARE_REVISION_UUID @"2A27"
#define KONASHI_SOFTWARE_REVISION_UUID @"2A28"
#define KONASHI_BATTERY_LEVEL_UUID @"2A19"

@interface ViewController : UIViewController <CBCentralManagerDelegate, 
    CBPeripheralDelegate>

@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *peripheral;

@property (nonatomic, strong) NSString *connected;
@property (nonatomic, strong) NSString *manufacturer;
@property (nonatomic, strong) NSString *firmwareRevision;
@property (nonatomic, strong) NSString *hardwareRevision;
@property (nonatomic, strong) NSString *softwareRevision;
@property (nonatomic, strong) NSString *batteryLevel;

@property (nonatomic, weak) IBOutlet UILabel *connectedField;
@property (nonatomic, weak) IBOutlet UILabel *manufacturerField;
@property (nonatomic, weak) IBOutlet UILabel *firmwareRevisionField;
@property (nonatomic, weak) IBOutlet UILabel *hardwareRevisionField;
@property (nonatomic, weak) IBOutlet UILabel *softwareRevisionField;
@property (nonatomic, weak) IBOutlet UILabel *batteryLevelField;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.connectedField setText:@""];
    [self.manufacturerField setText:@""];
    [self.firmwareRevisionField setText:@""];
    [self.hardwareRevisionField setText:@""];
    [self.softwareRevisionField setText:@""];
    [self.batteryLevelField setText:@""];

    CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self 
        queue:dispatch_get_main_queue()];
    self.centralManager = centralManager;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManager:(CBCentralManager *)central 
    didConnectPeripheral:(CBPeripheral *)peripheral
{
    [peripheral setDelegate:self];
    [peripheral discoverServices:nil];
    self.connected = [NSString stringWithFormat:@"%@", 
        peripheral.state == CBPeripheralStateConnected ? @"YES" : @"NO"];
    NSLog(@"%@", self.connected);
    self.connectedField.text = self.connected;
}

- (void)centralManager:(CBCentralManager *)central 
    didDiscoverPeripheral:(CBPeripheral *)peripheral 
    advertisementData:(NSDictionary *)advertisementData 
    RSSI:(NSNumber *)RSSI
{
    NSString *localName = [advertisementData objectForKey:CBAdvertisementDataLocalNameKey];
    if([localName length] > 0) {
        NSLog(@"Found the Konashi: %@", localName);
        [self.centralManager stopScan];
        self.peripheral = peripheral;
        peripheral.delegate = self;
        [self.centralManager connectPeripheral:peripheral options:nil];
    }
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    if([central state] == CBCentralManagerStatePoweredOff) {
        NSLog(@"CoreBluetooth BLE hardware is powered off");
    } else if([central state] == CBCentralManagerStatePoweredOn) {
        NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
        [self.centralManager scanForPeripheralsWithServices:nil 
            options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}];

    } else if([central state] == CBCentralManagerStateUnknown) {
        NSLog(@"CoreBluetooth BLE hardware is unknown");
    } else if([central state] == CBCentralManagerStateUnsupported) {
        NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
    }
}

#pragma mark - CBPeripheralDelegate

- (void)peripheral:(CBPeripheral *)peripheral 
    didDiscoverServices:(NSError *)error
{
    for (CBService *service in peripheral.services) {
        NSLog(@"Discovered service: %@", service.UUID);
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral 
    didDiscoverCharacteristicsForService:(CBService *)service 
    error:(NSError *)error
{
    if([service.UUID isEqual:[CBUUID UUIDWithString:KONASHI_DEVICE_INFO_SERVICE_UUID]]) {
        for(CBCharacteristic *aChar in service.characteristics) {
            if([aChar.UUID isEqual:[CBUUID UUIDWithString:KONASHI_MANUFACTURER_NAME_UUID]]) {
                [self.peripheral readValueForCharacteristic:aChar];
            }
            if([aChar.UUID isEqual:[CBUUID UUIDWithString:KONASHI_FIRMWARE_REVISION_UUID]]) {
                [self.peripheral readValueForCharacteristic:aChar];
            }
            if([aChar.UUID isEqual:[CBUUID UUIDWithString:KONASHI_HARDWARE_REVISION_UUID]]) {
                [self.peripheral readValueForCharacteristic:aChar];
            }
            if([aChar.UUID isEqual:[CBUUID UUIDWithString:KONASHI_SOFTWARE_REVISION_UUID]]) {
                [self.peripheral readValueForCharacteristic:aChar];
            }
        }
    }
    if([service.UUID isEqual:[CBUUID UUIDWithString:KONASHI_BATTERY_SERVICE_UUID]]) {
        for(CBCharacteristic *aChar in service.characteristics) {
            if([aChar.UUID isEqual:[CBUUID UUIDWithString:KONASHI_BATTERY_LEVEL_UUID]]) {
                [self.peripheral readValueForCharacteristic:aChar];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral 
    didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic 
    error:(NSError *)error
{
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:KONASHI_MANUFACTURER_NAME_UUID]]) {
        self.manufacturer = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        self.manufacturerField.text = self.manufacturer;
    }
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:KONASHI_FIRMWARE_REVISION_UUID]]) {
        self.firmwareRevision = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        self.firmwareRevisionField.text = self.firmwareRevision;
    }
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:KONASHI_HARDWARE_REVISION_UUID]]) {
        self.hardwareRevision = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        self.hardwareRevisionField.text = self.hardwareRevision;
    }
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:KONASHI_SOFTWARE_REVISION_UUID]]) {
        self.softwareRevision = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        self.softwareRevisionField.text = self.softwareRevision;
    }
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:KONASHI_BATTERY_LEVEL_UUID]]) {
        self.batteryLevel = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        self.batteryLevelField.text = self.batteryLevel;
    }
}

@end

実行結果がこちらです。

2016-03-23 12.20.34

kazz12211 について

Working as a OO programmer and enjoying music, bicycle and photography.

ディスカッション

コメントはまだありません。

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト / 変更 )

Twitter 画像

Twitter アカウントを使ってコメントしています。 ログアウト / 変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト / 変更 )

Google+ フォト

Google+ アカウントを使ってコメントしています。 ログアウト / 変更 )

%s と連携中

評価

ブログ統計

  • 593,676 ヒット

カテゴリー

アーカイブ

カレンダー

2016年3月
« 2月   4月 »
 12345
6789101112
13141516171819
20212223242526
2728293031  
%d人のブロガーが「いいね」をつけました。