Detecting bluetooth signal strength from RSSI on Windows - c#

I'm trying to understand how I might access the RSSI of a Bluetooth (not LE) connection in either C# or C++ on Windows.
My understanding is that there is no straightforward "GetRSSI()" type command but is there any indirect way to access it?
Everything I've found so far seems to be aimed at LE connections.
Edit:
I've had a look into AEPs and tried to get the SignalStrength AEP from a connected BT device.
foreach (var key in deviceInformation.Properties.Keys)
{
Debug.WriteLine($"{key}: {deviceInformation.Properties.GetValueOrDefault(key)}");
}
Gives:
System.ItemNameDisplay: <ommitted>
System.Devices.DeviceInstanceId:
System.Devices.Icon: C:\Windows\System32\DDORes.dll,-2001
System.Devices.GlyphIcon: C:\Windows\System32\DDORes.dll,-3001
System.Devices.InterfaceEnabled:
System.Devices.IsDefault:
System.Devices.PhysicalDeviceLocation:
System.Devices.ContainerId:
With the item name omitted by me.
So it looks like there are no AEPs, unless I'm missing something?

I know this is late, but I just started a new project where I also want information about the SignalStrength for Bluetooth (not LE) devices.
#Mike-Petrichenko was giving you some good hints. After following his advice of searching for "System.Devices.Aep.SignalStrength" I found this post
After going throw the OPs Code and debugging a little, I came up with this solution:
private const string SignalStrengthProperty = "System.Devices.Aep.SignalStrength";
var additionalProperties = new[] { SignalStrengthProperty };
DeviceWatcher mWatcher = DeviceInformation.CreateWatcher(BluetoothDevice.GetDeviceSelector(), additionalProperties);
var rssi = Convert.ToInt16(deviceInformation.Properties[SignalStrengthProperty]);

Related

How to find USB HID DevicePath?

I've been working on USB HID Device in embedded system and C# for a while. I decided to use USBHid library in C#. I got the ideal result with this library. But I have a problem. While defining the USB in the USBHid library, the following code is sufficient in the project of the library that I found on the internet.
public UsbHidDevice Device;
Device = new UsbHidDevice(vvvv,pppp);
However, when I use the same library, it asks me for an expression in the following format.
public UsbHidDevice Device; string vidandpid =
"\\hid#vid_0000&pid_0000&mi_00#a&0&000000000&1&0000#{eeof37d0-1963-47k4-aa41-74476db7uf49}";
Device = new UsbHidDevice(vidandpid);
I adapted this format for my own HID device, but without success. How should this string expression be? I am open to your views. Thank you from now.
How to find USB HID DevicePath?
I gave up on USBHID library and found solution with HidLibrary library. As far as I understand, HidLibrary falls short on some issues.
Here I am sharing the C# code that I linked with HidLibrary. Thank you for all the replies.
device = HidDevices.Enumerate(VendorID, ProductID).FirstOrDefault();
if (device != null)
{
device.OpenDevice();
device.Inserted += DeviceAttachedHandler;
device.Removed += DeviceRemovedHandler;
device.MonitorDeviceEvents = true;
device.ReadReport(myfunction);
}
else { RtBox_Feedback.AppendText("NOT DEVICE!"); }
\\hid#vid_0000&pid_0000&mi_00#a&0&000000000&1&0000#{eeof37d0-1963-47k4-aa41-74476db7uf49} - is a device interface for the {eeof37d0-1963-47k4-aa41-74476db7uf49} interface. It is almost always unique and semi-random for each device. It also may change if yore put device in another USB slot. This string may be used as path to open this "file" with CreateFile Win32 API and talk with device by means of interface-specific IOCTLs. More info here.
For HID devices Windows have another device interface GUID - GUID_DEVINTERFACE_HID - {4D1E55B2-F16F-11CF-88CB-001111000030}
You can use CM_Get_Device_Interface_ListW or SetupDiGetClassDevs/SetupDiEnumDeviceInterfaces/SetupDiGetDeviceInterfaceDetail APIs to enumerate device interfaces by interface GUID or by device Instance ID.
Mentioned "USBHid library in C#" may already have code that doing such enumeration and filtering by HID deivce VID/PID but I cannot say it for sure since you haven't added link to the code of this library. :)

using an Audio Endpoint other than 'DefaultAudioEndpoint' in C#

