IOS蓝牙连接和发送数据

首先要确定蓝牙是否打开
本文使用的是 Objective-C语言
1.新建一个蓝牙帮助类BlueHelp
并导入

pragma mark - CBPeripheralDelegate

//只要扫描到服务就会调用,其中的外设就是服务所在的外设
- (void)peripheral:(CBPeripheral )peripheral didDiscoverServices:(NSError )error{
if (error){
NSLog(@”扫描服务出现错误,错误原因:%@”,error);
}else{
//获取外设中所扫描到的服务
NSArray *services = peripheral.services;
for (CBService *service in services){
//拿到需要扫描的服务,例如打印一些服务数据
//把所有的service打印出来
NSLog(@”service is :%@”,service);
//从需要的服务中查找需要的特征
//从peripheral的services中扫描特征
[peripheral discoverCharacteristics:nil forService:service];
}
}
}

//只要扫描到特征就会调用,其中的外设和服务就是特征所在的外设和服务
- (void)peripheral:(CBPeripheral )peripheral didDiscoverCharacteristicsForService:(CBService )service error:(NSError *)error{
if (error){
NSLog(@”扫描特征出现错误,错误原因:%@”,error);
}else{
//拿到服务中所有的特征
NSArray *characteristics = service.characteristics;
//遍历特征,拿到需要的特征进行处理
for (CBCharacteristic *characteristic in characteristics){
NSLog(@”所有的特征为:%@”,characteristic.UUID.UUIDString);
//如果是温度数据处理
if([characteristic.UUID.UUIDString isEqualToString:@”你自己的特征值”]){
//将全部的特征信息打印出来
_peripheral = peripheral;
scperipheral = peripheral;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
NSLog(@”%@”,characteristic);
}
//这里是发送 设备设置蓝牙发送温度数据的值
else if([characteristic.UUID.UUIDString isEqualToString:@”你自己的特征值”]){
writecharacteristic = characteristic;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
NSLog(@”写入的值为:%@”,characteristic);
}
//如果是ota进行ota升级
else if([characteristic.UUID.UUIDString isEqualToString:@”你需要的特征值”]){
_peripheral = peripheral;
scperipheral = peripheral;
writeOtacharacteristic = characteristic;
//设置通知
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
//NSLog(@”OTA升级了”);
isOTA = TRUE;
NSString *s = @”OTA”;
NSDictionary *tempOta = [NSDictionary dictionaryWithObject:s forKey:@”ota”];
[[NSNotificationCenter defaultCenter] postNotificationName:@”tempOTA” object:nil userInfo:tempOta];
}
//无键按钮DFU
else if([characteristic.UUID.UUIDString isEqualToString:@”你自己需要的特征值”]){
writeDfucharacteristic = characteristic;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
NSLog(@”写入的OTA值为:%@”,characteristic);
}
}
}
}

/*
* 获取所有的温度更新数据
* 接收蓝牙发送过来的温度数据 并经过解析和转换
*/
- (void)peripheral:(CBPeripheral )peripheral didUpdateValueForCharacteristic:(CBCharacteristic )characteristic error:(NSError *)error
{
if ([characteristic.UUID isEqual:BOOT_LOADER_CHARACTERISTIC_UUID])
{
uint8_t dataPointer = (uint8_t ) [characteristic.value bytes];
NSString *errorCode = [NSString stringWithFormat:@”0x%2x”,dataPointer[1]];
errorCode = [errorCode stringByReplacingOccurrencesOfString:@” ” withString:@”0”];

    // Checking the error code from the response
    if ([errorCode isEqualToString:SUCCESS]&&commandArray.count>0)
    {
        if ([[commandArray objectAtIndex:0] isEqual:@(ENTER_BOOTLOADER)])
        {
            [self getBootLoaderDataFromCharacteristic:characteristic];
        }
        else if ([[commandArray objectAtIndex:0] isEqual:@(GET_FLASH_SIZE)])
        {
            [self getFlashDataFromCharacteristic:characteristic];
        }
        else if ([[commandArray objectAtIndex:0] isEqual:@(SEND_DATA)])
        {
            _isWritePacketDataSuccess = YES;
            [_userDefaults setBool:_isWritePacketDataSuccess forKey:@"WriteSuccess"];
        }
        else if ([[commandArray objectAtIndex:0] isEqual:@(PROGRAM_ROW)])
        {
            _isWritePacketDataSuccess = YES;
            [_userDefaults setBool:_isWritePacketDataSuccess forKey:@"WriteSuccess"];
        }

        else if ([[commandArray objectAtIndex:0] isEqual:@(VERIFY_ROW)])
        {
            [self getRowCheckSumFromCharacteristic:characteristic];
        }
        else if([[commandArray objectAtIndex:0] isEqual:@(VERIFY_CHECKSUM)])
        {
            [self checkApplicationCheckSumFromCharacteristic:characteristic];
        }

        if (cbCharacteristicUpdationHandler != nil)
        {
            cbCharacteristicUpdationHandler(YES,[commandArray objectAtIndex:0],nil);
            [commandArray removeObjectAtIndex:0];
        }

    }
    else
    {
        if(commandArray.count>0){
            if ([[commandArray objectAtIndex:0] isEqual:@(PROGRAM_ROW)])
            {
                _isWritePacketDataSuccess = NO;
            }
            else if ([[commandArray objectAtIndex:0] isEqual:@(SEND_DATA)])
            {
                _isWritePacketDataSuccess = NO;
            }
            if (cbCharacteristicUpdationHandler != nil)
            {
                cbCharacteristicUpdationHandler(YES,[commandArray objectAtIndex:0],nil);
                [commandArray removeObjectAtIndex:0];
            }
        }
    }
}
if(!isOTA&&!_isSendData){
    NSString *temps=[self getTempData:characteristic];
    NSArray *ss = [temps componentsSeparatedByString:@","];
    NSString *tempWendu =ss[0];
    NSString *tempSymbol = ss[1];

    self.currentDate = [NSDate date];

    NSString *dateString = [_dateformatter stringFromDate:self.currentDate];

    NSLog(@" ==save is time=== :%@",dateString);

    NSDate *logDate = [_dateformatter dateFromString:dateString];
    long logTime= (long)[logDate timeIntervalSince1970];
    if(temps!=nil&&![_bluename isEqualToString:@""]&&_bluename!=nil&&_bluename!=NULL){ //把数据存入到数据库
    NSString *a = [_userDefaults objectForKey:@"tempUnit"];
    //如果是华氏度的时候一定要把它转为摄氏度之后再来保存数据 以便数据的统一性
    if([a isEqualToString:@"°F"]){
        float floatString = [tempWendu floatValue];

        float aa = [_normalUtil convertFahrenheitToCelcius:floatString];

        NSString *ftempWendu =  [NSString stringWithFormat:@"%.1f",aa];
        NSString *ftempSymbol = @"°C";

        [_tempDao saveTempname:_bluename saveTempaddre:_blueaddre saveTempwenduname:ftempSymbol saveTempwendu:ftempWendu saveTemptime:logTime];
        }else{

            [_tempDao saveTempname:_bluename saveTempaddre:_blueaddre saveTempwenduname:tempSymbol saveTempwendu:tempWendu saveTemptime:logTime];
        }

        NSLog(@" ==save is success=== :%ld",logTime);
    }

    //当读取到数据的时候就要存入数据 以后用来蓝牙自动的去连接
    if(_saveAutoOnce){
        [_userDefaults setObject:_bluename forKey:@"autoBlueName"];
        [_userDefaults setObject:_blueaddre forKey:@"autoBlueAddre"];
        _saveAutoOnce = false;
    }

    NSString * tp = [temps stringByAppendingString:@","];

    NSString * tempp = [tp stringByAppendingString:_blueaddre];

    NSDictionary *tempDict = [NSDictionary dictionaryWithObject:tempp forKey:@"temp"];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"tempNofiction" object:nil userInfo:tempDict];
}

}

