Trying to retrieve previously paired bluetooth device in IOS app will not respond with failure if device is off - ios

Sorry for the long title, but we are having a pretty interesting issue with using corebluetooth for ios. We are issuing a call to retrievePeripherals in CBCentralManager and are able to find the previously paired device.
This happens though regardless if the device is on or off though. I can't find anything in apple's documentation as to why it's able to find the device when it is off though and it isn't showing up in Settings -> Bluetooth -> Devices. I'm suspecting that Apple is caching this information but can't find any documentation to confirm this. Also, when the device is off and we issue the connect call, the program continues to execute as normal but the delegate for didFailToConnect never gets called. When the device is turned on, it will connect immediately.
Is there a way to pass a timeout parameter when trying to connect to a device? If not, what would the best solution be to handling reconnecting to a previously used device for an application (we're storing the last connected device within the app).

Two points you need to know about retrievePeripherals: and connectPeripheral:
1.) retrievePeripherals: attempts to retrieve the CBPeripheral object associated with the uuid you supply. Even if the ble device is off (or on the other side of the country) retrievePeripherals: will still return an instance of CBPeripheral that you can call connectPeripheral: on. This is done intentionally so that you can issue a call to a peripheral that is not even around and still automatically connect to it when it comes back into range. It basically creates a marker inside the system bluetooth so that when the device is actually seen, it will know it should connect to it.
2.)connectPeripheral: will not time out unless the communication channel is broken with the actual device. If the iOS device has not seen the device, it will not fail and should not time out (unless some error occurs inside the system bluetooth).
And as for the timeout parameter, there is no documented way inside the CoreBluetooth framework. You can create your own implementation for it, however I believe you'd be better off keeping a list of which peripheral uuid's you've actually called connectPeripheral: on and then just pop them from the list when they connect. If you no longer want to connect to a peripheral in the list call cancelPeripheral: on that UUID, call connectPeripheral: on the other, and swap entries. Good to go.

Related

CoreBluetooth `retrieveConnectedPeripheralsWithServices` returns disconnected peripherals

I wonder about the semantics of CBManager's retrieveConnectedPeripheralsWithServices. Everytime I'm using this I get CBPeripheral instances back with state CBPeripheralStateDisconnected.
It's not a problem to connect again, but isn't this method supposed to return connected peripherals?
Unfortunately, this is intended behaviour. It is a bit counterintuitive I have to admit but the peripheral state is always related to your app. That means if you have connected/paired/bonded the peripheral using another app or via the bluetooth system settings, it will still show as disconnected within your app. If you have connected some peripherals within your app they will show as connected.

CoreBluetooth: detect device out of range/ connection timeout