This program is an audio visualizer for an rgb keyboard that listens to windows' default audio device. My audio setup is a bit more involved, and I use way more than just the default audio device. For instance, when I play music from Winamp it goes through the device Auxillary 1 (Synchronous Audio Router) instead of Desktop Input (Synchronous Audio Router) which I have set as Default. I'd like to be able change the device that the program listens to for the visualization.
I found in the source where the audio device is declared; Lines 32-36 in CSCoreAudioInput.cs:
public void Initialize()
{
MMDevice captureDevice = MMDeviceEnumerator.DefaultAudioEndpoint(DataFlow.Render, Role.Console);
WaveFormat deviceFormat = captureDevice.DeviceFormat;
_audioEndpointVolume = AudioEndpointVolume.FromDevice(captureDevice);
}
The way that I understand it from the documentation, the section MMDeviceEnumerator.DefaultAudioEndpoint(DataFlow.Render, Role.Console) is where Windows gives the application my default IMMEndpoint "Desktop Input."
How would I go about changing DefaultAudioEndpoint?
Further Reading shows a few ways to get an IMMDevice, with DefaultAudioEnpoint being one of them. It seems to me that I'd have to enumerate the devices, and then separate out Auxillary 1 (Synchronous Audio Router) using PKEY_Device_FriendlyName. That's a bit much for me, as I have little to no C# experience. Is there an easier way to go about choosing a different endpoint? Am I on the right track? or am I missing the mark completely?
Also, what is the difference between MMDevice and IMMDevice? The source only seems to use MMDevice while all the Microsoft documentation references IMMDevice.
Thanks.
I DID IT!
I've found why the program uses MMDevice rather than IMMDevice. The developer has chosen to use the CSCore Library rather than Windows' own Core Audio API.
From continued reading of the CSCore MMDeviceEnumerator Documentation, it looks like I'll have to make a separate program that outputs all endpoints and their respective Endpoint ID Strings. Then I can substitute the DefaultAudioEndpoint method with the GetDevice(String id) method, where String id is the ID of whichever Endpoint I chose from the separate program.
To find the the Endpoint I wanted, I wrote this short program to find all the info I wanted:
static void Main(string[] args)
{
MMDeviceEnumerator enumerator = new MMDeviceEnumerator();
MMDeviceCollection collection = enumerator.EnumAudioEndpoints(DataFlow.Render,DeviceState.Active);
Console.WriteLine($"\nNumber of active Devices: {collection.GetCount()}");
int i = 0;
foreach (MMDevice device in collection){
Console.WriteLine($"\n{i} Friendly name: {device.FriendlyName}");
Console.WriteLine($"Endpoint ID: {device.DeviceID}");
i++;
}
Console.ReadKey();
}
This showed me that the Endpoint I wanted was item number 3 (2 in an array) on my list, and instead of using GetDevice(String id) I used ItemAt(int deviceIndex).
MMDeviceEnumerator enumerator = new MMDeviceEnumerator();
MMDeviceCollection collection = enumerator.EnumAudioEndpoints(DataFlow.Render,DeviceState.Active);
MMDevice captureDevice = collection.ItemAt(2);
However in this case, the program was not using captureDevice to bring in the audio data. These were the magic lines:
_capture = new WasapiLoopbackCapture(100, new WaveFormat(deviceFormat.SampleRate, deviceFormat.BitsPerSample, i));
_capture.Initialize();
I found that WasapiLoopbackCapture uses Windows' default device unless changed, and the code was using DefaultAudioEndpoint to get the properties of the default device. So I added
_capture.Device = captureDevice;
//before
_capture.Initialize();
And now the program properly pulls the audio data off of my non-default audio endpoint.
I had been asked to solve a similar type of problem this week. Although there are a few librarys to do this I was specifically asked to do this for "non ish" programmers so I developed this in PowerShell.
Powershell default audio device changer - Github
Maybe you can alter it to your needs.

Disable specific USB Storage Device C#

