Windows IoT Raspberry Pi 3 C# USB DeviceWatcher - c#

I manage to enumerate my USB device as below. How can I add the enumerateDevices into DeviceWatcher?
I have referred to the following examples but still not getting any progress.
The watcher did trigger once during the startup subsequently any changes in my usb devices doesn't show anything.
[How to get notifications if devices are added, removed, or changed (XAML)][1]
[Device Enumeration Samples][2] Any idea how to constantly monitoring the changes on my USB port to prompt if any of the USB device has been removed or connected?
private void StartWatcher()
{
usbStorageWatcher = DeviceInformation.CreateWatcher(DeviceClass.PortableStorageDevice);
audioCaptureWatcher = DeviceInformation.CreateWatcher(DeviceClass.AudioCapture);
audioRenderWatcher = DeviceInformation.CreateWatcher(DeviceClass.AudioRender);
usbStorageWatcherAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, async () =>
{
var usbDevices = await DeviceInformation.FindAllAsync(DeviceClass.PortableStorageDevice);
if (usbDevices.Count > 0)
{
for (var i = 0; i < usbDevices.Count; i++)
{
usbDeviceList.Add(usbDevices[i]);
}
usbList.SelectedItem = usbDevices[0];
usbDeviceCount.Text = usbDevices.Count.ToString();
GeneralMessage.Text = String.Format("{0} USB Storage found.", usbDevices.Count);
}
});
});
usbStorageWatcher.Added += usbStorageWatcherAdded;
usbStorageWatcherRemoved = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(async (watcher, deviceInfoUpdate) =>
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, async () =>
{
var usbDevices = await DeviceInformation.FindAllAsync(DeviceClass.PortableStorageDevice);
if (usbDevices.Count > 0)
{
for (var i = 0; i < usbDevices.Count; i++)
{
usbDeviceList.Add(usbDevices[i]);
}
usbList.SelectedItem = usbDevices[0];
usbDeviceCount.Text = usbDevices.Count.ToString();
GeneralMessage.Text = String.Format("{0} USB Storage found.", usbDevices.Count);
}
});
});
usbStorageWatcher.Removed += usbStorageWatcherRemoved;

Related

Connect to a bluetooth printer, and print something

The library i'm using is called Plugin.BLE. It doesn't have good documentation, and I'm just guessing.
First I scan for connected devices, then I connect to the bluetooth printer which is called "MTP-2" then I get it's service. From that service I get the characteristics, and I write data into it, but it doesn't actually do anything.
private async void Print(object sender, EventArgs e)
{
var adapter = CrossBluetoothLE.Current.Adapter;
var devices = adapter.GetSystemConnectedOrPairedDevices();
foreach (var device in devices)
{
var name = device.Name;
if (name == "MTP-2")
{
var cts = new CancellationToken();
var guid = device.Id;
await adapter.ConnectToDeviceAsync(device, new ConnectParameters(true, true), cts);
var services = await device.GetServicesAsync();
foreach (var _service in services)
{
var characteristics = await _service.GetCharacteristicsAsync();
foreach (var characteristic in characteristics)
{
var read = characteristic.CanRead;
var write = characteristic.CanWrite;
var update = characteristic.CanUpdate;
if (read && write && update)
{
await characteristic.StartUpdatesAsync();
var content = "Hi there.";
var data = System.Text.Encoding.ASCII.GetBytes(content);
await characteristic.WriteAsync(data);
await characteristic.StopUpdatesAsync();
return;
}
}
}
}
}
}
I think you have such options:
send a special character to initiate printing. I think the printer should have some documentation for this.
call a special method from the api.

Not able to detect Hard disk drive in C# application

I have written an api to get all external storage drives connected to my computer. But i am not able to detect hard disk drives.
private async Task GetAllDrivesConnected()
{
await Task.Run(() =>
{
var drives = DriveInfo.GetDrives();
lock (this.myUsbDriveListLock)
{
foreach (var aDrive in drives .Where(theDrive => theDrive.DriveType == DriveType.Removable && theDrive.IsReady))
{
DriveLetter_Array.Add(aDrive.Name);
}
}
string LatestPath = DriveLetter_Array.LastOrDefault();
this.SetCurrentUsbPath(LatestPath);
var DeviceMessageEventArgs = new DeviceMessageEventArgs { Drive = LatestPath, UsbAdded = true };
FireEventAddPathRemovePath(DeviceMessageEventArgs);
});
}
I am making use of WML queries to listen to device inserted event:
private async Task DeviceNotification()
{
await Task.Run(() =>
{
var InsertQuery = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");
myInsertionWatcher = new ManagementEventWatcher(InsertQuery);
myInsertionWatcher.EventArrived += this.DeviceInsertedEvent;
myInsertionWatcher.Start();
var RemoveQuery = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3");
myRemovalWatcher = new ManagementEventWatcher(RemoveQuery);
myRemovalWatcher.EventArrived += this.DeviceRemovedEvent;
myRemovalWatcher.Start();
});
}
Please try adding the wait for next event method after start
myInsertionWatcher.WaitForNextEvent();
It's not clear from your comment if you actually checked for other DriveTypes. If I run the following after having connected an external hard drive I get the output from the image:
DriveInfo.GetDrives().Where(d => d.IsReady)
As you can see it has DriveType Fixed, even if it's connected through a USB port.
You may want to change your foreach loop:
foreach (var aDrive in drives .Where(theDrive => theDrive.IsReady))
{
DriveLetter_Array.Add(aDrive.Name);
}
If you want to only see external hard drives, you may want to take a look at this answer

