美文网首页IOS开发
分包发送蓝牙数据

分包发送蓝牙数据

作者: 上尉H借个火 | 来源:发表于2018-03-20 09:40 被阅读0次

    这里以20个字节为一个发送

    //写入数据
    
    - (void)writeData:(NSData *)data
    
    {
    
    NSLog(@"send:%@", data);
    _responseTimer = [NSTimer scheduledTimerWithTimeInterval:_responseInterval target:self selector:@selector(timeoutForResponse) userInfo:nil repeats:NO];
    if (self.writingChar && self.notifyChar)
    {
        int len = (int)[data length];
        //当写入的数据大于20个字节时,分包发送
        if (len > 20){
            /**
           *  subdataWithRange( , );
           *  @param 0  从第0个字节开始截取
           *  @param 20 截取数据长度为20
           */
    
           NSData *dataTemp = [data subdataWithRange:NSMakeRange(0, 20)];
    
           /**
           dataTemp:           写入的数据
           self.writingChar:   写给哪些特征
           CBCharacteristicWriteWithResponse:   通过此响应纪录是否写入成功
           */
    
           [self.cbPeripheral writeValue:dataTemp forCharacteristic:self.writingChar   type:CBCharacteristicWriteWithResponse];
    
           /**
           举例:
           if(len == 43),则 len / 20 == 2;
           i == 0;
           i == 1;
           if(i == 0), 则 len - (20 + 20 * i) == 23;
           if(i == 1), 则 len - (20 + 20 * i) == 3;
           */
    
           //这里分包发送
           for (int i = 0; i < len / 20; i++)
           {
                 int lenTemp = 20;
                 if ((len - (20 + 20 * i) < 20) && (len - (20 + 20 * i) > 0)) {//i == 1
                        lenTemp = len - (20 + 20 * i);
                 }
                 if (len - (20 + 20 * i) > 0){//i ==0;
                       dataTemp = [data subdataWithRange:NSMakeRange(20 + 20 * i, lenTemp)];
                       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                       [self.cbPeripheral writeValue:dataTemp forCharacteristic:self.writingChar type:CBCharacteristicWriteWithResponse];
                       });
                 }
             }
       }else{//小于20个字节时,直接写入
          [self.cbPeripheral writeValue:data forCharacteristic:self.writingChar type:CBCharacteristicWriteWithResponse];
       }
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       Byte b[] = {3};
       [self.cbPeripheral writeValue:[NSData dataWithBytes:b length:1] forCharacteristic:self.notifyChar type:CBCharacteristicWriteWithResponse];
       });
    }else{
        NSLog(@"木有找到");
        self.sendData = data;
        [self.cbPeripheral discoverServices:nil];
    }
    }
    

    相关文章

      网友评论

        本文标题:分包发送蓝牙数据

        本文链接:https://www.haomeiwen.com/subject/owyuqftx.html