BLE on Xamarin Cross Platform - c#

In Xamarin.Form cross platform , is there any way to show the list of available BLE devices (after scan) in a pop-up dialog box or in menu list and then connect the desired BLE device from the pop-up dialog box and show the data on the UI created for displaying data ??????

You will need DependencyService to retrieve the list of available BLE devices and just display to the ListView as usual.
Besides, below component made by Xamarin may help you to find BLE devices easily for both iOS and Android.
https://components.xamarin.com/view/Monkey.Robotics

Xamarin doesn't provide cross-platform BLE support out of the box. There are a few 3rd-party libraries providing cross-platform BLE functionality, one of which I wrote after spending 1-2 years on a native BLE project: https://github.com/nexussays/ble.net
There is a complete Xamarin.Forms project for iOS, Android, and UWP (https://github.com/nexussays/ble.net/tree/master/test/ble.net.sampleapp) that provides the exact functionality you asked for -- scan, display results, connect, display dialog, etc. But to briefly cover the API here...
You can scan thusly:
await adapter.ScanForDevices(
( IBlePeripheral peripheral ) =>
{
// check if this is the device you want to connect to
// e.g., query peripheral.Advertisement.Services
},
cancellationTokenSource.Token );
And to connect to read/write/notify characteristics:
var connection = await adapter.ConnectToDevice( peripheral, TimeSpan.FromSeconds( 5 ));
if(connection.IsSuccessful())
{
var gatt = connection.GattServer;
var value = await gatt.ReadCharacteristicValue( someServiceGuid, someCharacteristicGuid );
await gatt.WriteCharacteristicValue( someServiceGuid, someCharacteristicGuid, new byte[]{ 1, 2, 3 } );
// etc...
}
else
{
Debug.WriteLine( "Error connecting to device. result={0:g}", connection.ConnectionResult );
}

Related

How to enable LightningProviders for GPIO?

I am trying to access the GPIO on my custom SBC using Windows 10 IoT Core. I have discovered that I must use LightningProviders to accomplish this . So I tried to follow this guide to use lightning providers properly.
I used very simple code:
if (LightningProvider.IsLightningEnabled)
{
LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
}
GpioStatus = "Initializing...";
var gpio = GpioController.GetDefault();
if (gpio == null)
{
GpioStatus = "There is no GPIO controller on this device.";
}
else
{
gpio.OpenPin(1).Write(GpioPinValue.High);
GpioStatus = gpio.OpenPin(1).Read().ToString();
}
Where GpioStatus is output text on a UI.
I discovered that if I run the LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider(); line outside of the enabled check, it picks up the GPIO controller and lets me detect how many pins I have and read them (All low). However I can't change the DriveMode or write to the pins without error. The error I get just says to Make sure the LightningProviders are enabled.
This brings me back to the guide I linked at the start. It suggests to enable DMAP drivers using the Device Portal for W10IoT or DMAPUtil.exe. I have tried both. In the Device Portal the area where it should be is just blank. And in the command line trying to use the DMAPUtil.exe only returns that dmaputil.exe is not available on this system.
Therefore I am asking if there is any other way to enable the LightningProviders or if there a way to know if they are incompatible with my board?
Thanks!
UPDATE
Also tried using the devcon.exe commands in the W10IoT Command line.
I am able to locate the Direct memory access controller but when i do devcon.exe enable *PNP0200 it says it is enabled but remains disabled when checked with devcon.exe status *PNP0200
Please confirm if you have added the IOT_DMAP_DRIVER feature in your OEMInput.xml, this feature will add the DMAP driver in the image. If IOT_DMAP_DRIVER is removed from the OEMInput.xml, the Default Driver Controller will be blank in device protal, and dmaputil will be not available on Windows IoT Core. Please see the IoT Core feature list.
Update:
You can download the source of Lighting Provider, and then deploy and debug in your custom image.

How to display 2 web camera preview in UWP?

Hello I displayed 1 webcam preview in UWP and that was a success.
But now I want to use 2 camera's preview on my program or be able to choose between the two cameras while connected 2 cameras on computer.
When I run 1 webcam preview, I referred to documentation on using MediaCapture and it was good.
But now I don't know how to display 2 camera previews or select a one between cameras.
Is it impossible?
Yes, it is possible :-) . The MediaCapture class takes the default camera when you call the InitializeAsync method without parameters, but there is another overload that allows you to specify the device ID.
The documentation shows how to discover video capture devices:
DeviceInformationCollection devices =
await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
Now you can initialize multiple MediaCapture instances like this:
foreach ( var device in devices )
{
var mediaInitSettings =
new MediaCaptureInitializationSettings { VideoDeviceId = device.Id };
MediaCapture mediaCapture = new MediaCapture();
mediaCapture.InitializeAsync(mediaInitSettings);
//do something with the media capture
}
Naturally, when you want to display multiple previews, you will need to have multiple CaptureElements, each set to the specific MediaCapture instance you want.
However this approach is quite simplified. To make sure the concurrent capture and preview is supported, you must first ensure to query only cameras that support device profile using MediaCapture.IsVideoProfileSupported method as shown in the documentation and then also check find a concurrency-enabled profile common for both cameras - MediaCapture.FindConcurrentProfiles, see docs. Only then you can safely create the two previews and know the app will not crash.

