蓝牙分包发送数据 在包前面加上包头

int BLE_SEND_MAX_LEN = 256;
    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 *content = [msgData subdataWithRange:NSRangeFromString(rangeStr)];

            
            Byte byteData[2] = {};
            int right,left;
             
            byteData[0] =(Byte)(right = (i/256 +1) & 0x00ff); // 取低8位 221 0xDD
                
            byteData[1] =(Byte)(left = (i/256 + 1) >> 8); //取高8位 223 0xDF
                
            Byte byte[] = {0x01,0x81,0x01,byteData[0],byteData[1]};
            
            
            
            NSData *temphead = [[NSData alloc]initWithBytes:byte length:5];
            
            //拼接content
            NSMutableData *m_data = [[NSMutableData alloc] init];
            [m_data appendData:temphead];
            [m_data appendData:content];
            
            uint8_t *sendByte = [m_data bytes];
            [self send_data:sendByte length:sizeof(sendByte)];
            
           // NSLog(@"%@",m_data);
           // [self.currPeripheral writeValue:subData forCharacteristic:self.
           // characteristic type:CBCharacteristicWriteWithResponse];
            //根据接收模块的处理能力做相应延时
            usleep(20 * 1000);
        } else {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([msgData length] - i)];
            NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
            [self.currPeripheral writeValue:subData forCharacteristic:self.
            characteristic type:CBCharacteristicWriteWithResponse];
            usleep(20 * 1000);
        }

猜你喜欢

转载自blog.csdn.net/zhoudaxiaq/article/details/106215929