I am working on a project that needs to enable/disable specific USB storage devices.
My app gets all storage USB DeviceIDs, and depending on saved settings then needs to allow the device or not. I have used the code from this previous question for the enable/disable, and call it like so:
DisableHardware.DisableDevice(n => n.ToUpperInvariant().Contains(VidPid), true);
with string VidPid = "VID_8564&PID_1000";.
I have stepped through the code, it all works perfectly (as far as I can tell) until the SetupDIChangeState call, which then returns -536870389 (E000020B as hex) as error code (from Marshall.GetLastWin32Error()).
Apparently this refers to either 1) the device not being present (which as far as I understand is not the case here, as all other calls in this class work fine, and I get `VidPid' from
private static List<WMUBClasses.USBDeviceInfo> GetUSBDevices()
{
try
{
List<WMUBClasses.USBDeviceInfo> tList = new List<WMUBClasses.USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_USBHub"))
{
collection = searcher.Get();
}
foreach (var device in collection)
{
if (!device.GetPropertyValue("Description").ToString().Contains("Storage"))
{
continue;
}
tList.Add(new WMUBClasses.USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
return tList;
}
catch (Exception ex)
{
return null;
}
}
or 2) an incorrect build platform, but I have tried all the different combinations (Any CPU, Mixed Platforms, x86 and x64), they all return the same result.
I have also looked at this which is another approach to my problem (by creating and using a kernel mode filter driver), it just seems like killing a fly with a wrecking ball. To be honest I have no clue of how to go about using this (for someone that hasn't done any driver development it looks super intimidating, especially after having read some of the available documentation.)
Should I (A) keep using the SetupDi API calls to achieve my goal and if so, can anyone see what is wrong with the code or how I am using it? If not (A), should I (B) use the filter driver approach instead and if so, any pointers?
As stated in the header, I want to disable specific USB storage devices, so as far as I understand, this precludes using the Registry to disable ALL USB storage devices. So if neither of the above, does anyone have any other direction I should be looking at instead?

Find USBportname with c#

For a project i have to communicate with a netduino,
So i use serial communication to communicate with the netduino.
But here's my problem
I cannot find my Usb portname, i use this small piece of code to find the port names.
private void GetPortNames()
{
string[] ports = SerialPort.GetPortNames();
ComportListbox.DataSource = ports;
}
It doesnt show the usb port names.
What am i doeing wrong, or how can i fix this issue.
EDIT
Question edited:
Can i see the usbportname from my usbport where the NETduino is attached to. So i hope to see COM10 for example. I looked in the system managment and saw that the usb is called Port_#0001.Hub_#0001. How can i open this port.
If ComportListbox has an "add" method, why not just use that with a for loop.
foreach ( string portName in ports )
{
ComportListbox.Items.Add( portName );
}
If not, let me know and I will delete this answer.
Otherwise you may have to use a BindingList<string>. see: Binding List<T> to DataGridView in WinForm
Or you might even have to create an object that contains a string property for the binding name.

HASP HL working demo needed for C#

Okay. Well, I know this question has a good chance of being closed within the first 10 minutes, but I am going to ask it anyways for I have spent almost day and an half trying to find a solution. Still, I can't figure this one out. There is not much info on this on the Internet not even on the HASP (safenet) website although they have demos.
I have a HASP HL USB dongle. I try to convert their demo and test run it but for the life of me I simply can't get it to login even. It keeps raising Aladdin.HASP.HaspStatus.HaspDotNetDllBroken exception.
However, if I run the C version of their demo, it works perfectly.
Here is the Csharp version of my code:
Aladdin.HASP;
HASP myHasp = new HASP();
var thestatus = myHasp.Login(vender_code);
myHasp.Logout;
I would like to login to USB HASP and get its HaspID and the settings in its memory.
Thanks in advance,
It might be that you aren't having all dependencies for the HASP runtime. I'm packing with the app:
hasp_windows_NNNNN.dll (NNNNN = your number)
hasp_net_windows.dll
MSVCR71.DLL (added manually)
msvc runtime 80
One runtime library is required by HASP and it doesn't tell you which one unless you put it in the DEPENDS.EXE utility (you probably have you on your Visual Studio installation).
To log in (and read some bytes):
byte[] key = new byte[16];
HaspFeature feature = HaspFeature.FromFeature(4);
string vendorCode = "your vendor string, get it from your tools";
Hasp hasp = new Hasp(feature);
HaspStatus status = hasp.Login(vendorCode);
if (HaspStatus.StatusOk != status)
{
// no license to run
return false;
}
else
{
// read some memory here
HaspFile mem = hasp.GetFile(HaspFileId.ReadOnly);
mem.Read(key, 0, 16);
status = hasp.Logout();
if (HaspStatus.StatusOk != status)
{
//handle error
}
}
Hope it helps. My HASPed software works like a charm. BTW, wasn't able to put envelope around .NET app under no combination of settings.

Categories

Resources