How can i create Flashlight app in uwp C#

I have Lumia 830 and i've tried to create flashlight app in UWP C#. my device Flashlight works great but i don't know why i can't create my own app turn on / off Torch of my phone.
I use Lamp class :
var lamp = await Lamp.GetDefaultAsync();
if (lamp == null)
{
ShowErrorMessage("No Lamp device found");
return;
}
lamp.IsEnabled = true;
when run this code on my phone "lamp" is null and it couldn't find my FlashLED. I've got this code from MSDN.Microsoft.com and thay said
If the returned object is null, the Lamp API is unsupported on the
device. Some devices may not support the Lamp API even if there is a
lamp physically present on the device.
This class doesn't work on my Lumia 830 i don't kno why? :(
also i use this code :
var mediaDev = new MediaCapture();
await mediaDev.InitializeAsync();
var videoDev = mediaDev.VideoDeviceController;
var tc = videoDev.TorchControl;
if (tc.Supported)
{
// But wait, for this to work with Blue camera drivers, we have to Start a recording session
// Create video encoding profile as MP4
var videoEncodingProperties = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
// Start Video Recording
var videoStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync("tempVideo.mp4", CreationCollisionOption.GenerateUniqueName);
await mediaDev.StartRecordToStorageFileAsync(videoEncodingProperties, videoStorageFile);
// Turn on Torch
mediaDev.VideoDeviceController.TorchControl.Enabled = true;
}
this code works and my FlashLED turn on but it record video and it take's user SD Card memory.
please help me if you know there is best way to turn on/off Torch or FlashLED.
thanks in advance
Hussein Habibi Juybari
The Lamp API is designed for Windows 10 devices only and you can only use it on devices which support the API. Currently supported devices are 950/950XL, 650, and 550. Older devices will not be updated to support this API. You should fall back to the Windows 8.1 method of turning on flash when you detect that the lamp device is not available on older devices.
From: https://wpdev.uservoice.com/forums/110705/suggestions/15846967
Please test default sample named LampDevice (cf. https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/LampDevice). Do you have the same behavior ? I just tested on Lumia 930 it works fine. No Lumia 830 to test it.

Is it possible to launch system/third party app using an NDEFLaunchApp record to get the URI and by using LaunchUriAsync without NFC Tags?

So I have spent the whole night looking like a zombie in the morning trying to figure out how the OS handles an NFC tap for an NDEFLaunchApp Record and I have known the following.
I'm pretty sure that there is a workaround which lets you launch a system app / third party app (if you know the product Id / GUID) from your app. As there are apps in the Windows Phone Store which I have somehow figured out what I've been trying to.
I have come up with the following code:
NdefLaunchAppRecord appLaunchRecord = new NdefLaunchAppRecord();
appLaunchRecord.AddPlatformAppId("WindowsPhone", "{App GUID}");
appLaunchRecord.Arguments = "_default";
// Creating a new NdefMessage from the above record.
var message = new NdefMessage { appLaunchRecord };
// Getting the record from the message that we just created
foreach (NdefLaunchAppRecord record in message)
{
var specializedType = record.CheckSpecializedType(false);
if (specializedType == typeof(NdefLaunchAppRecord))
{
var x = String.Join(" ", record.Payload);
// Getting the payload by GetString gets a formatted Uri with args
string result = System.Text.Encoding.UTF8.GetString(record.Payload, 0, record.Payload.Length);
// result = "\0\fWindowsPhone&{5B04B775-356B-4AA0-AAF8-6491FFEA5630}\0\b_default";
// result = "(null)(form feed)WindowsPhone&{App GUID}(null)(backspace)_default
// So this will be sent to the OS and I believe the OS will then launch the specified app by an unknown protocol
// like xxx://result
// and the app will be launched?
// So is it then possible to somehow call the following:
await Windows.System.Launcher.LaunchUriAsync(new Uri("OUR MAGIC RESULT?", UriKind.RelativeOrAbsolute));
If anyone has / can figure out a way for this, it would be a REAL Service to the WP Community as developers are restricted by Microsoft to open certain settings / apps which are actually needed by those apps. For instance (speech settings, audio settings, about settings, alarms, region settings, date+time);
APPS that possibly have a workaround:
Music Hub Tile (Launches the old Music+Videos Hub)
http://www.windowsphone.com/en-gb/store/app/music-hub-tile/3faa2f9e-6b8d-440a-bb60-5dd76a5baec1
Tile for Bing Vision
http://www.windowsphone.com/en-gb/store/app/tile-for-bing-vision/05894022-e18c-40a4-a6cc-992383aa7ee8
There are reserved uri schemes for bing and zune.
See: http://msdn.microsoft.com/en-us/library/windows/apps/jj207065(v=vs.105).aspx
Those two apps propably use these and have found some undocumented use of the scheme.
If there is an uri scheme that launches any app by guid from within your app, it is hidden well.
Currently you can only launch apps that registered for an uri scheme or file association.

C# - Windows Mobile - Pairing with Zebra RW 420

Update: This may not be "Pairing". This may just need to have a service started and bound to a port. However, this code is not storing it either. I need the device to be stored even after the application is closed.
I am building a program specifically suited for Zebra RW 420's on a Windows Mobile 6 Handheld device. The application needs to allow a mobile device to pair with the printer on COM1. I believe I am very close to getting it, but I can't get the pair request to work.
I am able to communicate with the printer and even print by directly connecting and printing, but I can't get the mobile device to actually pair with it. I've tried a variation of pins to include null, "1", "0000", and "1234". No matter what, the method always returns false. Any suggestions or ideas why this might be failing? I can pair the device just find in the WM6 Bluetooth menu, but not in my application.
It might be important to note that the little light bulb icon on the printer comes on when the program says it is attempting to pair, but after about 5 to 10 seconds, it fails.
BluetoothSecurity.PairRequest(device, "1"))
Additional Information:
I've successfully paired with my Android phone using this code.
I then logged in and set a PIN on the Zebra printer. However, this code still fails to pair with the printer even when I know the pin is correct / set in the printer.
From https://km.zebra.com/kb/index?page=answeropen&type=open&searchid=1336682809706&answerid=16777216&iqaction=5&url=https%3A%2F%2Fkm.zebra.com%2Fkb%2Findex%3Fpage%3Dcontent%26id%3DSO8031%26actp%3Dsearch%26viewlocale%3Den_US&highlightinfo=6292341,26,43#
Zebra Bluetooth enabled mobile printers are 'slave' devices only. The printers will pair with any 'master' device that tries to make a valid connection. Since only a master device can initiate a connection, the printer does not store pairing data, that function is always done on the master device. The printer can only be connected to one master device at a time, but any number of master devices that have stored pairing information for the printer would be able to initiate a connection to the printer without having to rediscover it.
I'm guessing that this means the InTheHand.Net BluetoothSecurity.PairRequest might not work for this type of pairing?
In the Bluetooth section of the WM handheld, under the "Devices" tab, I can add the device. I need to essentially do that. I need to register the device in that list and then set it to use COM 1 in the "COM Ports" section. The application I am using doesn't actually print. It's sole purpose is to prepare the printer for other applications.
The quote from Zebra make it sounds as pairing is actually not required at all. Are you printing from your app? If so just connect to the SPP service and send the text.
BluetoothAddress addr = ...
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write ...
(From General Bluetooth Data Connections)
The Zebra Mobile Printer needed to be properly configured before pairing with this method will work. Here is what I did:
First, I ran the following commands on the printer:
.
! U1 setvar "bluetooth.authentication" "setpin"
! U1 getvar "bluetooth.authentication"
! U1 getvar "bluetooth.enable"
! U1 getvar "bluetooth.discoverable"
! U1 setvar "bluetooth.bluetooth_pin" "0000"
! U1 getvar "bluetooth.bluetooth_pin"
Then, the application with this code ran successfully.
.
int pair_req = 0;
try
{
if (BluetoothSecurity.SetPin(device, "0000")) {
while (status == false && pair_req < 3)
{
++pair_req;
status_box.Text = status_box.Text + '\n' + "Attempt " + pair_req.ToString();
status_box.Update();
if (BluetoothSecurity.PairRequest(device, "0000"))
{
status = true;
client.Refresh();
status_box.Text = "Paired Successfully.";
status_box.Update();
Thread.Sleep(5000);
}
else
{
status = false;
}
}
}
}
catch (ArgumentNullException e)
{
status_box.Text = "Pair failed.";
status_box.Update();
Thread.Sleep(5000);
}
status_box.Update();
Thread.Sleep(400);

Categories