Xamarin.iOS CoreBluetooth/External Accesory issue - ios

I've looking here on Forums, on the monotouch samples GIT hub, and never found a really functional sample to use CoreBluetooth in order to achieve the following:
1.Check if is there a device that match a criteria(by name or some identifier of the device) paired and connected
2.If paired but not connected, try connect to it
3.If connection fails, then show a list of the bluetooth devices that matches the criterias on topic 1 so the user can select and connect to it
Note: The device I'm trying to connect uses SPP but is Apple MFi certified. It is a credit card reader over bluetooth and some of then even implement ExternalAccessory protocols
The CoreBluetooth samples page is empty http://developer.xamarin.com/samples/ios/CoreBluetooth/
I've trying this pretty simple sample that never get the events called after the scan:
public static class BTHelper
{
private static CBCentralManager manager;
private static CBUUID UUID;
static BTHelper()
{
manager =
manager.DiscoveredPeripheral += OnDiscovery;
manager.ConnectedPeripheral += OnConnected;
manager.DisconnectedPeripheral += OnDisconnected;
UUID = CBUUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
}
public static void CheckBluetooth()
{
manager.ScanForPeripherals(new[] { UUID });
}
static void OnDisconnected(object sender, CBPeripheralErrorEventArgs e)
{
Console.WriteLine("Disconnected - " + e.Peripheral.Name);
}
static void OnConnected(object sender, CBPeripheralEventArgs e)
{
Console.WriteLine("Connected - " + e.Peripheral.Name);
}
static void OnDiscovery(object sender, CBDiscoveredPeripheralEventArgs e)
{
Console.WriteLine("Found - " + e.Peripheral.Name);
}
}
Can anyone help? I've being really tired of googling and looking of many questions on SO with no real answer.
#XamarinTeam, you guys should provide a sample on how to use it... We are lost without reference...
Thank, really appreciate any help...
Gutemberg

It seems like you are looking at wrong documents.Core Bluetooth only allows you to communicate with Bluetooth Low Energy (BLE) devices using the GATT profile. you can not scan SPP device with corebluetooth.
For your MFI device, you need to check External Accessory framework , It allows communication with 'legacy' Bluetooth devices using profiles such as the Serial Port Protocol (SPP).
To answer your question:
: 1.Check if is there a device that match a criteria(by name or some identifier of the device) paired and connected
You can use showBluetoothAccessoryPicker function of EAAccessoryManager to get list of Available devices, read more here
2.If paired but not connected, try connect to it
There is not any documented way to check for this. You can not initiate connect from app without showBluetoothAccessoryPicker . You can monitor for
EAAccessoryDidConnect notification. if this method is not called, and showbluetoothaccessorypicker 's complition get called, your device is not connected.
3.If connection fails, then show a list of the bluetooth devices that matches the criterias on topic 1 so the user can select and connect to it
1)
After completion of showbluetoothaccessorypicker You can check in ConnectedAccessories . If its not avaiable, call showbluetoothaccessorypicker to display list of accessories.
Sample code for using External Accessory framework in your code
EAAccessoryManager manager= EAAccessoryManager.SharedAccessoryManager;
var allaccessorries= manager.ConnectedAccessories;
foreach(var accessory in allaccessorries)
{
yourlable.Text = "find accessory";
Console.WriteLine(accessory.ToString());
Console.WriteLine(accessory.Name);
var protocol = "com.Yourprotocol.name";
if(accessory.ProtocolStrings.Where(s => s == protocol).Any())
{
yourlable.Text = "Accessory found";
//start session
var session = new EASession(accessory, protocol);
var outputStream = session.OutputStream;
outputStream.Delegate = new MyOutputStreamDelegate(yourlable);
outputStream.Schedule(NSRunLoop.Current, "kCFRunLoopDefaultMode");
outputStream.Open();
}
}
and
public class MyOutputStreamDelegate : NSStreamDelegate
{
UILabel label;
bool hasWritten = false;
public MyOutputStreamDelegate(UILabel label)
{
this.label = label;
}
public override void HandleEvent(NSStream theStream, NSStreamEvent streamEvent)
{
//write code to handle stream.
}
}
There is not any perticular demo for using Exeternal Accessory framework,
but You can check this sample code for understanding how it works.:
Whole Project
AccessoryBrowser class

Related

Not able to discover CBServices I am advertising