Best way to create new Event Hub Namespace for every ten Event Hubs

Since I am only allowed 10 event hubs per namespace, I am looking for a good algorithm to create a new namespace for every ten event hubs in the list I have.
NOTE: The list of event hub namespaces are being passed in to the method.
var eventHubResources = GetRequiredService<List<EventHubResource>>();
foreach (var eventHubResource in eventHubResources)
{
eventHubResource.ResourceGroup = resourceGroup;
MyNamespace.IEventHub eventHub = new EventHub(logger);
if (eventHubResource.CaptureSettings == null)
{
if (eventHubResources.IndexOf(eventHubResource) <= 9)
{
await eventHub.CreateEventHubAsync(azure, eventHubNamespace[0], eventHubResource, null);
}
if ((eventHubResources.IndexOf(eventHubResource) > 9) && (eventHubResources.IndexOf(eventHubResource) <= 19))
{
await eventHub.CreateEventHubAsync(azure, eventHubNamespace[1], eventHubResource, null);
}
// and so on....
}
else
{
await eventHub.CreateEventHubAsync(azure, eventHubNamespace, eventHubResource, storageAccount);
}
}
What is a better way to achieve this, compared to what I have above?
I didn't test the code but you can get the idea.
public static async Task CreateNamespaces(List<string> eventhubNames, ServiceClientCredentials creds) {
int totalEventHubsInNamespace = 0;
var ehClient = new EventHubManagementClient(creds)
{
SubscriptionId = "<my subscription id>"
};
foreach (var ehName in eventhubNames)
{
if (totalEventHubsInNamespace == 0)
{
var namespaceParams = new EHNamespace()
{
Location = "<datacenter location>"
};
// Create namespace
var namespaceName = "<populate some unique namespace>";
Console.WriteLine($"Creating namespace... {namespaceName}");
await ehClient.Namespaces.CreateOrUpdateAsync(resourceGroupName, namespaceName, namespaceParams);
Console.WriteLine("Created namespace successfully.");
}
// Create eventhub.
Console.WriteLine($"Creating eventhub {ehName}");
var ehParams = new Eventhub() { }; // Customize you eventhub here if you need.
await ehClient.EventHubs.CreateOrUpdateAsync(resourceGroupName, namespaceName, ehName, ehParams);
Console.WriteLine("Created Event Hub successfully.");
totalEventHubsInNamespace++;
if (totalEventHubsInNamespace >= 10)
{
totalEventHubsInNamespace = 0;
}
}
}

Finding Bluetooth Mac address in Windows10 UWP without pairing

