vaguely

和歌山に戻りました。ふらふらと色々なものに手を出す毎日。

MacとiOSをBLEで連携 - Central編2

前回の続きです。

基本的にはPeripheralと同じで、1秒に1回データを更新する部分を、ボタン押下時にデータ送信されるよう変更しているだけです。

ViewController.h

#import 

@interface ViewController : UIViewController
@end

ViewController.m

#import "ViewController.h"
#import "CentralController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField    *txtGotValue;
@property (weak, nonatomic) IBOutlet UITextField    *txtSendValue;
@property (weak, nonatomic) IBOutlet UIButton       *btnSend;
@property (strong, nonatomic) CentralController     *ctrCentral;
@property (strong, nonatomic) NSTimer               *tmrUpdateText;
@property (nonatomic) int                           intSendValue;
- (IBAction)btnSendTouched:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _ctrCentral = [[CentralController alloc] init];
    [_ctrCentral initCentralController];
    
    // タイマーの起動.
    [self startUpdateTextTimer];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
- (void)startUpdateTextTimer
{
    // 0.05秒ごとにPeripheralから取得した値を更新.
    _tmrUpdateText = [NSTimer scheduledTimerWithTimeInterval:0.05f target:self selector:@selector(updateText:) userInfo:nil repeats:YES];
}
- (void)updateText:(NSTimer *)timer
{
    // Centralから取得した値をTextFieldに入れる.
    _txtGotValue.text = [_ctrCentral getPeripheralValue];
    
    // 書き込みリクエストの結果.
    if([_ctrCentral getIsValueWrote])
    {
        NSLog(@"YES");
    }
    else
    {
        NSLog(@"NO");
    }
}
- (void)stopUpdateLabelTimer
{
    if(_tmrUpdateText)
    {
        [_tmrUpdateText invalidate];
        _tmrUpdateText = nil;
    }
}
- (IBAction)btnSendTouched:(id)sender
{
    // ボタン押下で乱数をPeripheralに送信する.
    _intSendValue = (int)arc4random_uniform(999);
    _txtSendValue.text = [NSString stringWithFormat:@"%d", _intSendValue];
    [_ctrCentral sendValue:_intSendValue];
}
@end

課題

書き込みリクエストの際、結果がNO(Error)だった場合の処理が入っていないため、変更した方が良いかな、というところです。