How to get service from the connected Bluetooth device in Xamarin forms in IOS - xamarin

I am getting service null for the connected devices, I need characteristic to write in device.
The "ConnectToDevice" method is retuning true but service is returning null, even status of the device is showing connected.
Here is below sample code design.
public bool ConnectToDevice(Device device)
{
// Disconnect any previously connected peripheral
if (_connectedPeripheral != null)
{
_centralManager.CancelPeripheralConnection(_connectedPeripheral);
_connectedPeripheral = null;
}
// Find the CBPeripheral object for the selected device
_selectedPeripheral = _centralManager.RetrievePeripheralsWithIdentifiers(
new NSUuid(device.Address)).FirstOrDefault();
if (_selectedPeripheral != null)
{
// Connect to the peripheral
_centralManager.ConnectPeripheral(_selectedPeripheral);
_selectedPeripheral.DiscoverCharacteristics(null, _selectedPeripheral.Services[0]);
return true;
}
else
{
return false;
}
}

Related

Xamarin Forms iOS Remote Notifications Not Displaying

Remote Notifications are not displaying on the device.
We are using iOS 11.2 and Twilio.
We have generated the APN in Apple Developer Portal and exported the
certificate and key into Twilio.
Twilio says the message is "sent," but it never displays on the
device.
The goal is to send a message with a simple header and body text, and have that display as a remote push notification on the device.
The Xamarin documentation seems incomplete, and I cannot find clear instructions on how to handle displaying the notification. I have looked at the Xamarin samples, but they mostly cover local notifications.
Questions are below in the comments. What is missing?
using Foundation;
using UserNotifications;
using UIKit;
namespace MyNotifications.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
protected UIWindow window;
protected string deviceToken = string.Empty;
public string DeviceToken { get { return deviceToken; } }
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
// check for a notification while running
if (options != null)
{
if (options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
{
NSDictionary remoteNotification = options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
if (remoteNotification != null)
{
//1) is this necessary to handle??? if so, how to display? what are the properties from the remoteNotification object that contain the text?
}
}
}
//this prompts for permissions, which are set
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null
);
app.RegisterUserNotificationSettings(notificationSettings);
app.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
UNUserNotificationCenter.Current.GetNotificationSettings((settings) =>
{
var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
});
// Request notification permissions from the user
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
{
// 2) how do we handle this??? what comes next?
});
return base.FinishedLaunching(app, options);
}
// 3) does this override need to do anything???
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
// 4) should all of these trigger a notification? does that have to happen manually?
if (application.ApplicationState == UIApplicationState.Active)
{
ProcessPushNotification(userInfo, true);
}
else if (application.ApplicationState == UIApplicationState.Background)
{
ProcessPushNotification(userInfo, true);
}
else if (application.ApplicationState == UIApplicationState.Inactive)
{
ProcessPushNotification(userInfo, true);
}
}
protected void ProcessPushNotification(NSDictionary userInfo, bool isAppAlreadyRunning)
{
if (userInfo == null) return;
if (isAppAlreadyRunning)
{
// 5) do we need to generate our own view???
}
else
{
// 6) how to handle in the background???
}
}
// APNS background
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
deviceToken = deviceToken.ToString();
}
// Handle errors and offline
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
// 7) what to do here???
}
}
}
Microsoft Docs has a few guides on how to deal with push notifications on both platforms, iOS and Android. Most of them are sending notifications from an Azure Notifications Hub but in this case, it shouldn't make any difference, because your question is about displaying push notifications, and not sending them.
The guide on how to send and receive notifications in a Xamarin.Forms app gives you an idea of the complete end-to-end setup. There are also two slightly different guides with a focus on Azure here and here
And for rendering messages on iOS, if the app is backgrounded, the notification is rendered by iOS without any custom code so if the app is properly configured and signed, you should be able to see a push notifications without any additional client-side code, just make sure you test on a device (sims doesn't support pushes) and valid profile with pushes enabled.

How to get Device Instance path from Bus Relations in Win32 API

Is there a good way to get the Device Instance path(e.g: USB\VID_021D&PID_0C51&MI_00\6&192CE49&4&0000) from Bus Relations (e.g:{0.0.1.00000000}.{4234a4c6-3535-49d6-971c-76ce1f22521e}) ?
I realize some terms in Windows have aliases, by "Device Instance path" and "Bus Relations", I mean the two properties found in the device manager:
I have tried to get the Device Instance path from the PropertyStore
int getProperty(std::string& sampleID)
{
HRESULT hr = S_OK;
IMMDeviceEnumerator* pEnumerator = NULL;
//CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(IMMDeviceEnumerator),
(void**)&pEnumerator);
if (hr != S_OK)
{
// error cleanup
return hr;
}
IMMDevice* pEndpoint = NULL;
std::wstring wSampleID(sampleID.begin(), sampleID.end());
hr = pEnumerator->GetDevice(wSampleID.c_str(), &pEndpoint);
if (hr != S_OK || pEndpoint == NULL)
{
// error cleanup
return hr;
}
if (!pEndpoint)
{
// error cleanup
return hr;
}
IPropertyStore* pProps = NULL;
hr = pEndpoint->OpenPropertyStore(
STGM_READ, &pProps);
PROPVARIANT varName;
// Initialize container for property value.
PropVariantInit(&varName);
hr = pProps->GetValue(
PKEY_AudioEndpoint_GUID, &varName);
if (hr != S_OK)
{
//error cleanup
return hr;
}
std::cout << varName.pwszVal << std::endl;
PropVariantClear(&varName);
SAFE_RELEASE(pProps)
SAFE_RELEASE(pEndpoint)
SAFE_RELEASE(pEnumerator);
return hr;
}
but there does not seem to be a property key to retrieve this piece of information for Audio Endpoint IMMDevice. Any suggestion is appreciated.
An example would be a headphone + microphone device which yields two
Bus Relation strings, one for headphone and the other for microphone.
My goal is to group the Bus Relations belonging to the same physical
device.
Bus Relations belonging to the same physical device have already been grouped and you can get it through "Bus relations" property of the same physical audio device (parent). You can find that via Device Manager (View -> Devices by connection) like this:
Is there a good way to get the Device Instance path(e.g:
USB\VID_021D&PID_0C51&MI_00\6&192CE49&4&0000) from Bus Relations
(e.g:{0.0.1.00000000}.{4234a4c6-3535-49d6-971c-76ce1f22521e}) ?
Although it is not clear that what grouped Bus relations will you use for. But you will find that not all (USB) devices have Device Instance path in this format: USB\VID_xxxx&PID_xxxx*. Take Microphone showed in above snapshot as an example, its Device Instance path like below, same with one of bus relations of its parent.