I am designing an iOS framework to handle multiple BLE devices (all of the same kind). Everything is working very well at the moment, except one thing:
The client wants a list with available devices. But how can I detect when a device, that has been discovered in the past, is not available anymore?
Another problem occurs, when I try to connect to a device that is not available anymore. Documentation says: Connection attempts never time out and
And yes, I never get an error via didFailToConnectPeripheral.
I did some research but couldn't figure out how handle these problems via CoreBluetooth properly. So I developed my own solutions, but I am not sure if that is the right way (or at least a good way, cause there may be several ways to do it).
1. Detecting devices that are not available anymore
I scan with
[_centralManager scanForPeripheralsWithServices:services options:#{CBCentralManagerScanOptionAllowDuplicatesKey: #(TRUE)}];
so I receive advertisments all the time as long as a device is not connected. I check with a timer that the advertisement reoccured in a given time interval (large enough corresponding to the devices ad interval). If the advertisement didn't occur in the interval, I remove the device from the list.
2. Detecting connection timeout
Well, that's a pretty easy one I think. I use my own timeout function and cancel the connection request if the timer expires.
If somebody ever came across these problem, I would be very interested in your opinion and/or your solution of course.
UPDATE 2014-12-17:
In the meantime I worked on my own solution using timers and it seems to work pretty well.
Connection timeout is straight forward. Simply set a timer to 5 seconds or whatever you think is good for you. If the timer expires and the device did not connect, simply cancel the connection and tell the user that there was a problem.
Detecting devices that go out of range was a bit trickier. For every discovered device I start a timer that fires after double the time, the device sends advertisements. If the device does send another advertisement till the timer expires, it probably went out of range or was turned off or connected to another device.
I don't want to answer my own question because I hope that maybe Apple will one day take care of those problems.
The correct way to determine whether a device is available is to store the peripheral identifier value. Before you attempt to reconnect, call retrievePeripheralsWithIdentifiers. However, this still does not guarantee that the device will be in range by the time you attempt to connect!
Connection attempts do not time out at the OS level, and this is explicitly documented.
Some apps may need to use the Core Bluetooth framework to perform
long-term actions in the background. As an example, imagine you are
developing a home security app for an iOS device that communicates
with a door lock (equipped with Bluetooth low energy technology). The
app and the lock interact to automatically lock the door when the user
leaves home and unlock the door when the user returns—all while the
app is in the background. When the user leaves home, the iOS device
may eventually become out of range of the lock, causing the connection
to the lock to be lost. At this point, the app can simply call the
connectPeripheral:options: method of the CBCentralManager class, and
because connection requests do not time out, the iOS device will
reconnect when the user returns home.

Peripheral and central at the same time on iOS

I've looked everywhere and tried everything, but nothing seems to work :(
On iOS, I'm making an app (for iOS 6 and above) in which iOS devices need to exchange data. Therefore, both devices need to be peripheral and central at the same time. I've done exactly as specified in the WWDC video, but the devices can't connect successfully with each other.
When I make one device only central and the other only peripheral, the central connects seamlessly to the peripheral.
However, when both devices are peripheral and central at the same time, I get random errors: at any stage (discovering services/characteristics or setting notify value to YES) errors sometimes happen, and sometimes discoverServices doesn't even call didDiscoverServices
Is there something different I should be doing? I simply merged the peripheral and central code into one view controller. I've noticed that if device "a" connects to device "b", and then device "b" connects to device "a", it works more often than not. I manage this by using NSThread sleepForTimeInterval: manually for different amounts of time on each device, but how could I get one device to connect first (and then the other) in a reliable (and not manually pre-defined) way?
If I do get errors, usually they're simply Unknown error
Please let me know if you need any code or any other information :)
Yes, it can be in both roles at the same time. You just have to initialize a CBPeripheralManager and a CBCentralManager. As soon as the peripheral manager is initialized and you receive the POWER ON state the device starts acting as a peripheral. You can add your services at this point and receive connections from other devices. At the same time you can use the central manager to scan and initiate connections to other peripherals.
Note that you cannot connect to your own device even if it acts as a peripheral.
For your errors, I suggest:
Turn off scanning before initiating a connection. That is, scan, find peripheral, stop scan, connect. Connection and scanning do not like each other.
Use a dedicated queue for handling bluetooth events, not the main queue. [[CBCentralManager alloc] initWithDelegate:self queue:my_dedicated_bluetooth_q]
Unfortunately, the stack sometimes become unstable. Even restarts are possible. But this usually happens only under heavy loads or several simultaneous connections. Hopefully, this will be improved in iOS7.
The unfamous Unknown error started to appear for several developers recently. Judging from your description there are probably a number of reasons why your setup may fail and it would require much more info that what fits well into a SO question.
For more info I suggest you search the bluetooth-dev mailing list archives https://lists.apple.com/archives/Bluetooth-dev or send a mail Bluetooth-dev#lists.apple.com. The community provides great help if you approach with reasonable questions like this.
As per my understanding one device can work with one mode at a time . That is if the device is working in the peripheral mode then it you cant work it as a central mode .If you see some standard examples like BTLE transfer or lilke Light Blue those are working in one mode at a time .
Firstly, what do you mean "the same time"?
If you mean the device advertising to other devices while it scanning for other devices, it can not.
But you can create two threads which share same lock to advertising and scanning.
Before scanning, stop advertising, before advertising, stop scanning.
I tested on my iPhone 4s and iPad air, worked well.

CoreBluetooth: What is the lifetime of unique UUIDs

Following off of this question:
Corebluetooth, How to get a unique UUID?
After connecting to a peripheral, I can retrieve its CFUUIDRef, which is unique, and can use it to reconnect via retrievePeripherals. However, I have found that I can not use it to reconnect after closing the application.
Is the unique UUID generated after a connection only valid for the lifetime of the application or are we supposed to be able to save it for later use? I am trying to have my application remember one particular peripheral, but besides peripheral.UUID, I don't know of any other unique identifiers.
Long story short, YES you can use the UUID to reconnect to the same device even after you close the application (in exactly the way you say).
I assume however, that you are not actually pairing with peripheral. That's a big problem right there. You need to actually establish the pairing request and get the peripheral to show up in the bluetooth table. The UUID will then be solidified with the iOS device and will remain until you flush the Network Settings of the iOS device.
The other possibility is that your BLE device has a firmware problem, wherein after you disconnect, it forces itself into advertising mode or something. This will also mess with your ability to reconnect. Let me know if you have any questions!

Initiating CoreBluetooth reconnect from peripheral

I've got an iPhone, I've got a bluetooth low energy (aka Bluetooth 4.o) device. The two have connected in the past. But now they're apart. Something happened, words were said that couldn't be taken back, and now they've disconnected.
Now they're in the same room again. The BTLE device wants to connect again. It doesn't want to wait for the iPhone to call it. It's taking the initiative. It wants to talk to the iPhone, and get that app they used to share launched again.
How do I set up the iPhone code to support this?
(Wow, corny.)
You have to leave the app connecting to the device, so when the device becomes available the app will connect to it (so long as the app is alive). Just call [centralManager connectPeripheral] on the CMPeripheral, so the phone will keep listening for the device and connect immediately when it sees it. That doesn't time out, so you can just leave it running forever.
If no app is to connect to the peripheral, there's nothing the peripheral can do to change that.
This is a little late, but here's what I would do to accomplish this:
When your device wants to connect, have it advertise a special service.
Assuming the phone is already scanning for devices, it will see the service and you can auto-connect to it.
Now you can have the periphal trigger whatever you like on the central by updating a characteristic, etc.
Of course, this relies on the phone scanning at the time you need the action to trigger, but that is the nature of the beast.

Resources