美文网首页
iOS编程蓝牙的分包发送

iOS编程蓝牙的分包发送

作者: 单线程Jack | 来源:发表于2019-07-18 15:09 被阅读0次
BLE_SEND_MAX_LEN是蓝牙单次可处理最大字节长度

//分包发送蓝牙数据
-(void)sendMsgWithSubPackage:(NSData*)msgData 
                  Peripheral:(CBPeripheral*)peripheral
              Characteristic:(CBCharacteristic*)character
{
    for (int i = 0; i < [msgData length]; i += BLE_SEND_MAX_LEN) {
        // 预加 最大包长度,如果依然小于总数据长度,可以取最大包数据大小
        if ((i + BLE_SEND_MAX_LEN) < [msgData length]) {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, BLE_SEND_MAX_LEN];
            NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
            NSLog(@"%@",subData);
            [self writeCharacteristic:peripheral
                       characteristic:character
                                value:subData];
            //根据接收模块的处理能力做相应延时
            usleep(20 * 1000);
        }
        else {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([msgData length] - i)];
            NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
            [self writeCharacteristic:peripheral
                       characteristic:character
                                value:subData];
            usleep(20 * 1000);
        }
    }
}

相关文章

网友评论

      本文标题:iOS编程蓝牙的分包发送

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