藍牙架構的搭建
#
import <Foundation/Foundation.h>#
import <CoreBluetooth/CoreBluetooth.h>#define kHMBluetoothManager [HMBluetoothManager shareInstance]
@interface HMBluetoothManager : NSObject
+(HMBluetoothManager*)shareInstance;
@property(nonatomic,strong)CBCentralManager *CB_central;
@property(nonatomic,strong)NSMutableArray <CBPeripheral *>*scanArr;
@property(nonatomic,strong)NSMutableArray <CBPeripheral *>*connectArr;
@property(nonatomic,copy)
void(^scanPeripheralUpdate)(CBPeripheral *peripheral);
@property(nonatomic,copy)
void(^connectedPeripheral)(CBPeripheral *peripheral,NSString *connectState);
@property(nonatomic,strong)CBPeripheral *currentPeripheral;
@property (strong ,nonatomic) CBCharacteristic *currentCharacteristic;
@property(nonatomic,strong)NSString *UUID;
/**檢測藍牙是否可用 @param completion 錯誤表示 可用標簽
@return 可用標簽*/
- (BOOL)isDeviceBluetoothAvaliable:(
void(^)(NSError *error,BOOL flag))completion;
/**開始掃描*/
- (
void)BeginScanPeripheral:(
void(^)(CBPeripheral *peripheral))scanPeripheralUpdate;
/**連接外設 @param peripheral 外設
@param connectedPeripheral 連接回調*/
- (
void)connectPeripheral:(CBPeripheral *)peripheral Completion:(
void(^)(CBPeripheral *peripheral,NSString *connectState))connectedPeripheral;
/**發送數據 @param value 數據
@param peripheral 外設
@param characteristic 特征*/
- (
void)writeValue:(NSData *)value toPeripheral:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic;
@end
#import "HMBluetoothManager.h"
#import <CoreBluetooth/CoreBluetooth.h>#define kDisconnectPeripheralNotification @"kDisconnectPeripheralNotification"const NSString *connectStateSuccess = @
"連接成功";
const NSString *connectStateRepeat = @
"外設已經在連接列表中";
const NSString *connectStateFaild = @
"連接失敗";
@interface HMBluetoothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>@end@implementation HMBluetoothManager
+(HMBluetoothManager*)shareInstance
{
static HMBluetoothManager *manager =
nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{manager = [[HMBluetoothManager alloc] init];});
return manager;
}- (instancetype)init
{
self = [
super init];
self.scanArr = [
NSMutableArray array];
self.connectArr = [
NSMutableArray array];
return self;
}
#pragma mark - 檢測藍牙是否可用
- (
BOOL)isDeviceBluetoothAvaliable:(
void(^)(
NSError *error,
BOOL flag))completion
{
NSString * state =
nil;
BOOL flag =
NO;
switch ([
self.CB_central state]){
case CBCentralManagerStateUnsupported:state = @
"系統不支持藍牙.";
break;
case CBCentralManagerStateUnauthorized:state = @
"手機藍牙未開啟";
break;
case CBCentralManagerStatePoweredOff:state = @
"Bluetooth is currently powered off.";
break;
case CBCentralManagerStatePoweredOn:state = @
"藍牙可用";flag =
YES;
break;
case CBCentralManagerStateUnknown:flag =
YES;state = @
"未知錯誤";
break;
default:
break;}
if ([state isEqualToString:@
"未知錯誤"]) {dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(
0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[
self.CB_central scanForPeripheralsWithServices:
nil options:
nil];});}
NSError *error = [
NSError errorWithDomain:@
"HMBluetoothManager" code:-
1 userInfo:@{NSLocalizedDescriptionKey:state}];
if (completion) {completion(error,flag);}
return flag;
}
#pragma mark - 1.開始掃描- (
void)BeginScanPeripheral:(
void(^)(CBPeripheral *peripheral))scanPeripheralUpdate
{
if (!
self.CB_central) {
self.CB_central = [[CBCentralManager alloc] initWithDelegate:
self queue:dispatch_get_main_queue()];}NSAssert([
self isDeviceBluetoothAvaliable:
nil], @
"手機不支持藍牙");
self.scanPeripheralUpdate = scanPeripheralUpdate;[
self.CB_central scanForPeripheralsWithServices:
nil options:
nil];
}
#pragma mark -3.連接外設- (
void)connectPeripheral:(CBPeripheral *)peripheral Completion:(
void(^)(CBPeripheral *peripheral,
NSString *connectState))connectedPeripheral
{
self.connectedPeripheral = connectedPeripheral;
if (peripheral
.state == CBPeripheralStateConnected) {connectedPeripheral(peripheral,connectStateRepeat);}
else{[
self.CB_central connectPeripheral:peripheral options:
nil];}
}
#pragma mark -藍牙中心代理
- (
void)centralManagerDidUpdateState:(CBCentralManager *)central
{}
#pragma mark - 2.掃描到外設
-(
void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(
NSDictionary *)advertisementData RSSI:(
NSNumber *)RSSI
{
NSLog(@
"%@",advertisementData);
NSLog(@
"%@",peripheral
.identifier);
NSLog(@
"%@",peripheral
.name);
NSLog(@
"%@",RSSI);
self.scanPeripheralUpdate(peripheral);
if (![
self.scanArr containsObject:peripheral]) {[
self.scanArr addObject:peripheral];}}
#pragma mark - 4.連接外設成功,開始尋找服務
- (
void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
self.connectedPeripheral(peripheral,connectStateSuccess);
self.currentPeripheral = peripheral;[
self.connectArr addObject:peripheral];[peripheral setDelegate:
self];[peripheral discoverServices:
nil];}
-(
void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(
NSError *)error
{
self.connectedPeripheral(peripheral,connectStateFaild);
}
- (
void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(
NSError *)error
{[[
NSNotificationCenter defaultCenter] postNotificationName:kDisconnectPeripheralNotification object:
nil userInfo:@{@
"key":peripheral}];[
self.connectArr removeObject:peripheral];}
#pragma mark CBPeripheralDelegate 外設代理#pragma mark- 5.發現服務,搜索特征
-(
void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(
NSError *)error{
if (error) {
NSLog(@
"Error discovering services: %@", [error localizedDescription]);
return;}
int i=
0;
for (CBService *s in peripheral
.services) {
NSLog(@
"%@",[
NSString stringWithFormat:@
"%d :服務 UUID: %@(%@)",i,s
.UUID.data,s
.UUID]);i++;[peripheral discoverCharacteristics:
nil forService:s];}
}
#pragma mark- 6.已搜索到某個服務的特征Characteristics
-(
void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(
NSError *)error{
if (error) {
NSLog(@
"Error discovering characteristics: %@", [error localizedDescription]);
return;}
for (CBCharacteristic *c in service
.characteristics) {
NSLog(@
"%@",[
NSString stringWithFormat:@
"發現特征的服務UUID:%@ 該特征UUID:%@",service
.UUID ,c
.UUID]);
if ([[c
.UUID UUIDString] isEqual:
self.UUID]) {
self.currentCharacteristic = c;}[peripheral setNotifyValue:
YES forCharacteristic:c];}}
#pragma mark- 獲取外設發來的數據,不論是read和notify,獲取數據都是從這個方法中讀取。
- (
void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(
NSError *)error
{
NSLog(@
"外設發送過來的數據:%@",characteristic
.value.description );
}
#pragma mark- 中心讀取外設實時數據
- (
void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(
NSError *)error {
if (error) {}
if (characteristic
.isNotifying) {[peripheral readValueForCharacteristic:characteristic];
NSLog(@
"%@",characteristic
.value);}
else { }
}
#pragma mark - 7.給特征發送數據
- (
void)writeValue:(NSData *)value toPeripheral:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic {[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
}
@end
總結
以上是生活随笔為你收集整理的03-iOS蓝牙架构搭建的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。