For a project I'm working on, I need to read data from a BluetoothLE module (HM-10). I need to read and use this data from a Unity-application. To connect and read data I'm building a plugin for Unity using Visual Studio 2017. I can get a list of BluetoothLE devices using:
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
Connecting to a device seems to work as well. I use:
BluetoothLEDevice btDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
Next, I want to read the data that this device is sending. I understand I need to collect the services and characteristics next before I can read this data. But for some reason I can't await the services. I get an error using this:var gattservices = await btDevice.GetGattServicesAsync();
The error reads:
Unable to cast object of type 'Windows.Devices.Bluetooth.BluetoothLEDevice' to type 'Windows.Devices.Bluetooth.IBluetoothLEDevice3'
Am I using the wrong methods to get my results?
Any help will be appreciated!
I have finally found how I can get all services and the characteristics per service. By creating a GattDevice I can get the services with GattDevice.GattServices.
When I found the correct GattDeviceService, I can get the Characteristics with:
GattService s = new GattService(GattDeviceService)
GattCharacteristic.GetCharacteristics(s)
Related
I am using Lecia Disto e7100i which basically measures distance and area using laser. This device has bluetooth and can be paired with windows.
I am trying to develop an wpf app that reads the mesaured data using c#
There is no sdk that comes along with the device.
I have tried to use 32feet.Net but since there is no proper documentation I don't know where to start.
Is there any way that I can do to solve my problem?
This is not a full response, instead its more of a guideline on how to resolve your issue:
Pair the device with your Computer
Run the included software that displays the data somehow
Use WireShark to analyze the traffic
see if it is a standard protocol type or something custom
understand the protocol and reimplement it using c# and BluetoothSockets
To get started, you can try:
var client = new BluetoothClient();
// Select the bluetooth device
var dlg = new SelectBluetoothDeviceDialog();
DialogResult result = dlg.ShowDialog(this);
if (result != DialogResult.OK)
{
return;
}
BluetoothDeviceInfo device = dlg.SelectedDevice;
BluetoothAddress addr = device.DeviceAddress;
Console.WriteLine(device.DeviceName);
BluetoothSecurity.PairRequest(addr, "PIN"); // set the pin here or take user input
device.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
Thread.Sleep(100); // Precautionary
if (device.InstalledServices.Length == 0)
{
// handle appropriately
}
client.Connect(addr, BluetoothService.HumanInterfaceDevice);
Also make sure that
Device appears in "Bluetooth devices" in the "Control panel".
Device is HID or change code accordingly.
Hope it helps. Cheers!
Try this demo project, and the following articles after that one.
Try to follow this tutorial
Here you can see a direct answer by the mantainer of 32feet, with which you can get in touch
Check also this answer
I'm attempting to get the characteristics of a custom BLE service. I have a NETStandard class library, making use of NETCore build 17134 for Bluetooth communication. This library is then used in a WPF application (.NET Framework 4.7.1.) I'm able to connect to my BLE peripheral, as well as read the generic service that includes Hardware Revision, etc. However, when it then goes to get the characteristics of my custom service, the status reads AccessDenied and the array of characteristics is empty. Any help would be greatly appreciated.
The same code works when it's purely UWP. However, I have no way to set Bluetooth permissions in the desktop app as I can in UWP. I've attempted running as administrator and performing the workaround using an AppID/registry entry. It didn't seem to work, but perhaps I simply did something wrong.
Is this a known issue? I've read there's been some regression since the original Creator's Update (15xxx) but the threads all seem about a year old.
protected async override Task<IList<ICharacteristic>> GetCharacteristicsNativeAsync()
{
var accessRequestResponse = await _nativeService.RequestAccessAsync();
// Returns Allowed
if (accessRequestResponse != Windows.Devices.Enumeration.DeviceAccessStatus.Allowed)
{
throw new Exception("Access to service " + _nativeService.Uuid.ToString() + " was disallowed w/ response: " + accessRequestResponse);
}
var allCharacteristics = await _nativeService.GetCharacteristicsAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);
// Status: AccessDenied
var status = allCharacteristics.Status;
// No error
var err = allCharacteristics.ProtocolError;
var nativeChars = allCharacteristics.Characteristics;
var charList = new List<ICharacteristic>();
foreach (var nativeChar in nativeChars)
{
var characteristic = new Characteristic(nativeChar, this);
charList.Add(characteristic);
}
return charList;
}
Any help would be greatly appreciated!
I am developing a simple app that need to send and receive some data from azure.
First of all, I have worked with a simulated device(and console app). I have configured my azure portal to work with the this data and everything works well.
At the same time, I checked my sensor with unit-tests and it works fine too.
Now, I want to send some data from my sensors to azure(with Universal App). I tried to work with this link:
https://blogs.windows.com/buildingapps/2016/03/03/connect-your-windows-app-to-azure-iot-hub-with-visual-studio/#BgxLrRq1bXolCitM.97
I choose the device that I worked with in the simulated device and got an error of "unknown host" for the client connect.
Do I need to register my raspberry pi as a device before? How I can send a simple string from known universal app (i.e: https://developer.microsoft.com/en-us/windows/iot/samples/helloblinky ) to azure?
I am working with Windows 10 IOT, c#
Thanks!
Update:
I tried to do all what you suggested without success.
Relavant code:
public static async Task SendDeviceToCloudMessageAsync()
{
CreateClient();
var currentTemperature = 20 /*getCurrentTemperature()*/;
var currentHumidity = 20/*getCurrentHumidity()*/;
var telemetryDataPoint = new
{
deviceId = DeviceId,
plantID = 7,
temperature = currentTemperature,
humidity = currentHumidity,
userId = 1
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");
Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
await deviceClient.SendEventAsync(message);
}
I don't know how to validate the "sharedAccessKey" on connectionString var
Error(on await deviceClient.SendEventAsync(message) line):
Exception thrown: 'System.Exception' in System.Private.CoreLib.ni.dll
No such host is known. (Exception from HRESULT: 0x80072AF9)
You will need to do two things here.
First up, connect your device. Details here - https://developer.microsoft.com/en-us/windows/iot/docs/ConnectDeviceToCloud
Second, connect your app. - https://developer.microsoft.com/en-us/windows/iot/docs/ConnectAppToCloud
If you run into issues when doing the above two, then, you will be able to ask more specific questions.
I'm trying to connect to a device (SecuGen Hamster Pro 20) through Windows.Devices.Usb APIs using Universal Windows App for PC only (no phones)(WinRT).
The device is a fingerprint scanner.
I've done all the steps found online to do that:
I've looked for all devices using:
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync();
This returns about 1400 devices. After some filteration using:
var resultList = myDevices.Where(s => s.Name.ToLower().Contains("secu")).ToList<DeviceInformation>();
resultList contains 3 devices in my machine (I've tried it on other machine and found 10 results on some).
I didn't use the overload for finding devices DeviceInformation.FindAllAsync(String aqsFilter) because it returns 0 results althought I'm sure I've done it right (used correct VID & PID)
The problem here is when I try to create a UsbDevice object from any of the 3 results using:
UsbDevice device = await UsbDevice.FromIdAsync(resultList[0].Id);
The return value is null, I've tried all of them (resultList[0] , resultList[1] , resultList[2]) with no luck.
I configured the capabilities using:
<DeviceCapability Name="usb">
<Device Id="vidpid:1162 2200">
<Function Type="name:vendorSpecific"/>
</Device>
</DeviceCapability>
I also tried to create a UsbDevice object from any of the 1400 devices returned from DeviceInformation.FindAllAsync() but all returned null and even some throw an exception that says the system cannot find the file specified 0x80070002
I tried to read DeviceAccessInformation for the device it returned DeviceAccessStatus.Unspecified
Anyone can lead me to what am I missing here?
You have to use UsbDevice.GetDeviceSelector and then use the selector when searching for the device. If that returns nothing, then the device isn't properly 'configured' to use the WinUSB.sys driver. (And from what I understand, it must use that driver to be used with the usbdevice class).
If you manually told it to use that driver in the device manager, then, in theory, you still have to change a key with regedit before that works (Note: I did that and it still wouldn't work). I found a solution that solved it here:
http://www.lewisbenge.net/2013/09/20/integrating-windows-8-1-with-owi-535-robotic-arm/
Basically, you have to install the driver using an inf file. use the one linked on that site and replace the NTamd64 with NTarm depending on the target platform
Firstly, try to narrow down your search by vendor and product Id
This method will help you do that:
public static async Task<List<wde.DeviceInformation>> GetDevicesByProductAndVendorAsync(int vendorId, int productId)
{
return ((IEnumerable<wde.DeviceInformation>)await wde.DeviceInformation.FindAllAsync($"System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True AND System.DeviceInterface.Hid.VendorId:={vendorId} AND System.DeviceInterface.Hid.ProductId:={productId} ").AsTask()).ToList();
}
https://github.com/MelbourneDeveloper/Hid.Net/blob/c69e3368343e59e51e8818c87dbea00e6ccfecae/Hid.Net.UWP/UWPHelpers.cs#L11
You will be able to get a list of connected devices from that. You should then be able to connect with FromIdAsync.
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.