Xamarin Form and Bluetooth disconnect

Is there an event of a Android.Bluetooth class that is raised when the device is disconnected?
You have to set add a BluetoothGattCallback
public class MyGattCallback : BluetoothGattCallback
{
public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
{
base.OnConnectionStateChange(gatt, status, newState);
if(newState == ProfileState.Disconnected)
{
// disconnected
}
}
}
And when you connect your device, you pass it:
BluetoothDevice device = ...;
var callback = new MyGattCallback();
device.ConnectGatt(Application.Context, false, callback);

Android Auto - Callback when user connects mobile device

In regards to Android auto how can i get a callback when user has plugged the device into a car ? I'd like to trigger an action to occur based on when the user actually connects to android auto, is it possible ?
You should be able to get USB connection broadcast. From there you will have to write your own logic to figure out Android Auto is in foreground.
(may need to introduce a slight delay in case android auto takes time to come up. Launcher seems to be part of google play service)
Here is how I did it in my services onCreate method (right form the example code):
IntentFilter filter = new IntentFilter(CarHelper.ACTION_MEDIA_STATUS);
mCarConnectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String connectionEvent = intent.getStringExtra(CarHelper.MEDIA_CONNECTION_STATUS);
mIsConnectedToCar = "media_connected".equals(connectionEvent);
LogHelper.i(TAG, "Connection event to Android Auto: ", connectionEvent,
" isConnectedToCar=", mIsConnectedToCar);
if(mIsConnectedToCar ) {
if(mService == null) {
bindMusicService();
if (mService != null) {
try {
initMediaMetaData();
toggleMediaPlaybackState(mService.isPlaying());
} catch (RemoteException e) {
Log.d(TAG, e.toString());
}
}
}
}
}
};
registerReceiver(mCarConnectionReceiver, filter);

Developing iTunes like application in c#

