How to improve performance of CBCentralManager while CBPeripheralManager is active - ios

We've created an iOS app that implements a CBCentralManager to connect to a device that we've created, that transmits data at 10Hz. It's vitally important that this data comes through and displays quickly, so we have built tight latency checks around this, if too many points are missed or if the local clock detects that incoming values are slowed, we will fault and break the connection.
The client has asked us top implement a second iOS app that will observe the first one. We implemented a CBPeripheralManager in the original app which advertises, can be connected to, and will periodically publish its data to a few outgoing characteristics.
What we are finding is that we cannot seem to connect the observer iOS app to the original iOS app (i.e., the original iOS app has both a CBCentral connection to the device and CBPeripheral connection to the observer app active at the same time), without tripping up our latency checks on the incoming data from the device.
I've tried everything I can think of, I've used separate queues for both CBPeripheralManager and CBCentralManager, as follows:
q = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0);
ptr_CBPeriphMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:q];
Also,
I logged and timestamped everything, verified none of my code is taking too long
I moved almost all of my code out of BLE handlers to make them very light and not blocking,
I tried the separate queues (example shown above), with low priorities
I have tried slowing my CBPeripheralManager data rates to a trickle, a few updates a second
I have tried suspending the latency checks for three seconds after a CBPeripheralManager connection is established (which is very not ideal), but the problem seems to kick in randomly, not just after a connection.
It seems like no matter what I try, after 4-5 minutes of both peripheral and central connections being active (we have a loop where the second App repeatedly connects and disconnects every five seconds, to challenge the device connection) my incoming value updates from the device to the central slows to about 1/4 or 1/5 speed, or they stop for a full second and then three or four updates come in nearly simultaneously -- both of which trip our latency checks. It's like some queue is getting filled up and performance flatlines, but as I mentioned above I think I'm using separate queues.
I'm at my wits end... does anybody have any thoughts about how to prioritize my central functions over my peripheral functions in the iOS app, or to somehow improve performance to prevent this from being an issue and keep my app responsive to 10Hz updates from the device, even when being observed as a peripheral?
(Edited to state that we are connecting/disconnecting the second App repeatedly... perhaps I'm not cleaning up after the disconnection properly, and the garbage piles up and screws up BLE? That would explain why the problem seems to occur after 4-5 minutes regardless of the frequency of data updates over the second connection.)

Here are some suggestions:
Try creating queues using QOS_CLASS_USER_INITIATED or higher instead of QOS_CLASS_UTILITY.
Make sure that you call -[CBCentralManager stopScan] whenever you do not need to be scanning for peripherals, and -[CBPeripheralManager stopAdvertising] whenever you do not need to be prepared for incoming connections (probably whenever you are connected).
Call -[CBPeripheralManager setDesiredConnectionLatency:forCentral:] to reserve more resources.
However, if you can target iOS 11+, what I would recommend to decrease latency and increase speed is using a L2CAP channel. Although CoreBluetooth's L2CAP support is not documented well, here is a list of the available APIs.

Related

Does CBCentralManager connect ever time out?

I know the answer is nominally "no", but I mean really—what if the app goes into the background (with BTLE background processing enabled)? For 24 hours? Across an app update?
Under the heading "Reconnecting to Peripherals", this Apple documentation describes a reconnection workflow that first tries to reconnect to previously paired peripherals found via retrievePeripheralsWithIdentifiers: but then starts scanning again if you fail to connect. How do you know when to give up on connect-ing to a previously found peripheral if there is no formal timeout? How do you know when to start/keep scanning if the idea is to re-connect to a previously found BTLE device whenever you move back into proximity to it, without the user necessarily interacting with your app?
Also, a note further down that page says that some BTLE devices might invent a random identifier for themselves every time they're powered on, so even though you find some previously paired peripherals from retrievePeripheralsWithIdentifiers: you might not be able to connect to them as their names have changed. Do any BTLE devices do that in practice? That's nuts!
This is a tricky one to answer. The CoreBluetooth framework itself does not have an official timeout on connect requests. In fact it will try to connect the peripheral for as long as possible. But how long is that?
Well, unfortunately this is not something that is very well defined. You can be pretty confident that the connection will not time out while the app is in the foreground, but as soon as you involve connections in the background then things are not so funny any more. Obviously, like you mention, the pending connection will not remain after a phone reboot, etc.. which is fine since no user would expect the app to still be running after a reboot anyway. Regarding long running pending connections, you will find in Apple’s documentation that they tell you to opt-in for State Preservation and Restoration in order to make sure that the pending connections are properly kept while the app is suspended and eventually terminated. This would be good if it worked as advertised, but unfortunately it does not. After many years of working with this I have found that it is nearly impossible to get a reliable background pending connection on iOS. I have reported many bugs on this topic but so far none have been resolved.
There are a few issues in particular that I think you should pay extra attention to:
State Preservation and Restoration will completely stop working if a Bluetooth-state-change event happens while your app is in the terminated state. This essentially means that if the bluetooth chip gets reset for any reason (ex by toggling bluetooth/flight mode/etc..) then your app will never be relaunched again by Core Bluetooth whenever the peripheral is advertising within range. The reason for this is because all pending connections that have been set by your app will be cleared whenever the bluetooth chip is restarted. The problem with this is that your app will not be relaunched to be notified of this change, so the pending connections will never be recovered. So your app will think that the peripherals will connect, while in fact they will not. To me this one is the most serious issue and it alone makes CoreBluetooth extremely unreliable.
Sometimes the framework gets ”stuck” in a bad state (possibly by an internal race-condition or similar). This can happen randomly, but you can pretty easily reproduce this by calling connectPeripheral immediately in the didFailToConnect or didDisconnect callback. When this happen the ”connection state” property is set to “connecting” when a pending connection is in fact not set. To avoid this I have found that you should wait at least around 20ms before connecting, for example using a dispatch_after or something.
The framework internally uses XPC connections for interprocess communication in order to deliver bluetooth event. On some occasions this will break for whatever reason and the connection will be lost. I don’t know why this happens, but whenever it happens state preservation will stop working and you will manually have to relaunch the app to recover from it. Sometimes I manages to catch this in the device sysdiagnose logs...
Using an iPhone 7 and at the same time having an Apple Watch (paired the phone) will completely break all reconnects from behind the lock screen in case the Watch is not currently connected (out of range/flight mode/low battery/or any other reason). This is particularly bad since it was introduced recently! But it looks like the Apple Watch for some reason has "priority" over other bluetooth peripherals.
These are from the top of my head, but there are other issues as well. Regarding random addresses, most often these peripheral use so called ”random resolvable” addresses. This means that they appear random but in fact they can be resolved using an IRK (Identity Resolving Key) which is usually shared during initial bluetooth bonding. Devices that use completely random addresses are to my knowledge not very common.

iOS stops waking up the app upon incoming BLE connection from peripheral

we have a BLE peripheral that connects to the phone every hour and passes some data. Here is how the process works:
Upon launch with key UIApplicationLaunchOptionsBluetoothCentralsKey in
application(didFinishLaunchingWithOptions launchOptions) app re-initializes CBCentralManager with ID that was passed to it.
Then it goes through the regular restoration cycle and reads data off the BLE peripheral.
Performs REST request to the service in the cloud.
Assuming that app has been launched at least once after phone reboot everything works well for a few days (if app isnt running or been forced out of memory, iOS properly starts it up again, assuming user didnt do forced close manually).
However every few days iOS stops waking up the app when there is an incoming request from BLE device. If user relaunches app everything works properly for a few days and then stops agains. Given the nature of our product, it's critical to have our app / peripheral working together in the most reliable way possible.
Theories as to why it might be happening:
(upon closer examination all of them were dismissed)
Users restart the phone and forget to relaunch the app.
We've added logging of the uptime and it showed that phone didnt restart in between app launches.
Memory warnings lead to app being booted out.
Once again, added logging, they showed that there was no applicationDidReceiveMemoryWarning
Bad connection leads to app running for longer period than 10s when uploading results and iOS terminates it and gets upset
We artificially delayed server response by 15s to test this and everything continues to work properly during testing.
Any ideas on what is happening and why iOS stops notifying app about incoming BLE connection?
One of the problems is that we cannot figure out how to reliably reproduce the issue So any suggestions there will be much appreciated as well!
Thank you!
UPDATE 1:
Here is how we initialize CBCentralManager:
self.centralManager = CBCentralManager(delegate: self, queue: nil, options: [
CBCentralManagerOptionRestoreIdentifierKey : MyCentralManagerID,
CBCentralManagerOptionShowPowerAlertKey : 0])
I saw some suggestions that queue parameter should not be nil. Given that I'm unable to reliably reproduce issue I'm hesitant to make that change until I can confidently observe its effects.
I wanna start by saying that I have been working with CoreBluetooth for a long time now and from what I have noticed CoreBluetooth State Preservation and Restoration does not work reliably at all. You can get it working sort of "ok", but you will never get it to reconnect reliably unless Apple fixes it some day.
There are so many bugs that causes this to not work properly, but I will give you one that I believe is causing your problems:
State restoration will only relaunch your app due to bluetooth related activity if the event originates from a peripheral accessory that you are communicating with, such as connect/disconnect events and characteristics notifications. For other events, most importantly general bluetooth state change events, your app will not be relaunched and notified of this. The reason why this is so bad is because all bluetooth state change events will cancel all pending or current connections, meaning that pending connections will be dropped and your application will not be notified of it. This effectively means that your application will still believe that the connections are still pending when in fact they are not. Since your application is terminated at this time, the only way for it to wake up again is by having the user manually launch it again (or alternatively “hack” other background modes for this purpose, which does not work very reliably either).
This thing happens if the user toggles Flight Mode, toggles Bluetooth, power cycles the iOS device, or any other undefined reasons that many cause state changes…
But this is only one bug. Many other exists as well, such as the XPC connection being interrupted at different times for no apparent reason. I have also noticed that the pending connection can go into “limbo” mode where the peripheral state gets set to Connecting, but in fact it will never connect unless you cycle the connection state.
Anyhow, I am sad to say it, but if you are developing an app that must rely on the peripheral being reconnected in the background then I would not recommend doing it. You will be frustrated. I could probably write an essay about all the bugs in Core Bluetooth that Apple does not want to fix. Even more strange is that you can pretty easily ruin the bluetooth connectivity globally on the device from one single app so that no app can use bluetooth until the device is rebooted. This is pretty bad since it goes against Apple's own Sandboxing principle.

Multipeer Connectivity and data to send along the way

I am developing a platform game trying to make it as well for multiplayer using the IOS Multipeer connectivity. I am stuck/confused/do not know what is the best way to send messages between peers (mostly like 4 peers in the game). The game style is like fun run and I have 4 hero running and firing each other and stuff like that. The thing is that keeping the positions of the other players is pushing me crazy!!
Sometimes other players are positioned in the wrong position (keeping in mind all devices are with the same screen size). Is that because of the lag of connectivity. How much information I can send per seconds and what is the best way to manage data transferring?
Any idea/thoughts are appreciated.
The throughput of MPC depends mostly upon the connection. What I've seen as the biggest performance problem is when one of the peers has WiFi disabled. This forces MPC to communicate over bluetooth which is incredibly slow. I've seen it run 20x slower than MPC over Wifi.
You don't need to be connected to a WiFi network. Just enable WiFi on all of the devices and iOS will leverage shared WiFi networks or create its own adhoc network.
The second thing you want to ensure is that your peers don't invite each other. You can only have one inviter in your network. When multiple peers invite and accept connections the MPC network become unstable.
Third thing is sendData:(NSData *)data toPeers:(NSArray *)peerIDs withMode:(MCSessionSendDataMode)mode error:(NSError **)error. If you are broadcasting your packets to all peers in the toPeers: array AND mode is MCSessionSendDataReliable then MPC waits until all of the connected peers ACK the message before moving on to the next packet.
UPDATE: I did some testing with my own app and over WiFi and two devices I can put about 100kbps. I'm using an iPhone 6 Plus and an iPhone 5S.
UPDATE 2: Thinking more about your question, there are a couple things to keep in mind with MPC communications:
Do all of your sendData and didReceiveData calls on a background thread and have that thread update your position data in your model. Tell your viewController that updates are available with a delegate method or notification.
Keep your data packets small, but design them so an update received represents the current state of your player. This allows you to miss an update and not be completely out of sync -- "send player 1 moved to (10, 10)" instead of "player 1 moved by (1, -1)"
Number your packets and use MCSessionSendDataUnreliable. If you get a packet with an earlier number than the last one you processed, throw it away. If you follow the second guideline above, you won't need this packet.
If you follow Dan Loughney's suggestions, I think your best bet in debugging is to log the received coordinates from the other players. That should help you identify whether the problem is due to timing issues, misinterpreted data or something else.

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.

Resources