隨着智能家居的發展,藍牙技術愈加重要,尤爲是藍牙4.0.如下是我對藍牙4.0的封裝。app
使用時只需導入這個藍牙類便可。atom
DSBluetoothTool.hspa
#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.mcode
#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/1i4pHKDvblog