I am creating a custom CBService and adding them to the CBPeripheralManager. I am advertising the service along with the Advertisement data. But I am not able to see the service I created in the Light Blue app. The Light Blue app shows two services which I don't know what they are and I didn't add those. The advertisement data is shown but not the service. Below is my implementation of creating a service and advertising it in Xamarin:
void AdvertiseData()
{
var uui = new CBUUID[] { CBUUID.FromString("E20A39F4-73F5-4BC4-A12F-17D1AD07A961") };
var nsArray = NSArray.FromObjects(uui);
var nsObject = NSObject.FromObject(nsArray);
var manufacturerDataBytes = new byte[6] { 5, 255, 76, 0, 25, 35 };
var advertisementData = new NSDictionary(
CBAdvertisement.DataLocalNameKey, "id1",
CBAdvertisement.DataServiceUUIDsKey, nsObject,
CBAdvertisement.DataManufacturerDataKey, NSData.FromArray(manufacturerDataBytes));
try
{
var newService = new CBMutableService(CBUUID.FromString("1F3A8B1E-4BAA-45DA-B3A4-7A19DDC86305"), false);//1F3A8B1E-4BAA-45DA-B3A4-7A19DDC86305
newService.Characteristics = new CBCharacteristic[]
{
new CBMutableCharacteristic(CBUUID.FromString("906377DD-F782-448C-9A65-796B48E10894"),//906377DD-F782-448C-9A65-796B48E10894
CBCharacteristicProperties.Read, "FooChar",
CBAttributePermissions.Readable),
new CBMutableCharacteristic(CBUUID.FromString("2B77EC99-BE87-45D3-863C-599D5202E4C0"),//2B77EC99-BE87-45D3-863C-599D5202E4C0
CBCharacteristicProperties.Write, null,
CBAttributePermissions.Writeable)
};
cbPeriphMang.AddService(newService);
//cbPeriphMang.RemoveAllServices();
}
catch(Exception ex)
{
}
if (cbPeriphMang.Advertising) cbPeriphMang.StopAdvertising();
cbPeriphMang.StartAdvertising(new StartAdvertisingOptions(){LocalName="alpha", ServicesUUID = new CBUUID[] { CBUUID.FromString("1F3A8B1E-4BAA-45DA-B3A4-7A19DDC86305")} } );
}
I assume you are running the LightBlue app on another iOS device. In my experience iOS caches a lot of BLE data including services and characteristics. If the peripheral changes any service or characters (or adds or deletes) then iOS will not see those changes until you restart bluetooth on the iOS device where LightBlue is running. In some cases all I need to do is turn bluetooth off/on but in other cases I had to restart the device completely. If you scan the Apple developer forums you will find other people reporting the same problem and same workaround.

Use Bloothtooth LE while app is in background

I am building an iOS app with Xamarin, with this BLE plugin:
https://github.com/aritchie/bluetoothle
I'm just broadcasting a UUID via BLE, and it works. Here is my code:
var data = new Plugin.BluetoothLE.Server.AdvertisementData
{
LocalName = "MyServer",
};
data.ServiceUuids.Add(new Guid("MY_UUID_HERE"));
await this.server.Start(data);
The only problem is that it stops broadcasting once I put the app in the background. And resumes again when I open the app again.
How can I let it continue to broadcast once it's in the background? I read the documentation here:
https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html
And it says that I have to use the CBCentralManager class to obtain the preservation and restoration feature (so I can keep broadcasting the UUID at all times), but I'm having a hard time translating this to Xamarin/C#.
EDIT
After researching some more, I read that I need to create an instance of CBCentralManager and implement WillRestoreState in the delegate. I did this in the AppDelegate:
[Register("AppDelegate")]
public class AppDelegate : MvxApplicationDelegate, ICBCentralManagerDelegate
{
private IGattServer server = CrossBleAdapter.Current.CreateGattServer();
private CBCentralManager cbCentralManager;
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// irrelevant code...
this.Ble();
return true;
}
private async Task Ble()
{
try
{
await Task.Delay(5000); // wait for it to finish initializing so I can access BLE (it crashes otherwise)
var options = new CBCentralInitOptions();
options.RestoreIdentifier = "myRestoreIndentifier";
this.cbCentralManager = new CBCentralManager(this,null,options);
var data = new Plugin.BluetoothLE.Server.AdvertisementData
{
LocalName = "MyServer",
};
data.ServiceUuids.Add(new Guid("MY_UUID_HERE"));
await this.server.Start(data);
}
catch (Exception e)
{
}
}
public void UpdatedState(CBCentralManager central)
{
//throw new NotImplementedException();
}
[Export("centralManager:willRestoreState:")]
public void WillRestoreState(CBCentralManager central, NSDictionary dict)
{
//never gets called
}
But it didn't make a difference for me. And the WillRestoreState method never gets called... I don't mind using a different plugin/library if I have to at this point...
EDIT 2
I just realized that the app is still broadcasting while it is in the background, I just don't see the service UUID anymore (in the web portal of the beacon that I'm testing with), I only see the phone's identifier.
After doing tons of research, I found that it is simply an iOS restriction - you can not broadcast the UUID of a BLE service while your app is in the background. Background work is very restrictive in iOS.
EDIT to include Paulw11 comment (which is true):
You can advertise a service, but it is advertised in a way that only another iOS device that is specifically scanning for that service UUID can see.
Although you can not broadcast the UUID of a BLE service while your iOS app is in the background, for anyone trying to do something similar, you should look into iBeacon. It's Apple's protocol for letting iOS apps do bluetooth stuff while it's in the background.

