蓝牙4.0整理(OC)

2017-11-15  本文已影响72人  六两

记录用。
手机连蓝牙外设,读取信息,发送指令,监控蓝牙状态,数据实时更新(500毫秒一次)。
首先引入

#import<CoreBluetooth/CoreBluetooth.h>

代理<CBCentralManagerDelegate,CBPeripheralDelegate>

//中央管理者 -->管理设备的扫描 --连接 
@property (nonatomic, strong) CBCentralManager *centralManager;

蓝牙一共6种状态,初始化CBCentralManager,系统会调用- (void)centralManagerDidUpdateState:(CBCentralManager *)central代理方法,根据central.state判断蓝牙状态

- (CBCentralManager *)centralManager
{
    if (!_centralManager)
    {
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    return _centralManager;
}
// 状态更新时调用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBManagerStateUnknown:{
            NSLog(@"为知状态");
            self.peripheralState = central.state;
        }
            break;
        case CBManagerStateResetting:
        {
            NSLog(@"重置状态");
            self.peripheralState = central.state;
        }
            break;
        case CBManagerStateUnsupported:
        {
            NSLog(@"不支持的状态");
            self.peripheralState = central.state;
        }
            break;
        case CBManagerStateUnauthorized:
        {
            NSLog(@"未授权的状态");
            self.peripheralState = central.state;
        }
            break;
        case CBManagerStatePoweredOff:
        {
            NSLog(@"关闭状态");
            self.peripheralState = central.state;
            self.getBlueStateBlock(4, @"未开启蓝牙(自动)");
        }
            break;
        case CBManagerStatePoweredOn:
        {
            NSLog(@"开启状态-可用状态");
            self.peripheralState = central.state;
            NSLog(@"%ld",(long)self.peripheralState);
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        }
            break;
        default:
            break;
    }
}

注意看上面开启的状态,加入[self.centralManager scanForPeripheralsWithServices:nil options:nil];
这个会让手机开始扫描蓝牙外设。
然后进入代理方法- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral )peripheral advertisementData:(NSDictionary)advertisementData RSSI:(NSNumber *)RSSI
// [NSString stringWithFormat:@"发现蓝牙设备,设备名:%@",peripheral.name];
//iphone会不断扫描周边的蓝牙设备,在里面找到你的外设。

!!重点,尽量和你的硬件工程师连调!!

找到你的蓝牙外设之后,执行[self.centralManager connectPeripheral:peripheral options:nil];连接你的外设

根据(连接成功,失败)连接状态会走两个方法,先说成功的

连接成功进入----->

/**
 连接成功
 @param central 中心管理
 @param peripheral 连接成功的设备
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    // 设置设备的代理
    peripheral.delegate = self;
    // services:传入nil  代表扫描所有服务
    [peripheral discoverServices:nil];
}

然后进入- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

/**
 扫描到对应的特征
 @param peripheral 设备
 @param service 特征对应的服务
 @param error 错误信息
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    // 遍历所有的特征
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        NSLog(@"特征值:%@",characteristic.UUID.UUIDString);
        NSLog(@"服务server:%@ 的特征:%@, 读写属性:%ld", service.UUID.UUIDString, characteristic, characteristic.properties);
//1.只读
        if ([characteristic.UUID.UUIDString isEqualToString:@"根据协议上的说明放入可读特征字符串"])
        {
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
//2.读写 发送指令就是写。而且无论读写都会进入一个代理方法,方法我会写在结尾
        if ([characteristic.UUID.UUIDString isEqualToString:@"根据协议上的说明放入可读写特征字符串"])
        {
            //发送指令要根据协议是发送16进制data还是8进制(我是16进制,一样就直接复制,如果是8进制搜去吧)
            NSString *signal = @"你要发送的指令";
          //先转换成16进制字符串,然后转换成16进制data,我都写下面了,找一下
          NSString *signalStr = [self convertStringToHexStr:signal];
          NSData *signalData = [self stringToHexData:signalStr];
          //这里又会执行代理方法mmp
          [peripheral writeValue:signalData forCharacteristic:characteristic  type:CBCharacteristicWriteWithResponse];
        }
    }
}
//将NSString转换成十六进制的字符串则可使用如下方式:
- (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}
//将16进制的字符串转换成NSData
- (NSData *) stringToHexData:(NSString *)hexStr
{
    int len = [hexStr length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    
    int i;
    for (i=0; i < [hexStr length] / 2; i++) {
        byte_chars[0] = [hexStr characterAtIndex:i*2];
        byte_chars[1] = [hexStr characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}
//写入数据后的回调
//用于检测中心向外设写数据是否成功
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
NSLog(@"peripheral.name=%@,peripheral.services=%@",peripheral.name,peripheral.services);
    if (error) {  
        NSLog(@"%s, line = %d, erro = %@",__FUNCTION__,__LINE__,error.description);
    }
}
/**
 根据特征读到数据
 @param peripheral 读取到数据对应的设备
 @param characteristic 特征
 @param error 错误信息
 */
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    if ([characteristic.UUID.UUIDString isEqualToString:@“外设特征”])
    {
        if (characteristic.value != NULL) {
            NSData *myD = characteristic.value;
            Byte *bytes = (Byte *)[myD bytes];
            //下面是Byte 转换为16进制。
            NSString *hexStr=@"";
            for(int i=0;i<[myD length];i++){
                NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
                if([newHexStr length]==1)
                    hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
                else
                    hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
            }
            char *myBuffer = (char *)malloc((int)[hexStr length] / 2 + 1);
            bzero(myBuffer, [hexStr length] / 2 + 1);
            for (int i = 0; i < [hexStr length] - 1; i += 2) {
                unsigned int anInt;
                NSString * hexCharStr = [hexStr substringWithRange:NSMakeRange(i, 2)];
                NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
                [scanner scanHexInt:&anInt];
                myBuffer[i / 2] = (char)anInt;
            }
            NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
            NSLog(@"从蓝牙接收到的数据,并转化为NSString=%@<---",unicodeString);
        }
    }
}

完。

上一篇下一篇

猜你喜欢

热点阅读