I need to develop an application in c# that could automatically detect an iPhone when it is connected to the system and read a particular file for the iPhone file system. I basically want this file to be downloaded automatically from device to the PC. I used USBpcap tool that suggests that iTunes connects to phone using some XML format. Any help or insight greatly appreciated. Is there any documentation of Third party APIs that can get me started? There are some applications that can replicate iTunes functionality e.g Copytrans
Is there any protocol or APIs provided by Apple?
I have been digging the internet and found this link Layered communication for iPhone.
Also I am using the LibUsbDotNet libraries for communicating to the usb device(Example). Can any one suggest which EndPoints should be used.
It seems to me that I have to implement usbmuxd in windows application. It is a multilayer protocol. There must be some libraries that implement usbmuxd(I dont think I have to implement the protocol all by my self)
I dont have much idea about iTunes communication as well as USB communication. I am adding as much information as I can(of course with the things I come up with in my R&D). Any help is highly appreciated.
public static DateTime LastDataEventDate = DateTime.Now;
public static UsbDevice MyUsbDevice;
#region SET YOUR USB Vendor and Product ID!
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(1452, 4768);
#endregion
private void LibUSB()
{
ErrorCode ec = ErrorCode.None;
try
{
// Find and open the usb device.
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
// If the device is open and ready
if (MyUsbDevice == null)
throw new Exception("Device Not Found.");
// If this is a "whole" usb device (libusb-win32, linux libusb)
// it will have an IUsbDevice interface. If not (WinUSB) the
// variable will be null indicating this is an interface of a
// device.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(0);
}
// open read endpoint 1.
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);
// open write endpoint 1.
UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
int bytesWritten;
ec = writer.Write(usbmux_header.GetBytes(), 2000, out bytesWritten);
if (ec != ErrorCode.None)
throw new Exception(UsbDevice.LastErrorString);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 100 milliseconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 10000, out bytesRead);
if (ec == ErrorCode.Win32Error)
throw new Exception("port not open");
if (bytesRead == 0)
throw new Exception("No more bytes!");
// Write that output to the console.
Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
}
finally
{
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
// If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
// it exposes an IUsbDevice interface. If not (WinUSB) the
// 'wholeUsbDevice' variable will be null indicating this is
// an interface of a device; it does not require or support
// configuration and interface selection.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// Release interface #0.
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
MyUsbDevice = null;
// Free usb resources
UsbDevice.Exit();
}
}
}
class usbmux_header
{
public static UInt32 length = 10; // length of message, including header
public static UInt32 reserved = 0; // always zero
public static UInt32 type = 3; // message type
public static UInt32 tag = 2; // responses to this query will echo back this tag
public static byte[] GetBytes()
{
byte[] lgth = BitConverter.GetBytes(length);
byte[] res = BitConverter.GetBytes(reserved);
byte[] tpe = BitConverter.GetBytes(type);
byte[] tg = BitConverter.GetBytes(tag);
byte[] retArray = new byte[16];
lgth.CopyTo(retArray, 0);
res.CopyTo(retArray, 4);
tpe.CopyTo(retArray, 8);
tg.CopyTo(retArray, 12);
return retArray;
}
};
I have been trying to send hello packet bytes to iPhone but I am not able to read any response from phone.
To play with ipod you can use SharePodLib
As I understand it, only one client can use the USB connection to iOS at one time. On both macOS and Windows, that one client is usbmux. That library multiplexes TCP connections with higher-level clients, including iTunes, Photos, and (on macOS) the open-source peertalk library.
So on Windows, you wouldn't want to implement your own usbmux, but rather a client that sits on top of that, analogous to peertalk. I haven't seen anything open-source that does this, but a number of developers have accomplished it with their own proprietary software.
If anybody else has pointers about using usbmux on Windows, I'd love to hear about it.
—Dave
You can use imobiledevice-net. It provides a C# API to connect to iOS devices using your PC.
For example, to list all iOS devices connected to your PC, you would run something like this:
ReadOnlyCollection<string> udids;
int count = 0;
var idevice = LibiMobileDevice.Instance.iDevice;
var lockdown = LibiMobileDevice.Instance.Lockdown;
var ret = idevice.idevice_get_device_list(out udids, ref count);
if (ret == iDeviceError.NoDevice)
{
// Not actually an error in our case
return;
}
ret.ThrowOnError();
// Get the device name
foreach (var udid in udids)
{
iDeviceHandle deviceHandle;
idevice.idevice_new(out deviceHandle, udid).ThrowOnError();
LockdownClientHandle lockdownHandle;
lockdown.lockdownd_client_new_with_handshake(deviceHandle, out lockdownHandle, "Quamotion").ThrowOnError();
string deviceName;
lockdown.lockdownd_get_device_name(lockdownHandle, out deviceName).ThrowOnError();
deviceHandle.Dispose();
lockdownHandle.Dispose();
}

Resources