简单粗暴上代码
步骤解释请看另一篇 http://blog.csdn.net/swibyn/article/details/20531593
demo下载 http://download.csdn.net/detail/swibyn/9717588
#import "TableViewController.h"
#import "CoreBluetooth/CoreBluetooth.h"
#pragma mark - CBPeripheral Category
//扩展,主要是界面显示用
@interface CBPeripheral (Text)
-(NSString *)stateText;
@end
@implementation CBPeripheral (Text)
-(NSString *)stateText{
NSArray *array = @[@"Disconnected",@"Connecting",@"Connected",@"Disconnecting"];
NSInteger index = self.state;
return array[index];
}
@end
#pragma mark - NSString Category
@interface NSString (Category)
@property (readonly) NSData *hexData;
@end
@implementation NSString (Category)
-(NSData *)hexData{
NSUInteger len = [self length] / 2; // Target length
unsigned char *buf = malloc(len);
unsigned char *whole_byte = buf;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [self length] / 2; i++) {
byte_chars[0] = [self characterAtIndex:i*2];
byte_chars[1] = [self characterAtIndex:i*2+1];
*whole_byte = strtol(byte_chars, NULL, 16);
whole_byte++;
}
NSData *data = [NSData dataWithBytes:buf length:len];
free( buf );
return data;
}
@end
#pragma mark - TableViewController
@interface TableViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property CBCentralManager* centralManger;
@property NSMutableArray* peripherals;
@end
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.centralManger = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.peripherals = [NSMutableArray array];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark utils
#pragma mark Action
- (IBAction)scanBarButtonAction:(id)sender {
for (CBPeripheral* peripheral in self.peripherals) {
if (peripheral.state != CBPeripheralStateDisconnected) {
[self.centralManger cancelPeripheralConnection:peripheral];
}
}
[self.peripherals removeAllObjects];
[self.centralManger scanForPeripheralsWithServices:nil options:nil];
}
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.peripherals.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
CBPeripheral *peripheral = self.peripherals[indexPath.row];
// Configure the cell...
cell.textLabel.text = peripheral.name;
cell.detailTextLabel.text = peripheral.stateText;
return cell;
}
#pragma mark Table view Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
CBPeripheral *peripheral = self.peripherals[indexPath.row];
if (peripheral.state == CBPeripheralStateConnected) {
[self.centralManger cancelPeripheralConnection:peripheral];
}else if(peripheral.state == CBPeripheralStateDisconnected){
[self.centralManger connectPeripheral:peripheral options:nil];
}
}
#pragma mark CBCentralManagerDelegate
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
}
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
NSLog(@"%s",__FUNCTION__);
peripheral.delegate = self;
[peripheral discoverServices:nil];
[self.tableView reloadData];
}
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
NSLog(@"error:%@",error);
[self.tableView reloadData];
}
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
}
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(@"peripheral:%@",peripheral);
NSLog(@"advertisementData:%@",advertisementData);
[self.peripherals addObject:peripheral];
[self.tableView reloadData];
}
#pragma mark CBPeripheralDelegate
-(void)peripheralDidUpdateName:(CBPeripheral *)peripheral{
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
}
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
if ([service.UUID.UUIDString isEqualToString:@"EDBC"]) {//你需要的service UUID
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID.UUIDString isEqualToString:@"ED01"]) {//你需要的characteristic UUID
NSLog(@"EDBC ED01 found");
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
NSData *data = @"0209010000000201000002".hexData;
NSLog(@"write:%@",data);
[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
return;
}
}
}
}
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
}
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
NSLog(@"value:%@",characteristic.value);
}
@end
执行步骤
1,搜索设备 scanBarButtonAction
2,点击列表中的设备 tableView:didSelectRowAtIndexPath:
3,peripheral主动断开
打印的日志如下:
2016-12-22 09:47:19.776 Bluetooth[193:3829] peripheral:0x15e802b0, identifier = 54D36F04-3DCC-90C9-1AAA-6A453A821FEA, name = eID_00213200333, state = disconnected>
2016-12-22 09:47:19.778 Bluetooth[193:3829] advertisementData:{
kCBAdvDataIsConnectable = 1;
kCBAdvDataLocalName = "eID_00213200333";
kCBAdvDataServiceUUIDs = (
EDBC
);
}
2016-12-22 09:47:20.585 Bluetooth[193:3829] -[TableViewController centralManager:didConnectPeripheral:]
2016-12-22 09:47:20.907 Bluetooth[193:3829] -[TableViewController peripheral:didDiscoverServices:]
2016-12-22 09:47:21.027 Bluetooth[193:3829] -[TableViewController peripheral:didDiscoverCharacteristicsForService:error:]
2016-12-22 09:47:21.028 Bluetooth[193:3829] EDBC ED01 found
2016-12-22 09:47:21.029 Bluetooth[193:3829] write:<02090100 00000201 000002>
2016-12-22 09:47:21.296 Bluetooth[193:3829] -[TableViewController peripheral:didWriteValueForCharacteristic:error:]
2016-12-22 09:47:21.298 Bluetooth[193:3829] -[TableViewController peripheral:didUpdateValueForCharacteristic:error:]
2016-12-22 09:47:21.299 Bluetooth[193:3829] value:<020b0100 4c000000 02004c00 03>
2016-12-22 09:47:31.632 Bluetooth[193:3829] -[TableViewController centralManager:didDisconnectPeripheral:error:]
2016-12-22 09:47:31.632 Bluetooth[193:3829] error:Error Domain=CBErrorDomain Code=6 "The connection has timed out unexpectedly." UserInfo={NSLocalizedDescription=The connection has timed out unexpectedly.}