I try to make program to detect uncertain Bluetooth device at iOS.
The device scanning work well but it could not detect any device. However in the basic option in Ipad, the bluetooth devices were detected well. Bellow show the my code. Please advise to fix some problem.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//CB setup
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
// You should test all scenarios
if (central.state != CBCentralManagerStatePoweredOn) {
return;
}
if (central.state == CBCentralManagerStatePoweredOn) {
_scan_state = 1;
}
[self deviceScan];
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(#"dicovered: %#", peripheral.name);
if(![self.BTNames containsObject:peripheral]){
[self.BTNames addObject:peripheral];
}
_num_cell = self.BTNames.count;
[self.BTList reloadData];
}
- (void) deviceScan{
if(_scan_state){
/* [_centralManager scanForPeripheralsWithServices:nil options:#{ CBCentralManagerScanOptionAllowDuplicatesKey : #NO }];*/
[_centralManager scanForPeripheralsWithServices:nil options:nil];
NSLog(#"Scan Starting");
}
}
Related
I have a BLE device (obd2 dongle) that I want to connect to. I can pair with it through "settings" but I can't discover it via didDiscoverPeripheral delegate method , any help ?
- (void)viewDidLoad {
[super viewDidLoad];
_centralManager =[[CBCentralManager alloc]initWithDelegate:self queue:nil];
[self scan];
}
-(void)scan {
NSDictionary *options1 =#{ CBCentralManagerScanOptionAllowDuplicatesKey : #YES };
[_centralManager scanForPeripheralsWithServices:nil options:options1];
}
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
if (central.state == CBCentralManagerStatePoweredOn) {
[self scan];
}
}
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
[peripheral readRSSI];
[central connectPeripheral:peripheral options:nil];
}
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
CBPeripheral *peripheral1 =peripheral;
NSLog(#"peripheral1 name = %#",peripheral1.name); peripheral.delegate=self;
[peripheral discoverServices:nil];
}
is it possible to configure a bluetooth-device in a way that my app automatically connects to it when near - without pairing etc.?
The device will be custom built and the app will be written by me, I first have to define some specs. It would be great if there's an option in the device that as soon as it's near my (opened) app that both are connected automatically without any setup process.
Sure you can. If the device will be custom made and you know its characteristics
Code below (TRANSFER_SERVICE_UUID - GUID of your device):
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
// You should test all scenarios
if (central.state != CBCentralManagerStatePoweredOn) {
[self stop];
return;
}
if (central.state == CBCentralManagerStatePoweredOn) {
// Scan for devices
[_centralManager scanForPeripheralsWithServices:#[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] options:#{ CBCentralManagerScanOptionAllowDuplicatesKey : #YES }];
NSLog(#"Scanning started");
if(_delegate)
{
if([_delegate respondsToSelector:#selector(CB_changedStatus:message:)])
{
[_delegate CB_changedStatus:CBManagerMessage_ScanningStarted message:#"Scanning started"];
}
}
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(#"Discovered %# at %#", peripheral.name, RSSI);
if (_discoveredPeripheral != peripheral) {
// Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it
_discoveredPeripheral = peripheral;
// And connect
NSLog(#"Connecting to peripheral %#", peripheral);
if(_delegate)
{
if([_delegate respondsToSelector:#selector(CB_changedStatus:message:)])
{
[_delegate CB_changedStatus:CBManagerMessage_ConnectingToPeripheral message:[NSString stringWithFormat:#"Connecting to peripheral %#", peripheral]];
}
}
[_centralManager connectPeripheral:peripheral options:nil];
}
}
I have a bluetooth bracelet which connects to my iPhone 5s via Bluetooth; it comes with an App called Zeroner. Now I want to obtain the information from the connected and paired up bracelet without using the App. Here is what I attempted to do:
Setup CBCentralManager
Use retrieveConnectedPeripheralsWithServices: to obtain connected devices
Here is the code:
CBConnectedDevicesVC.h
#import <UIKit/UIKit.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import SERVICE_ID #"FB694B90-F49E-4597-8306-171BBA78F846"
#interface CBConnectedDevicesVC : UIViewController <CBCentralManagerDelegate, CBPeripheralDelegate>
#property (strong, nonatomic) CBCentralManager *centralManager;
#property (strong, nonatomic) CBPeripheral *discoveredPeripheral;
#end
CBConnectedDevicesVC.m
#import "CBConnectedDevicesVC.h"
#implementation CBConnectedDevicesVC
- (void)viewDidLoad {
[super viewDidLoad];
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state != CBCentralManagerStatePoweredOn) {
return;
}
if (central.state == CBCentralManagerStatePoweredOn) {
NSArray* connectedDevices = [_centralManager retrieveConnectedPeripheralsWithServices:#[[CBUUID UUIDWithString:SERVICE_UUID]]];
for (CBUUID *uuid in connectedDevices) {
NSLog(#"Device Found. UUID = %#", uuid);
}
}
}
#end
For the above codes, I have to specify the service ID in SERVICE_UUID, which I don't know what the value of the bracelet is. Is there any alternatives to obtain the information from the connected bracelet?
UPDATE about test result of LightBlue App
After unpaired from Zeroner App and "Forget this Device" in Settings > Bluetooth > choose the device named "Bracelet-0366", LightBlue App discovers the device (finally!).
Here is the result screenshot:
I got several values here, but I'm not sure which values I should use.
Further Test Results:
If I put the UUID (starts with 4EFF) found in LightBlue into SERVICE_ID, no delegate is called with the above codes.
Another piece of code I tried is (obtained from Tut+ tutorial):
NSArray *serviceID;
#implementation CBCentralManagerViewController
- (void)viewDidLoad {
[super viewDidLoad];
serviceID = #[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]];
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
_data = [[NSMutableData alloc] init];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
// You should test all scenarios
if (central.state != CBCentralManagerStatePoweredOn) {
return;
}
if (central.state == CBCentralManagerStatePoweredOn) {
// Scan for devices
[_centralManager scanForPeripheralsWithServices:serviceID options:#{ CBCentralManagerScanOptionAllowDuplicatesKey : #YES }];
NSLog(#"Scanning started");
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(#"Discovered %# at %#", peripheral.name, RSSI);
if (_discoveredPeripheral != peripheral) {
// Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it
_discoveredPeripheral = peripheral;
// And connect
NSLog(#"Connecting to peripheral %#", peripheral);
[_centralManager connectPeripheral:peripheral options:nil];
}
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(#"Failed to connect");
[self cleanup];
}
- (void)cleanup {
// See if we are subscribed to a characteristic on the peripheral
if (_discoveredPeripheral.services != nil) {
for (CBService *service in _discoveredPeripheral.services) {
if (service.characteristics != nil) {
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
if (characteristic.isNotifying) {
[_discoveredPeripheral setNotifyValue:NO forCharacteristic:characteristic];
return;
}
}
}
}
}
}
[_centralManager cancelPeripheralConnection:_discoveredPeripheral];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(#"Connected");
[_centralManager stopScan];
NSLog(#"Scanning stopped");
[_data setLength:0];
peripheral.delegate = self;
[peripheral discoverServices:serviceID];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
[self cleanup];
return;
}
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:#[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]] forService:service];
}
// Discover other characteristics
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
[self cleanup];
return;
}
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(#"Error");
return;
}
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
// Have we got everything we need?
if ([stringFromData isEqualToString:#"EOM"]) {
[_textview setText:[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]];
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
[_centralManager cancelPeripheralConnection:peripheral];
}
[_data appendData:characteristic.value];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
return;
}
if (characteristic.isNotifying) {
NSLog(#"Notification began on %#", characteristic);
} else {
// Notification has stopped
[_centralManager cancelPeripheralConnection:peripheral];
}
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
_discoveredPeripheral = nil;
//
[_centralManager scanForPeripheralsWithServices:serviceID options:#{ CBCentralManagerScanOptionAllowDuplicatesKey : #YES }];
}
With the above code, there are 2 constants defined TRANSFER_SERVICE_ID and TRANSFER_CHARACTERISTIC_ID. From the tutorial, the TRANSFER_SERVICE_ID should be set to the one starts with 4EFF and the TRANSFER_CHARACTERISTIC_ID should be set to 0xFF20 or FF20. However, this piece of code does not detect the bracelet at all, even though the bracelet is unpaired & disconnected. What did I miss this time?
Don't worry about the UUID that starts with 4EFF - this is the UUID of the device and will be different for each one.
The service id is FF20 - You can use this in scanForPeripheralsWithServices - this is SERVICE_ID in your code above.
Then you have two characteristics- FF21 and FF22
You can write to FF21 using the writeValue method on your CBPeripheral instance.
With FF22 that you can subscribe to notifications using the setNotify CBPeripheral method. You will then get a call to the didUpdateValueForCharacteristic CBPeripheralDelegate method whenever the device changes the value.
There are 2 types of bluetooth devices you can work with:
BLE devices - no need (often can't) to pair them with iPhone
"standard" bluetooth devices - you need to pair them with iPhone before use
Those two types are managed independently - from the way you described it I expect your bracelet to fall into "standard" category, and CoreBluetooth can only be used for BLE.
For working with already paired external accessories you should use ExternalAccessory framework
I have two devices (ipad 3 and iphone 4s), and was trying to find a way to recognize one of the two devices (For future exchange information between them), for that, I'm with active Bluetooth devices in 2, and using the following code:
- (void)viewDidLoad {
[super viewDidLoad];
CBUUID *otherDevice = [CBUUID UUIDWithString:#"180A"];
NSDictionary *scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
[self.mgr scanForPeripheralsWithServices:[NSArray arrayWithObject:otherDevice] options:scanOptions];
}
#pragma mark - delegates
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(#"I found new devices -> %#",[NSString stringWithFormat:#"%#",[advertisementData description]]);
}
-(void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals{
NSLog(#"This is it!");
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
NSString *messtoshow;
switch (central.state) {
case CBCentralManagerStatePoweredOn:
{
messtoshow=[NSString stringWithFormat:#"Bluetooth is currently powered on and available to use."];
[self.mgr scanForPeripheralsWithServices:nil options:nil];
break;
}
}
NSLog(#"%#",messtoshow);
}
The problem with this code is that I am getting the message on the console that bluetooth is active, but the method 'didDiscoverPeripheral:' not being called, why this is happening? (since the Bluetooth on both devices are active)?
I'm pulling my hair out of this problems. I'm trying to connect to BLE devices, can't see what I've done wrong in my code below.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_cm = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
+ (NSString*)UUIDString:(CFUUIDRef)uuid {
CFStringRef string = CFUUIDCreateString(NULL, uuid);
return (__bridge_transfer NSString*)string;
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state == CBCentralManagerStatePoweredOn) {
[self scanForPeripherals];
}
}
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
// NSLog(#"Received peripheral : \n%#", peripheral);
// NSLog(#"Adv data : %#", advertisementData);
[peripheral setDelegate:self];
[central connectPeripheral:peripheral options:nil];
[peripheral readRSSI];
}
- (int)scanForPeripherals {
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey,
nil];
[_cm scanForPeripheralsWithServices:nil options:options];
return 0;
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(#"didConnectPeripheral");
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(#"didDisconnectPeripheral");
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(#"failed to connect");
}
- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {
NSLog(#"didReadRSSI");
}
These devices are not my own. I don't know its proximity UUID, but as far as I know, It won't be needed in connecting via CoreBluetooth right?
All of the devices are discovered in didDiscoverPeripheral:, in the selector I tried to connect them. But there's nothing comes after that.
Am I to expect a dialog with Pairing Password Request when I called to didDiscoverPeripheral:?
If so I don't see any dialog, why is that?
From apple documents, It clearly stated that after trying to connect to a device you should get a called to either didConnectPeripheral or didFailToConnectPeripher but I got none.
Any thoughts? I've been trying for almost a week now.
Appreciate every helps, thanks.
If you don't somehow retain the peripheral object that is delivered to didDiscoverPeripheral then it is released once this delegate method exits and you won't get a connection.
I suggest adding a property to track discovered peripherals
#property (strong,nonatomic) NSMutableArray *peripherals;
initialise this in viewDidLoad or init
self.peripherals=[NSMutableArray new];
And then add the peripheral to it in didDiscoverPeripheral
-(void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(#"Discovered peripheral %#",peripheral.identifier.UUIDString);
[self.peripherals addObject:peripheral];
[central connectPeripheral:peripheral options:nil];
}
var peripherals = [CBPeripheral]()
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
peripherals.append(peripheral)
bleManager.connectPeripheral(peripheral, options: nil)
}
This is the Swift version.