Skip to content
coolnameismy edited this page May 5, 2016 · 3 revisions

BabyRhythm

程序心跳:可以给peripheral的具体操作加上心跳进行监控,从而达到一些复杂控制的需求。

方法

//心跳
-(void)beats;
//主动中断心跳
-(void)beatsBreak;
//结束心跳,结束后会进入BlockOnBeatOver,并且结束后再不会在触发BlockOnBeatBreak
-(void)beatsOver;
//恢复心跳,beatsOver操作后可以使用beatsRestart恢复心跳,恢复后又可以进入BlockOnBeatBreak方法
-(void)beatsRestart;

//心跳中断的委托
-(void)setBlockOnBeatBreak:(void(^)(BabyRhythm *bry))block;
//心跳结束的委托
-(void)setBlockOnBeatOver:(void(^)())block;

//心跳时间间隔,默认是3
@property int beatsInterval;

example

因为central对peripheral的操作是离散的,没有完成状态的。有时候我们需要确认相关操作完成才进行下一步操作。例如需求:先读取c1的值,然后将c2的值设为c1的值,最后开启c3的notify获取数据

  @implementation xxxx{
      //建议新建一个class,用属性保存c1,c2,c3,不然可能会出现黄色的警告。
      CBCharacteristic *c1;
      CBCharacteristic *c2;
      CBCharacteristic *c3;
  }

  .... //省略中间操作和代码

 BabyRhythm *rhythm = [[BabyRhythm alloc]init];

 [baby setBlockOnDiscoverCharacteristicsAtChannel:channelOfLoadloadHistoryData block:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        //心跳
        [rhythm beats];
        for (CBCharacteristic *characteristic in service.characteristics) {
            //c1
            if ([characteristic.UUID.UUIDString isEqualToString:@"FFA4"]) {
                c1 = characteristic;
            }
            //c2
            if ([characteristic.UUID.UUIDString isEqualToString:@"FFA3"]) {
                c2 = characteristic;
            }
        }
    }];
    
    [baby setBlockOnReadValueForCharacteristicAtChannel:channelOfLoadloadHistoryData block:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        //心跳,每进入方法就跳一次,超过beatsInterval的时间就会进入setBlockOnBeatBreak,我们可以通过它判断数据是否全部读取完毕。
        [rhythm beats];
        //c2值写进c1
        if ([characteristic.UUID.UUIDString isEqualToString:@"FFA6"]) {
            [device.peripheral writeValue:c2.value forCharacteristic:c1 type:CBCharacteristicWriteWithResponse];
        }
    }];

    [rhythm setBlockOnBeatsBreak:^(BabyRhythm *bry) {

        //[self check] 可以具体验证下c1和c2值是否符合条件
        //若不符合条件继续发送心跳[bry beats];
        //若符合条件,则关闭心跳,订阅c3
        if ([self check]) {
            //关闭beats           
            [baby notify:device.peripheral characteristic:c3 block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
               //业务代码
            }];
 
        }
        [bry beats];
    }];

Clone this wiki locally