很多步骤来自网上,地址不记得了。 代码如下:
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)CBCentralManager *cbCentralMgr;
@property(nonatomic,strong)NSMutableArray *array;
@property(nonatomic,strong)CBPeripheral *BTPeripheral;
@property (nonatomic,strong) CBService *BTService;
@property (nonatomic,strong) CBCharacteristic *BTCharacteristic;
@property (nonatomic,strong) CBCharacteristic *BTCharacteristic1;
@end
static NSString * const kServiceUUID = @"0000fff0-0000-1000-8000-00805f9b34fb";//服务的UUID
static NSString * const kCharacteristicUUID = @"0000fff1-0000-1000-8000-00805f9b34fb";
static NSString * const kCharacteristicUUID1 = @"0000fff4-0000-1000-8000-00805f9b34fb";
static NSString * const CHARACTERISTICCONFIG = @"00002902-0000-1000-8000-00805f9b34fb";
#define golobadName @"5133954"
@implementation ViewController{
CBUUID *serviceUUID;
CBUUID *characterUUID;
CBUUID *characterUUID1;
CBUUID *descriptorUUID;
UIActivityIndicatorView *indicatorView;
}
@synthesize cbCentralMgr,BTPeripheral,BTCharacteristic,BTCharacteristic1,BTService;
- (void)viewDidLoad {
[super viewDidLoad];
/**
1. 初始化设备中心
初始化后会调用代理CBCentralManagerDelegate
**/
cbCentralMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.array = [[NSMutableArray alloc]init];
serviceUUID = [CBUUID UUIDWithString:kServiceUUID];
characterUUID = [CBUUID UUIDWithString:kCharacteristicUUID];
characterUUID1 = [CBUUID UUIDWithString:kCharacteristicUUID1];
descriptorUUID = [CBUUID UUIDWithString:CHARACTERISTICCONFIG];
indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:
UIActivityIndicatorViewStyleWhiteLarge];
indicatorView.center = self.view.center;
indicatorView.color = [UIColor redColor];
[indicatorView startAnimating];
[self.view addSubview:indicatorView];
}
#pragma mark ----CBCentralManagerDelegate 判断蓝牙是否可用
/**
* 2. 判断蓝牙是否可用
*/
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBCentralManagerStatePoweredOn:
NSLog(@"蓝牙可用");
[self searchBlue];
break;
case CBCentralManagerStatePoweredOff:
NSLog(@"蓝牙不可用");
break;
default:
break;
}
}
#pragma mark 扫描周边蓝牙设备
/**
*
* 3. 扫描周边蓝牙设备
*
*/
- (void)searchBlue{
//判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备 你可以指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备
// [self.manager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
[cbCentralMgr scanForPeripheralsWithServices:@[serviceUUID] options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
}
#pragma mark 发现周围的蓝牙设置
/**
* 4. 进行蓝牙连接
*
*
* 发现设备后即可连接该设备 调用完该方法后会调用代理CBCentralManagerDelegate的- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral表示连接上了设别
如果不能连接会调用 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
*/
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(@"周边蓝牙设备%@",peripheral.name);
if ([peripheral.name containsString:golobadName]) {
[cbCentralMgr stopScan]; // 停止扫描
BTPeripheral = peripheral;
// 开始连接蓝牙
[cbCentralMgr connectPeripheral:BTPeripheral options:nil];
}
}
#pragma mark 蓝牙连接成功, 然后找服务UUID
/**
* 5. 蓝牙连接成功,找设备上的指定服务
*
* 此时设备已经连接上了 你要做的就是找到该设备上的指定服务 调用完该方法后会调用代理CBPeripheralDelegate(现在开始调用另一个代理的方法了)的
(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
*/
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
NSString *str = peripheral.name;
str = [@"连接成功-->" stringByAppendingString:str];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"蓝牙连接" message:str delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
[alert show];
[indicatorView stopAnimating];
BTPeripheral.delegate = self;
[BTPeripheral discoverServices:[NSArray arrayWithObjects:serviceUUID, nil]];
}
#pragma mark 蓝牙连接失败
/**
* 5. 蓝牙连接失败
*/
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"蓝牙连接" message:@"连接失败" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
[alert show];
}
#pragma mark 连接服务端,返回的 服务端的一些数据,
/**
* 6. 连接成功后, 找到我们需要的服务。
在这个方法中我们要查找到我们需要的服务 然后调用discoverCharacteristics方法查找我们需要的特性
该discoverCharacteristics方法调用完后会调用代理CBPeripheralDelegate的
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
*
*/
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
NSLog(@"peripheral---------->%@------>%@",peripheral.services,error.localizedDescription);
if (peripheral.services) {
for (CBService *services in peripheral.services) {
NSLog(@"%@",services.UUID);
if ([services.UUID isEqual:serviceUUID]) {
BTService = services;
break;
}
}
}
// 检查Service正常后,开始打通这边的数据交互通道
if (BTService) {
[BTPeripheral discoverCharacteristics:[NSArray arrayWithObjects:characterUUID,characterUUID1,nil] forService:BTService];
}else{
[BTPeripheral discoverServices:[NSArray arrayWithObjects:serviceUUID, nil]];
}
}
#pragma mark 服务打通后,获取请求权限
/**
* 7. 在这个方法中我们要找到我们所需的服务的特性
*
在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
当setNotifyValue方法调用后调用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
*
*/
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
if (error) {
NSLog(@"didDiscoverDescriptorsForCharacteristic:%@",error.localizedDescription);
BTCharacteristic = nil;
[BTPeripheral discoverCharacteristics:[NSArray arrayWithObjects:characterUUID, characterUUID1, nil] forService:BTService];
}else{
for (CBCharacteristic *object in [service characteristics]) {
NSLog(@"Discovered characteristic %@", object);
if ([object.UUID isEqual:characterUUID]) {
BTCharacteristic = object;
[BTPeripheral readValueForCharacteristic:object];
}
else if ([object.UUID isEqual:characterUUID1]) {
BTCharacteristic1=object;
[BTPeripheral readValueForCharacteristic:object];
[BTPeripheral setNotifyValue:YES forCharacteristic:object];
[BTPeripheral discoverDescriptorsForCharacteristic:object];//不知道有什么用
}
}
}
}
#pragma mark 接受通知
/**
* 8. 接受通知。
*/
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if (error==nil) {
[peripheral readValueForCharacteristic:characteristic];
}
}
#pragma mark 处理蓝牙发送过来的数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSData *data = characteristic.value;
NSLog(@"--data:--->%@",data);
}
#pragma mark 暂时不明
- (void)peripheral:(CBPeripheral *)peripheral :(CBCharacteristic *)characteristic error:(NSError *)error{
for (CBDescriptor* descriptor in characteristic.descriptors) {
if ([descriptor.UUID isEqual:descriptorUUID]) {
//调用下面的方法后 会调用到代理的- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
[peripheral readValueForDescriptor:descriptor];
}
}
}
#pragma mark 发送请求
- (IBAction)requestService:(id)sender {
[self getVersionData];
}
#pragma mark 获取版本信息
- (void)getVersionData{
NSString *hexString = @"55AA0609B102021c1cCS";
NSData *data = [self stringToByte:hexString last:YES];
[BTPeripheral writeValue:data forCharacteristic:BTCharacteristic type:CBCharacteristicWriteWithResponse];
NSLog(@"------>%@----->%@---->%ld",data, BTCharacteristic,(long)CBCharacteristicWriteWithResponse);
}
#pragma mark 蓝牙发送数据后, 回调。
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSLog(@"蓝牙发送数据回调");
[peripheral readValueForCharacteristic:characteristic];
}
#pragma mark 暂时不明
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
for (CBDescriptor* descriptor in characteristic.descriptors) {
if ([descriptor.UUID isEqual:descriptorUUID]) {
[peripheral readValueForDescriptor:descriptor];
}
}
}
#pragma mark 转进制
-(NSData *)stringToByte:(NSString *)hexString last:(BOOL)last{ //字符串转byte
int j=0;
NSUInteger strLength = [hexString length];
Byte bytes[strLength/2];
for(int i=0;i<strLength;i++)
{
int int_ch; /// 两位16进制数转化后的10进制数
unichar hex_char1 = [hexString characterAtIndex:i]; 两位16进制数中的第一位(高位*16)
int int_ch1;
if(hex_char1 >= '0' && hex_char1 <='9')
int_ch1 = (hex_char1-48)*16; 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch1 = (hex_char1-55)*16; A 的Ascll - 65
else
int_ch1 = (hex_char1-87)*16; a 的Ascll - 97
if (i < strLength-1) {
i++;
}
unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
int int_ch2;
if(hex_char2 >= '0' && hex_char2 <='9')
int_ch2 = (hex_char2-48); 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch2 = hex_char2-55; A 的Ascll - 65
else
int_ch2 = hex_char2-87; a 的Ascll - 97
int_ch = int_ch1+int_ch2;
bytes[j] = int_ch; ///将转化后的数放入Byte数组里
j++;
}
if (last) {
int sum=0;
for (int i=2; i<strLength/2-1; i++) {
sum += bytes[i];
}
bytes[strLength/2-1] = sum;
}
NSData *newData = [[NSData alloc] initWithBytes:bytes length:strLength/2];
return newData;
}
@end