博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CoreBluetooth蓝牙4.0的封装
阅读量:5041 次
发布时间:2019-06-12

本文共 5766 字,大约阅读时间需要 19 分钟。

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

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

DSBluetoothTool.h

 

#import 
#import
@protocol DSBluetoothToolDelegate
@optional/*************扫描到蓝牙设备时调用**********************/- (void) peripheralFound:(CBPeripheral *)peripheral;/*************连接上设备时调用***********************/- (void) setConnect;/*************断开连接时调用***********************/- (void) setDisconnect;/*************出现低电量时调用************************/- (void) lowBattery;/*************读取设备版本号**************************/- (void) ballVersions:(NSString *)versions;/*************读取设备ID**************************/- (void) ID:(NSString *)str;@end@interface DSBluetoothTool : NSObject
@property (nonatomic, strong)id
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

 

转载于:https://www.cnblogs.com/DLS520/p/5106670.html

你可能感兴趣的文章
javascript String
查看>>
ecshop 系统信息在哪个页面
查看>>
【转】码云source tree 提交超过100m 为什么大文件推不上去
查看>>
Oracle数据库的增、删、改、查
查看>>
MySql执行分析
查看>>
git使用中的问题
查看>>
yaml文件 .yml
查看>>
linux字符集修改
查看>>
phpcms 添加自定义表单 留言
查看>>
mysql 优化
查看>>
读书笔记 ~ Nmap渗透测试指南
查看>>
WCF 配置文件
查看>>
动态调用WCF服务
查看>>
oracle导出/导入 expdp/impdp
查看>>
类指针
查看>>
css修改滚动条样式
查看>>
2018.11.15 Nginx服务器的使用
查看>>
Kinect人机交互开发实践
查看>>
百度编辑器UEditor ASP.NET示例Demo 分类: ASP.NET...
查看>>
JAVA 技术类分享(二)
查看>>