最近有一些人在问蓝牙主动断开外设的问题,例如连接了第一个外设,希望在连接第二个外设的时候释放了第一个外设,可是弄了主动断开却发现第一个外设并没有断开,解决问题的方法呢其实很简单,首先你得抓到外设的UUID,然后弄个代理传值,把UUID获取值传回去主界面,然后再次到扫描蓝牙的界面的时候,把这个值传过来进行判断,如果连接第二个外设那么UUID的值是不一样的,那这个时候你就可以写一个判断,判断你的蓝牙是否连接这一个外设,如果有,那就执行你这个判断里面的方法,也就是主动断开连接的方法,那样就可以断开了,亲测没问题了,有什么问题的可以找我,我能帮到你们的很乐意帮助你们 ,谢谢
续: 有些朋友遇到相关问题我又很少时间逛博客 所以我直接把代码片贴在下面
@property (copy, nonatomic) BSSuccessBlock
@property (copy, nonatomic) BSSuccessBlock powerOnBlock;
@end
@implementation BlueShield{
BOOL
NSInteger
}
static BlueShield* _defaultBLShield = nil;
+(BlueShield*)defaultBLShield
{
_defaultBLShield) {
_defaultBLShield = [[BlueShield alloc]init];
[_defaultBLShield initBLE];
}
return _defaultBLShield;
}
- (void) initBLE{
inited) {
return;
}
inited = TRUE;
connectState = KNOT;
delegate
self.activePeripheral = nil;
cm = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void) setConnectState:(NSInteger) state{
connectState
}
-(NSInteger)getConnectState
{
return connectState;
}
/*!
* @method writeValue:
*
* @param serviceUUID Service UUID to write to (e.g. 0x2400)
* @param characteristicUUID Characteristic UUID to write to (e.g. 0x2401)
* @param data Data to write to peripheral
* @param p CBPeripheral to write to
*
* @discussion Main routine for writeValue request, writes without feedback. It converts integer into
* CBUUID's used by CoreBluetooth. It then searches through the peripherals services to find a
* suitable service, it then checks that there is a suitable characteristic on this service.
* If this is found, value is written. If not nothing is done.
*
*/
- (void)writeValue:(CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral *)p data:(NSData
if (data == nil) {
NSLog(@"data = nil");
return;
}
CBUUID
CBUUID
CBService *service = [self findServiceFromUUID:su p:p];
if (!service) {
[[self delegate] connectLost];
connectState = KLOST;
NSLog(@"断开连接");
// printf("Could not find service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:su],p.identifier.UUIDString);
return;
}
CBCharacteristic *characteristic = [self findCharacteristicFromUUID:cu service:service];
if (!characteristic) {
// printf("Could not find characteristic with UUID %s on service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:cu],[self CBUUIDToString:su],p.identifier.UUIDString);
return;
}
[p writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
}
/*!
* @method readValue:
*
* @param serviceUUID Service UUID to read from (e.g. 0x2400)
* @param characteristicUUID Characteristic UUID to read from (e.g. 0x2401)
* @param p CBPeripheral to read from
*
* @discussion Main routine for read value request. It converts integers into
* CBUUID's used by CoreBluetooth. It then searches through the peripherals services to find a
* suitable service, it then checks that there is a suitable characteristic on this service.
* If this is found, the read value is started. When value is read the didUpdateValueForCharacteristic
* routine is called.
*
* @see didUpdateValueForCharacteristic
*/
//读取值
-(void) readValue: (CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral
CBUUID
CBUUID
CBService *service = [self findServiceFromUUID:su p:p];
if (!service) {
// printf("Could not find service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:su],p.identifier.UUIDString);
return;
}
CBCharacteristic *characteristic = [self findCharacteristicFromUUID:cu service:service];
if (!characteristic) {
// printf("Could not find characteristic with UUID %s on service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:cu],[self CBUUIDToString:su],p.identifier.UUIDString);
return;
}
[p readValueForCharacteristic:characteristic];
}
/*!
* @method notification:
*
* @param serviceUUID Service UUID to read from (e.g. 0x2400)
* @param characteristicUUID Characteristic UUID to read from (e.g. 0x2401)
* @param p CBPeripheral to read from
*
* @discussion Main routine for enabling and disabling notification services. It converts integers
* into CBUUID's used by CoreBluetooth. It then searches through the peripherals services to find a
* suitable service, it then checks that there is a suitable characteristic on this service.
* If this is found, the notfication is set.
*
*/
//连接失败通知
-(void) notification:(CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral *)p on:(BOOL)on {
CBUUID
CBUUID
CBService *service = [self findServiceFromUUID:su p:p];
if (!service) {
[[self delegate] connectFail];
//连接失败 KFAILED是3
connectState = KFAILED;
NSLog(@"连接失败");
// printf("Could not find service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:su],p.identifier.UUIDString);
return;
}
CBCharacteristic *characteristic = [self findCharacteristicFromUUID:cu service:service];
if (!characteristic) {
// printf("Could not find characteristic with UUID %s on service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:cu],[self CBUUIDToString:su],p.identifier.UUIDString);
return;
}
[p setNotifyValue:on forCharacteristic:characteristic];
}
/*!
* @method swap:
*
* @param s Uint16 value to byteswap
*
* @discussion swap byteswaps a UInt16
*
* @return Byteswapped UInt16
*/
-(UInt16) swap:(UInt16)s {
UInt16 temp = s << 8;
8);
return temp;
}
/*!
* @method controlSetup:
*
* @param s Not used
*
* @return Allways 0 (Success)
*
* @discussion controlSetup enables CoreBluetooths Central Manager and sets delegate to TIBLECBKeyfob class
*
*/
- (int)controlSetup {
cm = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
0;
}
/*!
* @method findBLEPeripherals:
*
* @param timeout timeout in seconds to search for BLE peripherals
*
* @return 0 (Success), -1 (Fault)
*
* @discussion findBLEPeripherals searches for BLE peripherals and sets a timeout when scanning is stopped
*
*/
//发现低消耗蓝牙外设
- (int) findBLEPeripherals:(int) timeout {
//判断蓝牙是否是开启状态
if (self.cm.state != CBCentralManagerStatePoweredOn) {
printf("CoreBluetooth not correctly initialized !\r\n");
//printf("State %ld%s (%s)\r\n(long)",(long)self.cm.state,[self centralManagerStateToString:self.cm.state]);
printf("进入了这里");
1;
}
[NSTimer scheduledTimerWithTimeInterval:(float)timeout
target:self
selector:@selector(scanTimer:)
userInfo:nil
repeats:NO];
[self.cm scanForPeripheralsWithServices:nil options:0]; // Start scanning
return 0; // Started scanning OK !
}
/*!
* @method connectPeripheral:
*
* @param p Peripheral to connect to
*
* @discussion connectPeripheral connects to a given peripheral and sets the activePeripheral property of TIBLECBKeyfob.
*
*/
//连接外设
- (void) connectPeripheral:(CBPeripheral
// printf("Connecting to peripheral with UUID : %s\r\n",peripheral.identifier.UUIDString);
NSLog(@"Connecting to peripheral with UUID");
_activePeripheral
_activePeripheral.delegate = self;
[_cm connectPeripheral:_activePeripheral options:nil];
[[self delegate] connecting];
}
/*!
* @method centralManagerStateToString:
*
* @param state State to print info of
*
* @discussion centralManagerStateToString prints information text about a given CBCentralManager state
*
*/
- (const char *) centralManagerStateToString: (int)state{
switch(state) {
case CBCentralManagerStateUnknown:
return "State unknown (CBCentralManagerStateUnknown)";
case CBCentralManagerStateResetting:
return "State resetting (CBCentralManagerStateUnknown)";
case CBCentralManagerStateUnsupported:
return "State BLE unsupported (CBCentralManagerStateResetting)";
case CBCentralManagerStateUnauthorized:
return "State unauthorized (CBCentralManagerStateUnauthorized)";
case CBCentralManagerStatePoweredOff:
return "State BLE powered off (CBCentralManagerStatePoweredOff)";
case CBCentralManagerStatePoweredOn:
return "State powered up and ready (CBCentralManagerStatePoweredOn)";
default:
"State unknown";
}
return "Unknown state";
}
/*!
* @method scanTimer:
*
* @param timer Backpointer to timer
*
* @discussion scanTimer is called when findBLEPeripherals has timed out, it stops the CentralManager from scanning further and prints out information about known peripherals
*
*/
- (void) scanTimer:(NSTimer
cm stopScan];
printf("Stopped Scanning\r\n");
// printf("Known peripherals %lu%d\r\n(unsigned long)",[_peripherals count]);
[self printKnownPeripherals];
}
/*!
* @method printKnownPeripherals:
*
* @discussion printKnownPeripherals prints all curenntly known peripherals stored in the peripherals array of TIBLECBKeyfob class
*
*/
- (void) printKnownPeripherals {
int
printf("List of currently known peripherals : \r\n");
0; i < _peripherals.count; i++) {
CBPeripheral *p = [_peripherals objectAtIndex:i];
//CFStringRef s = CFUUIDCreateString(NULL, p.UUID);
//printf("%d | %s\r\n",i,CFStringGetCStringPtr(s, 0));
[self printPeripheralInfo:p];
}
}
/*
* @method printPeripheralInfo:
*
* @param peripheral Peripheral to print info of
*
* @discussion printPeripheralInfo prints detailed info about peripheral
*
*/
- (void) printPeripheralInfo:(CBPeripheral*)peripheral {
[[self delegate] autoConnect];
//CFStringRef s = CFUUIDCreateString(NULL, peripheral.UUID);
printf("------------------------------------\r\n");
printf("Peripheral Info :\r\n");
// printf("UUID : %s\r\n",peripheral.identifier.UUIDString);
// printf("RSSI : %d\r\n",[peripheral.RSSI intValue]);
printf("Name : %s\r\n",[peripheral.name cStringUsingEncoding:NSStringEncodingConversionAllowLossy]);
//printf("isConnected : %d\r\n",peripheral.isConnected);
printf("-------------------------------------\r\n");
}
/*
* @method UUIDSAreEqual:
*
* @param u1 CFUUIDRef 1 to compare
* @param u2 CFUUIDRef 2 to compare
*
* @returns 1 (equal) 0 (not equal)
*
* @discussion compares two CFUUIDRef's
*
*/
- (int) UUIDSAreEqual:(CFUUIDRef)u1 u2:(CFUUIDRef)u2 {
CFUUIDBytes b1 = CFUUIDGetUUIDBytes(u1);
CFUUIDBytes b2 = CFUUIDGetUUIDBytes(u2);
memcmp(&b1, &b2, 16) == 0) {
1;
}
0;
}
/*
* @method CBUUIDToString
*
* @param UUID UUID to convert to string
*
* @returns Pointer to a character buffer containing UUID in string representation
*
* @discussion CBUUIDToString converts the data of a CBUUID class to a character pointer for easy printout using printf()
*
*/
-(const char *) CBUUIDToString:(CBUUID
return [[UUID.data description] cStringUsingEncoding:NSStringEncodingConversionAllowLossy];
}
/*
* @method UUIDToString
*
* @param UUID UUID to convert to string
*
* @returns Pointer to a character buffer containing UUID in string representation
*
* @discussion UUIDToString converts the data of a CFUUIDRef class to a character pointer for easy printout using printf()
*
*/
-(const char *) UUIDToString:(CFUUIDRef)UUID {
"NULL";
CFStringRef s = CFUUIDCreateString(NULL, UUID);
return CFStringGetCStringPtr(s, 0);
}
/*
* @method compareCBUUID
*
* @param UUID1 UUID 1 to compare
* @param UUID2 UUID 2 to compare
*
* @returns 1 (equal) 0 (not equal)
*
* @discussion compareCBUUID compares two CBUUID's to each other and returns 1 if they are equal and 0 if they are not
*
*/
-(int) compareCBUUID:(CBUUID *) UUID1 UUID2:(CBUUID
char b1[16];
char b2[16];
data getBytes:b1];
data getBytes:b2];
memcmp(b1, b2, UUID1.data.length) == 0)return 1;
0;
}
/*
* @method compareCBUUIDToInt
*
* @param UUID1 UUID 1 to compare
* @param UUID2 UInt16 UUID 2 to compare
*
* @returns 1 (equal) 0 (not equal)
*
* @discussion compareCBUUIDToInt compares a CBUUID to a UInt16 representation of a UUID and returns 1
* if they are equal and 0 if they are not
*
*/
-(int) compareCBUUIDToInt:(CBUUID *)UUID1 UUID2:(UInt16)UUID2 {
char b1[16];
data getBytes:b1];
UInt16 b2 = [self swap:UUID2];
memcmp(b1, (char *)&b2, 2) == 0) return 1;
0;
}
/*
* @method CBUUIDToInt
*
* @param UUID1 UUID 1 to convert
*
* @returns UInt16 representation of the CBUUID
*
* @discussion CBUUIDToInt converts a CBUUID to a Uint16 representation of the UUID
*
*/
-(UInt16) CBUUIDToInt:(CBUUID
char b1[16];
data getBytes:b1];
0] << 8) | b1[1]);
}
/*
* @method IntToCBUUID
*
* @param UInt16 representation of a UUID
*
* @return The converted CBUUID
*
* @discussion IntToCBUUID converts a UInt16 UUID to a CBUUID
*
*/
-(CBUUID *) IntToCBUUID:(UInt16)UUID {
char t[16];
0] = ((UUID >> 8) & 0xff); t[1] = (UUID & 0xff);
NSData *data = [[NSData alloc] initWithBytes:t length:16];
CBUUID UUIDWithData:data];
}
-(CBService *) findServiceFromUUID:(CBUUID *)UUID p:(CBPeripheral
int i = 0; i < p.services.count; i++) {
CBService *s = [p.services objectAtIndex:i];
compareCBUUID:s.UUID UUID2:UUID]) return s;
}
return nil; //Service not found on this peripheral
}
-(CBCharacteristic *) findCharacteristicFromUUID:(CBUUID *)UUID service:(CBService*)service {
int i=0; i < service.characteristics.count; i++) {
CBCharacteristic *c = [service.characteristics objectAtIndex:i];
compareCBUUID:c.UUID UUID2:UUID]) return c;
}
return nil; //Characteristic not found on this service
}
- (void)didPowerOnBlock:(BSSuccessBlock)block {
_powerOnBlock = block;
}
- (void)didUpdateValueBlock:(BSSuccessBlock)block {
_updatedValueBlock = block;
}
#pragma mark - CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager
printf("Status of CoreBluetooth central manager changed %ld (%s)\r\n",(long)central.state,[self centralManagerStateToString:central.state]);
if (central.state == CBCentralManagerStatePoweredOn) {
_powerOnBlock) {
_powerOnBlock(nil, nil);
}
}else if (central.state ==CBCentralManagerStatePoweredOff){
[[self delegate] connectLost];
}
}
- (void)centralManager:(CBCentralManager
CBPeripheral
NSDictionary
NSNumber
{
peripherals) {
peripherals = [[NSMutableArray alloc] initWithObjects:peripheral, nil];
} else {
int i = 0; i < self.peripherals.count; i++) {
CBPeripheral *p = [self.peripherals objectAtIndex:i];
if ([p.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
peripherals replaceObjectAtIndex:i withObject:peripheral];
printf("Duplicate UUID found updating ...\r\n");
return;
}
}
peripherals addObject:peripheral];
printf("New UUID, adding\r\n");
}
printf("didDiscoverPeripheral\r\n");
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral
// printf("Connection to peripheral with UUID : %s successfull\r\n",peripheral.identifier.UUIDString);
[[self delegate] connecting];
//连接状态 KING是1
connectState = KING;
NSLog(@"连接状态是1");
activePeripheral
activePeripheral discoverServices:nil];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError
if (!error) {
delegate] connected];
//KSUCCESS=2 意思就是连接状态2
connectState = KSUCCESS;
NSLog(@"连接状态成功 2");
printf("Characteristics of service with UUID : %s found\r\n", [self CBUUIDToString:service.UUID]);
int i = 0; i < service.characteristics.count; i++) {
CBCharacteristic *c = [service.characteristics objectAtIndex:i];
printf("Found characteristic %s\r\n",[ self CBUUIDToString:c.UUID]);
CBService *s = [peripheral.services objectAtIndex:(peripheral.services.count - 1)];
compareCBUUID:service.UUID UUID2:s.UUID]) {
printf("Finished discovering characteristics\r");
}
}
} else {
printf("Characteristic discorvery unsuccessfull !\r\n");
}
}
#pragma mark - CBPeripheralDelegate
//外围设备
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError
if (error) {
[[self delegate] connectFail];
connectState = KFAILED;
NSLog(@"连接状态3 也就是失败");
return;
}
CBService *s in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:s];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError
if (error) {
return;
}
if (_updatedValueBlock) {
_updatedValueBlock(characteristic.value, error);
}
}
//Peripherals断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError
NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
[[self delegate] connectLost];//这个是实现告诉用户与某个外设断开连接
[[self delegate] autoConnect];//这个是实现了发现外设就连接 要曾经连接过的
}
-(void)disconnectPeripheral:(CBCentralManager
CBPeripheral
//断开连接
cancelPeripheralConnection:peripheral];
NSLog(@"来过");
}
我已经一年半多没有看这个了,再看就需要花时间 所以我直接贴蓝牙这一块代码 只要诸位是在写的 就会相对理解的很快 看看你们少了哪一步 就加上哪一步试试