CoreBluetooth蓝牙4.0的封装

随着智能家居的发展,蓝牙技术越发重要,尤其是蓝牙4.0.以下是我对蓝牙4.0的封装。

使用时只需导入这个蓝牙类即可。

DSBluetoothTool.h

 

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@protocol DSBluetoothToolDelegate <NSObject>
@optional
/*************扫描到蓝牙设备时调用**********************/
- (void) peripheralFound:(CBPeripheral *)peripheral;
/*************连接上设备时调用***********************/
- (void) setConnect;
/*************断开连接时调用***********************/
- (void) setDisconnect;
/*************出现低电量时调用************************/
- (void) lowBattery;
/*************读取设备版本号**************************/
- (void) ballVersions:(NSString *)versions;
/*************读取设备ID**************************/
- (void) ID:(NSString *)str;
@end
@interface DSBluetoothTool : NSObject<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic, strong)id<DSBluetoothToolDelegate>delegate;
+(DSBluetoothTool *)shareBluetooth;
/**
 *  扫描蓝牙
 */
-(void)scanfBlueToothWith:(int)timeout;
/**
 *  连接蓝牙设备
 *
 *  @param peripheral 扫描到的蓝牙设备
 */
-(void)connect:(CBPeripheral *)peripheral;
/**
 *  断开蓝牙
 *
 *  @param peripheral 需要断开的蓝牙设备
 */
-(void)disconnect:(CBPeripheral *)peripheral;
/**
 *  给设备发送指令
*/
-(void) write:(CBPeripheral *)peripheral data:(NSString *)data;
/**
 *  读取蓝牙设备广播信息
*/
-(void) read:(CBPeripheral *)peripheral;
/**
 *  设备通知
 */
-(void) notify:(CBPeripheral *)peripheral on:(BOOL)on;


@end

 

DSBluetoothTool.m

 

#import "DSBluetoothTool.h"
#import "Commonds.h"

@interface DSBluetoothTool()
@property (nonatomic, strong)CBCentralManager *centeralManager;
@property (nonatomic, strong)CBPeripheral *peripheral;
@property (nonatomic, strong)CBCharacteristic *writeCharacter;

@end
@implementation DSBluetoothTool
/**
 *  懒加载中心设备
 */
-(CBCentralManager *)centeralManager{
    if (!_centeralManager) {
        _centeralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    };
    return _centeralManager;
}
+(DSBluetoothTool *)shareBluetooth{
    static DSBluetoothTool *inst;
    if(inst == nil){
        inst  = [[DSBluetoothTool alloc] init];
        
    }
    return inst;
}
#pragma mark -- 扫描蓝牙设备
-(void)scanfBlueToothWith:(int)timeout{
    if (self.centeralManager.state == CBCentralManagerStatePoweredOn) {
        [self.centeralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"0xFFF0"],[CBUUID UUIDWithString:@"0xFFE0"],[CBUUID UUIDWithString:@"0x18F0"]] options:0];
    }
    [NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:@selector(stopScanfBluetooth:) userInfo:nil repeats:NO];
    
}
#pragma mark -- 停止扫描蓝牙
-(void)stopScanfBluetooth:(NSTimer *)timer{
    [self.centeralManager stopScan];
    timer = nil;
}
#pragma mark -- 连接蓝牙
-(void)connect:(CBPeripheral *)peripheral{
    
    if (peripheral.state == CBPeripheralStateDisconnected) {
        [self.centeralManager connectPeripheral:peripheral options:nil];
    }
    NSLog(@"%@",peripheral);
}
#pragma mark -- 断开蓝牙
-(void)disconnect:(CBPeripheral *)peripheral{
    [self.centeralManager cancelPeripheralConnection:peripheral];
}
#pragma mark ---CBCentralManagerDelegate(扫描到蓝牙时调用)
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    
    self.peripheral = peripheral;
    [self.delegate peripheralFound:self.peripheral];
    
}
#pragma mark --- 连接上设备时调用
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    self.peripheral = peripheral;
    self.peripheral.delegate = self;
    [self.peripheral discoverServices:nil];
    [self.delegate setConnect];
}
#pragma mark --- 发送命令
-(void)write:(CBPeripheral *)peripheral data:(NSString *)data{

    [peripheral writeValue: [self convertHexStrToData:data]forCharacteristic:self.writeCharacter type:CBCharacteristicWriteWithoutResponse];
}
#pragma mark --- 发现服务时调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
    for (CBService *service in peripheral.services)
    {
        
        if ([service.UUID isEqual:[CBUUID UUIDWithString:SW20P_SERVICE_UUID]])
        {
            NSLog(@"发现20P的服务: %@", service.UUID);
            [peripheral discoverCharacteristics:nil forService:service];
            
            break;
        }
    }
}
#pragma mark -- 发现特征时调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:SW20P_CHAR_UUID]])
        {
            NSLog(@"发现20P的特征:%@ for service: %@", characteristic.UUID, service.UUID);
            
            self.writeCharacter = characteristic;//保存读的特征
            break;
        }
    }
}
//中新设备更新状态时调用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
}
-(void) read:(CBPeripheral *)peripheral{
    
}
/**
 *  设备通知
 */
-(void) notify:(CBPeripheral *)peripheral on:(BOOL)on{
    
}
#pragma mark -- 十六进制转换为NSData数据流
- (NSData *)convertHexStrToData:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    
    return hexData;
}

@end

 

  

 

源码连接地址:http://pan.baidu.com/s/1i4pHKDv

 

你可能感兴趣的:(CoreBluetooth蓝牙4.0的封装)