上面这些代码可以不看 我写的是一些数据的转换
下面我们可以看下蓝牙写入数据
//也可以自定义主要是给外部调用
//发送数据

-(void)writeBlueValue:(NSString *)value{
_isSendData = TRUE;
[self writeValue:value forCharacteristic:writecharacteristic];
}

/*
这个是给蓝牙发送数据用的
*/
-(void)writeValue:(NSString )value forCharacteristic:(CBCharacteristic )characteristic
{
// NSData *data = [value dataUsingEncoding:4];
NSData *data = [_normalUtil stringToBytes:value];
NSLog(@”send data is:%@:characteristic:%@”,data,writecharacteristic);
//is no write bluetooth data
if(writecharacteristic.properties & CBCharacteristicPropertyWriteWithoutResponse)
{
//send phone on bluetooth data
[selectPeriperal writeValue:data forCharacteristic:writecharacteristic type:CBCharacteristicWriteWithoutResponse];
}else
{
[selectPeriperal writeValue:data forCharacteristic:writecharacteristic type:CBCharacteristicWriteWithResponse];

}
//发送完成后 又要它归位
_isSendData = FALSE;
NSLog(@"已经向外设%@的特征值%@写入数据",selectPeriperal.name,writecharacteristic.description);

}

一般发送数据都需要用到 NSData数据类型格式下面我有几个方法
/**
* Method to convert hex to byteArray。这里是将16进制转换为NSData
*/

-(NSMutableData )dataFromHexString:(NSString )string
{
NSMutableData *data = [NSMutableData new];
NSCharacterSet *hexSet = [[NSCharacterSet characterSetWithCharactersInString:@”0123456789ABCDEF “] invertedSet];

// Check whether the string is a valid hex string. Otherwise return empty data
if ([string rangeOfCharacterFromSet:hexSet].location == NSNotFound) {

    string = [string lowercaseString];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i = 0;
    int length = (int)string.length;

    while (i < length-1)
    {
        char c = [string characterAtIndex:i++];

        if (c < '0' || (c > '9' && c < 'a') || c > 'f')
            continue;
        byte_chars[0] = c;
        byte_chars[1] = [string characterAtIndex:i++];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
}
return data;

}

还有一种是
//字符串转为数组
-(NSData )stringToBytes:(NSString )string{
int a = [string intValue];
NSData *aData = [string dataUsingEncoding: NSUTF8StringEncoding];
Byte testByte = (Byte )[aData bytes];
testByte[0] = (Byte)(a>>24&0xff);
testByte[1] = (Byte) (a>>16&0xff);
testByte[2] = (Byte)(a>>8&0xff);
testByte[3] = (Byte)(a&0xff);

NSData *adata = [[NSData alloc] initWithBytes:testByte length:4];

return adata;

}

这些方法比较常用的
好了基本思路就这样 源代码 过段时间放上来 。

你可能感兴趣的:(蓝牙4.0模块)