Knowing programmatically if cell data is disabled for the app for iOS [duplicate]

I have an iOS app that makes some small network requests on app launch (resource updates, etc). If the user turns off cellular access for the app in iOS Settings, they get a prompt from iOS about network usage every time they launch. Is there a way to know programmatically that cellular data for this app has been disabled, so that I can disable the requests at startup?
So I found this on the apple dev forums from an Apple engineer (https://devforums.apple.com/message/1059332#1059332).
Another developer wrote in to DTS and thus I had a chance to
investigate this in depth. Alas, the news is much as I expected:
there is no supported way to detect that your app is in this state.
Nor is there a way to make a "no user interaction" network connection,
that is, request that the connection fail rather than present UI like
this. If these limitations are causing problems for your app, I
encourage you to file a bug describing your specific requirements.
https://developer.apple.com/bug-reporting/
So it looks like it is not possible to detect if cellular data for your app has been turned off.
Edit
I filed a radar for this requesting that it be added. I just got this notification in my radar
We believe this issue has been addressed in the latest iOS 9 beta.
I looked through the API diffs, but so far I can't find the new API.
As of iOS9, the capability to check the setting to enable/disable use of cellular data for your app (Settings/Cellular/AppName) is available using Apple's CTCellularData class. The following code will set cellularDataRestrictedState when it is run initially and then set it and log whenever it changes:
import CoreTelephony
var cellularDataRestrictedState = CTCellularDataRestrictedState.restrictedStateUnknown
let cellState = CTCellularData.init()
cellState.cellularDataRestrictionDidUpdateNotifier = { (dataRestrictedState) in
if cellularDataRestrictedState != .restrictedStateUnknown { // State has changed - log to console
print("cellularDataRestrictedState: " + "\(dataRestrictedState == .restrictedStateUnknown ? "unknown" : dataRestrictedState == .restricted ? "restricted" : "not restricted")")
}
cellularDataRestrictedState = dataRestrictedState
}
Unfortunately (as of iOS11) this seems to check only the state of the app's switch - if your app's switch is set to enabled and the user switches the Cellular Data master switch to disabled, this API will return the app's state as being "not restricted".
Just wanted to add an Objective C version of the above Swift code for future travellers.
- (void)monitorCanUseCellularData {
if (GCIsiOS9) {
CTCellularData *cellularData = [[CTCellularData alloc] init];
NSLog(#"%ld", cellularData.restrictedState);
// 0, kCTCellularDataRestrictedStateUnknown
[cellularData setCellularDataRestrictionDidUpdateNotifier:^(CTCellularDataRestrictedState state) {
NSLog(#"%ld", state);
self.canUseCellularData = cellularData.restrictedState ==2?true:false;
}];
}
}
I have found that the CTCellularData class needs some time to get to the correct value. In my implementation I call the didUpdateNotifier very early after appDidFinishLaunching. By the time my networking call are returning with errors I definitely have a correct value for the restricted state.
class CellularRestriction: NSObject {
private static var cellularData = CTCellularData()
private static var currentState = CTCellularDataRestrictedState.restrictedStateUnknown
static var isRestricted: Bool {
currentState = cellularData.restrictedState
return currentState == .restricted
}
static func prepare() {
if currentState == .restrictedStateUnknown {
cellularData.cellularDataRestrictionDidUpdateNotifier = { state in
currentState = cellularData.restrictedState // This value may be inconsistent, however the next read of isRestricted should be correct.
}
}
}
}
You can detect if cellular data disabled using NWPathMonitor class. (https://developer.apple.com/documentation/network/nwpathmonitor)
let cellMonitor = NWPathMonitor(requiredInterfaceType: .cellular)
cellMonitor.pathUpdateHandler = { path in
self.isCellConnected = path.status == .satisfied
}
Adding to dirkgroten's answer, you can use the Apple Reachability class, found here:
https://developer.apple.com/Library/ios/samplecode/Reachability/Introduction/Intro.html
It uses SCNetworkReachability, and is very straight forward to use, it will detect connectivity via Cell and WiFi as you will need to check both at start up.
There are lots of frameworks out there that will give you the status of your network connectivity, and of course you can roll your own. I've found AFNetworking to be one of the best. It has a singleton class called AFNetworkReachabilityManager that abstracts some of the complexities for you. Specifically you'll want to look at the two boolean properties:
reachableViaWWAN
reachableViaWiFi
There is also a reachability changed status block that you can set:
– setReachabilityStatusChangeBlock:
AFNetworking Github
AFNetworkReachabilityManager

How do I know if cellular access for my iOS app is disabled?

I have an iOS app that makes some small network requests on app launch (resource updates, etc). If the user turns off cellular access for the app in iOS Settings, they get a prompt from iOS about network usage every time they launch. Is there a way to know programmatically that cellular data for this app has been disabled, so that I can disable the requests at startup?
So I found this on the apple dev forums from an Apple engineer (https://devforums.apple.com/message/1059332#1059332).
Another developer wrote in to DTS and thus I had a chance to
investigate this in depth. Alas, the news is much as I expected:
there is no supported way to detect that your app is in this state.
Nor is there a way to make a "no user interaction" network connection,
that is, request that the connection fail rather than present UI like
this. If these limitations are causing problems for your app, I
encourage you to file a bug describing your specific requirements.
https://developer.apple.com/bug-reporting/
So it looks like it is not possible to detect if cellular data for your app has been turned off.
Edit
I filed a radar for this requesting that it be added. I just got this notification in my radar
We believe this issue has been addressed in the latest iOS 9 beta.
I looked through the API diffs, but so far I can't find the new API.
As of iOS9, the capability to check the setting to enable/disable use of cellular data for your app (Settings/Cellular/AppName) is available using Apple's CTCellularData class. The following code will set cellularDataRestrictedState when it is run initially and then set it and log whenever it changes:
import CoreTelephony
var cellularDataRestrictedState = CTCellularDataRestrictedState.restrictedStateUnknown
let cellState = CTCellularData.init()
cellState.cellularDataRestrictionDidUpdateNotifier = { (dataRestrictedState) in
if cellularDataRestrictedState != .restrictedStateUnknown { // State has changed - log to console
print("cellularDataRestrictedState: " + "\(dataRestrictedState == .restrictedStateUnknown ? "unknown" : dataRestrictedState == .restricted ? "restricted" : "not restricted")")
}
cellularDataRestrictedState = dataRestrictedState
}
Unfortunately (as of iOS11) this seems to check only the state of the app's switch - if your app's switch is set to enabled and the user switches the Cellular Data master switch to disabled, this API will return the app's state as being "not restricted".
Just wanted to add an Objective C version of the above Swift code for future travellers.
- (void)monitorCanUseCellularData {
if (GCIsiOS9) {
CTCellularData *cellularData = [[CTCellularData alloc] init];
NSLog(#"%ld", cellularData.restrictedState);
// 0, kCTCellularDataRestrictedStateUnknown
[cellularData setCellularDataRestrictionDidUpdateNotifier:^(CTCellularDataRestrictedState state) {
NSLog(#"%ld", state);
self.canUseCellularData = cellularData.restrictedState ==2?true:false;
}];
}
}
I have found that the CTCellularData class needs some time to get to the correct value. In my implementation I call the didUpdateNotifier very early after appDidFinishLaunching. By the time my networking call are returning with errors I definitely have a correct value for the restricted state.
class CellularRestriction: NSObject {
private static var cellularData = CTCellularData()
private static var currentState = CTCellularDataRestrictedState.restrictedStateUnknown
static var isRestricted: Bool {
currentState = cellularData.restrictedState
return currentState == .restricted
}
static func prepare() {
if currentState == .restrictedStateUnknown {
cellularData.cellularDataRestrictionDidUpdateNotifier = { state in
currentState = cellularData.restrictedState // This value may be inconsistent, however the next read of isRestricted should be correct.
}
}
}
}
You can detect if cellular data disabled using NWPathMonitor class. (https://developer.apple.com/documentation/network/nwpathmonitor)
let cellMonitor = NWPathMonitor(requiredInterfaceType: .cellular)
cellMonitor.pathUpdateHandler = { path in
self.isCellConnected = path.status == .satisfied
}
Adding to dirkgroten's answer, you can use the Apple Reachability class, found here:
https://developer.apple.com/Library/ios/samplecode/Reachability/Introduction/Intro.html
It uses SCNetworkReachability, and is very straight forward to use, it will detect connectivity via Cell and WiFi as you will need to check both at start up.
There are lots of frameworks out there that will give you the status of your network connectivity, and of course you can roll your own. I've found AFNetworking to be one of the best. It has a singleton class called AFNetworkReachabilityManager that abstracts some of the complexities for you. Specifically you'll want to look at the two boolean properties:
reachableViaWWAN
reachableViaWiFi
There is also a reachability changed status block that you can set:
– setReachabilityStatusChangeBlock:
AFNetworking Github
AFNetworkReachabilityManager

Make a phone call from app when user presses the call button (override default behaviour)

I have a listfield in my app showing a list of contacts. I would like to call the selected contact when the user presses the green call button (instead of the default behaviour which launches the phone call log app).
This means there are 2 issues:
1) can I intercept the green call button?
2) how can I make the call from the app?
Before answering the question, it is assumed that you are keeping track of the currently selected item in the list, and you have a way of finding the related phone number.
1) Intercept the call button
You need to implement the keyDown(int, int) method in a Manager or Screen, catch the correct keycode, and return true:
protected boolean keyDown(int keycode, int time)
{
// check for the green phone button
if (keycode == 1114112)
{
/*
* Place your custom calling code here.
*/
return true; // indicates that this method has consumed the keypress
}
else
{
return super.keyDown(keycode, time);
}
}
(based on answer given at http://supportforums.blackberry.com/t5/Java-Development/Can-Over-ride-Call-Button-using-api-Issue-Shows-Context-Menu-on/m-p/252554/highlight/true#M41073)
2) Make a phone call
You need to Invoke() the phone app, passing it the phone number you wish to call:
PhoneArguments callArgs = new PhoneArguments(
PhoneArguments.ARG_CALL, "+27 83 111 1234");
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, callArgs);
So combining gives this code:
protected boolean keyDown(int keycode, int time)
{
// check for the green phone button
if (keycode == 1114112)
{
// get phone number - you must write this yourself
String number = selectedContact.getNumber(); // assume some method here depending on your solution
// make the call
PhoneArguments callArgs = new PhoneArguments(
PhoneArguments.ARG_CALL, number);
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, callArgs);
// indicate that the key has been processed
return true;
}
else
{
return super.keyDown(keycode, time);
}
}
From the Blackberry documentation:
net.rim.blackberry.api.phone
public final class Phone extends
Object
This class provides the following:
* Advanced utilities for interaction with the Phone
application. You can use the methods
in this class for finer manipulation
of the Phone application. For example,
injecting DTMF tones into active
calls.
* Access multiple lines on the device.
* Adding data to the incoming and active call screens, if supported.
Multi-line examples
Example A: Switching a line
Create a class that extends MultiLineListener.
public class MultiLineAction extends MultiLineListener
Register the class as a PhoneListener.
Phone.addPhoneListener(this);
Implement the MultiLineListener callbacks so that the app can be
notified of switching results.
public void setPreferredLineFailure(int lineId)
{
_screen.popupMessage("Switching failed");
}
public void setPreferredLineSuccess(int lineId)
{
_screen.popupMessage("Switching to " + Phone.getLineNumber(lineId) + "
completed" );
}
Invoke Phone.setPreferredLine().
Phone.setPreferredLine( Phone.getLineIds()[0]);
Example B: Initiate an outgoing call
Invoke Phone.initiateCall.
Phone.initiateCall(Phone.getLineIds()[0],
"5195550123");
Deregister the class from the phone listener before the application
is closed.
Phone.removePhoneListener(this);
Category:
Signed: This element is only accessible by signed applications. If
you intend to use this element, please
visit
http://www.blackberry.com/go/codesigning
to obtain a set of code signing keys.
Code signing is only required for
applications running on BlackBerry
smartphones; development on BlackBerry
Smartphone Simulators can occur
without code signing. Since:
BlackBerry API 4.0.0
http://www.blackberry.com/developers/docs/6.0.0api/

Resources