I'm trying to write an app that reads all MAC addresses around on Windows 10 IoT. These lines of code is returning all paired devices even if they aren't turn on.
var selector = BluetoothDevice.GetDeviceSelector();
var devices = await DeviceInformation.FindAllAsync(selector);
listBox.Items.Add(devices.Count);
foreach (var device in devices)
{
listBox.Items.Add(device.Id);
}
And I also found this line of code
await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
This returning null though. Is there any way to scan for all MAC addresses in a Windows 10 universal app?
You are very close to finding the answer of your question. You might try getting a BluetoothDevice instance from the DeviceId property. You will then be able to get all the specific Bluetooth information including the Bluetooth address
var selector = BluetoothDevice.GetDeviceSelector();
var devices = await DeviceInformation.FindAllAsync(selector);
foreach (var device in devices)
{
var bluetoothDevice = await BluetoothDevice.FromIdAsync(device.Id);
if (bluetoothDevice != null)
{
Debug.WriteLine(bluetoothDevice.BluetoothAddress);
}
Debug.WriteLine(device.Id);
foreach(var property in device.Properties)
{
Debug.WriteLine(" " + property.Key + " " + property.Value);
}
}
There is a new approach using BluetoothLEAdvertisementWatcher to scan for all Bluetooth LE device around.
Here is a piece of code I use in my project:
var advertisementWatcher = new BluetoothLEAdvertisementWatcher()
{
SignalStrengthFilter.InRangeThresholdInDBm = -100,
SignalStrengthFilter.OutOfRangeThresholdInDBm = -102,
SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000)
};
advertisementWatcher.Received += AdvertisementWatcher_Received;
advertisementWatcher.Stopped += AdvertisementWatcher_Stopped;
advertisementWatcher.Start();
and later
advertisementWatcher.Stop();
advertisementWatcher.Received -= AdvertisementWatcher_Received;
advertisementWatcher.Stopped -= AdvertisementWatcher_Stopped;
private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
//MessAgeChanged(MsgType.NotifyTxt, "FR_NAME:"+ eventArgs.Advertisement.LocalName + "BT_ADDR: " + eventArgs.BluetoothAddress);
string sDevicename = setup.Default.BLEName.Text;
BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).Completed = async (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
if (asyncInfo.GetResults() == null)
{
if (!FailMsg)
{
MessAgeChanged(MsgType.NotifyTxt, "None");
}
}
else
{
BluetoothLEDevice currentDevice = asyncInfo.GetResults();
Boolean contain = false;
foreach (BluetoothLEDevice device in DeviceList.ToArray())/
{
if (device.DeviceId == currentDevice.DeviceId)
{
contain = true;
}
}
if (!contain)
{
byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
Array.Reverse(_Bytes1);
// The received signal strength indicator (RSSI)
double rssi = eventArgs.RawSignalStrengthInDBm;
DeviceList.Add(currentDevice);
MessAgeChanged(MsgType.NotifyTxt, currentDevice.Name + " " + BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower() + " " + rssi);
DeviceWatcherChanged(MsgType.BleDevice, currentDevice);
}
}
}
};
}

Windows Phone Push Notification By Azure Notification Hub

I am android app developer .Now, I am developing app for windows phone . I am integrating push notification in windows phone first time by Azure notification Hub. I want help for notification Hub. How to integrate? How to send notification to selected device not to all?
I was integrated notification but after some time notification is stop. I have done with many notification hub credentials. Now notification is coming.
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
StorageFile MyDBFile = null;
try
{
// Read the db file from DB path
MyDBFile = await StorageFile.GetFileFromPathAsync(DB_PATH);
}
catch (FileNotFoundException)
{
if (MyDBFile == null)
{
// Copy file from installation folder to local folder.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(DbConst.DATABASE, UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile(DB_PATH))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
}
var channel = HttpNotificationChannel.Find("MyPushChannel");
if (channel == null)
{
channel = new HttpNotificationChannel("MyPushChannel");
channel.Open();
channel.BindToShellToast();
}
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
//var hub = new NotificationHub("<hub name>", "<connection string>");
var hub = new NotificationHub("mnokhgjhjhjbohkjkl", "Endpoint=sb://connect-hub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=RM6jjnbjnbjAnjhttD4yxqnknknklmkmnkkmkkkmmkbnl5rSk=");
Registration x= await hub.RegisterNativeAsync(args.ChannelUri.ToString());
//mChennelURI = x.ChannelUri;
Debug.WriteLine("Chennel URI: " + x.ChannelUri);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
System.Diagnostics.Debug.WriteLine(args.ChannelUri.ToString());
});
});
channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(async (o,args) =>
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", args.ErrorType, args.Message, args.ErrorCode,args.ErrorAdditionalData));
});
});
// Handle the event that is raised when a toast is received.
channel.ShellToastNotificationReceived +=new EventHandler<NotificationEventArgs>((o, args) =>
{
string message = "";
foreach (string key in args.Collection.Keys)
{
message += args.Collection[key] + ": ";
}
//string[] separators = { "#"};
// string[] words = message.Split(separators, StringSplitOptions.RemoveEmptyEntries);
// string type = words[0];
// string title = words[1];
// string body = words[2];
// string attach = words[3];
//string date = words[4];
//string time = words[5];
//string msdId = words[6];
//string groupIDS = words[7];
//foreach (var word in words)
//Console.WriteLine(word);
Console.WriteLine("Push notification : " + message);
Debug.WriteLine("Push notification : " + message);
Debugger.Log(1, "Push", "Push notification : " + message);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(message);
//<Temp>
// DatabaseHelperClass dbHelper = new DatabaseHelperClass();
// dbHelper.Insert(new Msg(msdId, groupIDS, type, title, body, attach, date, time, Constants.NO));
//</Temp>
});
});
}

Categories

Resources