iOS 蓝牙封装
2019-07-28 本文已影响0人
CaptainRoy
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@protocol BlueToothDelegate <NSObject>
@optional
//发现外设
- (void)didDiscoverPeripheral:(CBPeripheral *)peripheral;
//连接外设成功
- (void)didConnectPeripheral;
//连接外设失败
- (void)didFailToConnectPeripheral:(NSError *)error;
//断开与外设的连接
- (void)didDisconnectPeripheral:(NSError *)error;
//发现特性
- (void)didDiscoverCharacteristics:(CBCharacteristic *)characteristic;
//收到蓝牙回应的数据
- (void)getDataFromeBlueTooth:(NSString *)resultString;
@end
@interface QSSBlueTooth : NSObject
+ (QSSBlueTooth *)sharedClient;
- (void)stopScanPeripheral;
- (void)scanPeripheral:(id<BlueToothDelegate>)del;
- (void)connectPeripheral:(id<BlueToothDelegate>)del peripheral:(CBPeripheral *)peripheral;
- (void)cancelConnectPeripheral:(CBPeripheral *)peripheral;
- (void)writeValue:(NSArray *)characterArray command:(NSString *)command;
@end
#import "QSSBlueTooth.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+Add.h"
@interface QSSBlueTooth () <CBCentralManagerDelegate, CBPeripheralDelegate>
@property (assign) BOOL isConnect;
@property (nonatomic, strong) NSMutableArray *resultArray;
@property (nonatomic, strong) CBCentralManager *centralManger;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, weak) id<BlueToothDelegate> delegate;
@end
@implementation QSSBlueTooth
+ (QSSBlueTooth *)sharedClient
{
static QSSBlueTooth *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[QSSBlueTooth alloc] init];
});
return _sharedClient;
}
- (id)init
{
self = [super init];
if (self) {
self.isConnect = NO;
self.resultArray = [[NSMutableArray alloc] init];
self.centralManger = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
return self;
}
- (void)scanPeripheral:(id<BlueToothDelegate>)del
{
self.delegate = del;
[self.centralManger scanForPeripheralsWithServices:nil options:nil];
}
- (void)stopScanPeripheral
{
[self.centralManger stopScan];
}
- (void)connectPeripheral:(id<BlueToothDelegate>)del peripheral:(CBPeripheral *)peripheral
{
if (self.peripheral) {
[self cancelConnectPeripheral:self.peripheral];
self.peripheral = nil;
}
self.delegate = del;
self.peripheral = peripheral;
self.peripheral.delegate = self;
self.isConnect = YES;
[self.centralManger connectPeripheral:self.peripheral options:nil];
}
- (void)cancelConnectPeripheral:(CBPeripheral *)peripheral
{
self.isConnect = NO;
[self.centralManger cancelPeripheralConnection:peripheral];
}
- (void)writeValue:(NSArray *)characterArray command:(NSString *)command
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *subCommand = command;
while (1) {
if (subCommand.length > 16) {
[dataArray addObject:[subCommand substringWithRange:NSMakeRange(0, 16)]];
subCommand = [subCommand substringWithRange:NSMakeRange(16, subCommand.length-16)];
}
else {
[dataArray addObject:subCommand];
break;
}
}
[self.resultArray removeAllObjects];
for (CBCharacteristic *c in characterArray) {
if ([c.UUID isEqual:[CBUUID UUIDWithString: @"FFE1"]]) {
for (NSInteger i=0; i<[dataArray count]; i++) {
NSData *data = [[dataArray objectAtIndex:i] dataUsingEncoding:NSUTF8StringEncoding];
[self.peripheral writeValue:data forCharacteristic:c type:CBCharacteristicWriteWithoutResponse];
[NSThread sleepForTimeInterval:0.04];
}
}
}
}
#pragma mark -
#pragma mark CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if (central.state == CBCentralManagerStatePoweredOn) {
NSLog(@"BLE状态正常");
}
else {
NSLog(@"设备不支持BLE或者未打开");
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
if ([self.delegate respondsToSelector:@selector(didDiscoverPeripheral:)]) {
[self.delegate didDiscoverPeripheral:peripheral];
}
}
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
if ([self.delegate respondsToSelector:@selector(didConnectPeripheral)]) {
[self.delegate didConnectPeripheral];
}
[peripheral discoverServices:nil];
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
if ([self.delegate respondsToSelector:@selector(didFailToConnectPeripheral:)]) {
[self.delegate didFailToConnectPeripheral:error];
}
}
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
if (self.isConnect) {
[self.centralManger connectPeripheral:self.peripheral options:nil];
}
else {
if ([self.delegate respondsToSelector:@selector(didDisconnectPeripheral:)]) {
[self.delegate didDisconnectPeripheral:error];
}
}
}
#pragma mark -
#pragma mark CBPeripheralDelegate
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (error) {
NSLog(@"发现服务时发生错误:%@",error);
}
else {
NSLog(@"发现服务:%@",peripheral.services);
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
}
}
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (error) {
NSLog(@"%@",error);
}else {
NSLog(@"%@%lu", service.UUID, (unsigned long)service.characteristics.count);
}
for (CBCharacteristic *characteristic in service.characteristics) {
[peripheral readValueForCharacteristic:characteristic];
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
if ([self.delegate respondsToSelector:@selector(didDiscoverCharacteristics:)]) {
[self.delegate didDiscoverCharacteristics:characteristic];
}
}
}
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"写数据错误:%@",error);
}
else {
// [[[UIAlertView alloc] initWithTitle:@"发送数据成功" message:[NSString stringWithFormat:@"设备:%@ 特性:%@", peripheral, characteristic] delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil] show];
NSLog(@"数据发送成功");
}
}
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"读数据错误:%@",error);
}
else {
NSData *data=characteristic.value;
NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if (string && string.length > 0 && ![string containsString:@"\0"]) {
[self.resultArray addObject:string];
}
if ([self.resultArray count] > 0) {
NSString *resultString = [self.resultArray componentsJoinedByString:@""];
if ([resultString containsString:@"</BTDATA>"]) {
if ([self.delegate respondsToSelector:@selector(getDataFromeBlueTooth:)]) {
[self.delegate getDataFromeBlueTooth:resultString];
}
[self.resultArray removeAllObjects];
}
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"通知错误:%@",error);
}
else {
}
}
@end