您的位置:首页 > 移动开发 > IOS开发

iOS  蓝牙分段发送数据代码

2016-08-26 16:17 1061 查看
//
蓝牙的支持能力是每命令发送20byte

超过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];
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息