private static async Task <string> GetRootDeviceInfoAsync(string propertyKey) { var pnp = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, RootContainer, new[] { propertyKey }); return((string)pnp.Properties[propertyKey]); }
/// <summary> /// Device Containerを列挙する. /// </summary> /// <returns>列挙されたDevice Containerを返す</returns> private static async Task <Dictionary <Guid, PnpObject> > GetDeviceContainers() { var props = new string[] { DevicePropertyHelper.SystemItemNameDisplay, DevicePropertyHelper.SystemDevicesFriendlyName, DevicePropertyHelper.SystemDevicesModelName, DevicePropertyHelper.SystemDevicesManufacturer, DevicePropertyHelper.SystemDevicesInLocalMachineContainer, DevicePropertyHelper.SystemDevicesDiscoveryMethod, DevicePropertyHelper.SystemDevicesConnected, DevicePropertyHelper.SystemDevicesIsNetworkConnected, DevicePropertyHelper.DEVPKEY_DeviceContainer_Category, DevicePropertyHelper.DEVPKEY_DeviceContainer_PrimaryCategory, }; var devContainers = await PnpObject.FindAllAsync(PnpObjectType.DeviceContainer, props); var idContainerDict = new Dictionary <Guid, PnpObject>(devContainers.Count); foreach (var container in devContainers) { var guid = Guid.Parse(container.Id); idContainerDict.Add(guid, container); } return(idContainerDict); }
internal static async Task <string> GetOperatingSystemVersionAsync() { if (_operatingSystemVersion == null) { try { // There is no good place to get this so we're going to use the most popular // Microsoft driver version number from the device tree. var requestedProperties = new[] { DeviceDriverVersionKey, DeviceDriverProviderKey }; var microsoftVersionedDevices = (await PnpObject.FindAllAsync(PnpObjectType.Device, requestedProperties, RootQuery)) .Select(d => new { Provider = (string)d.Properties.GetValueOrDefault(DeviceDriverProviderKey), Version = (string)d.Properties.GetValueOrDefault(DeviceDriverVersionKey) }) .Where(d => d.Provider == "Microsoft" && d.Version != null) .ToList(); var versionNumbers = microsoftVersionedDevices .GroupBy(d => d.Version.Substring(0, d.Version.IndexOf('.', d.Version.IndexOf('.') + 1))) .OrderByDescending(d => d.Count()) .ToList(); var confidence = (versionNumbers[0].Count() * 100 / microsoftVersionedDevices.Count); _operatingSystemVersion = versionNumbers.Count > 0 ? versionNumbers[0].Key : ""; } catch { _operatingSystemVersion = "Unknown"; } } return(_operatingSystemVersion); }
/// <summary> /// デバイスのPnpObjectをツリーの情報を保持するDeviceItemとしてDictionaryに登録する. /// </summary> /// <param name="device">デバイスのPnpObject</param> /// <param name="dict">登録先</param> /// <returns>登録されたデバイスのDeviceItemを返す</returns> private static TreeNode <DeviceItem> RegisterDeviceToDeviceItemDictionary(PnpObject device, Dictionary <string, TreeNode <DeviceItem> > dict) { System.Diagnostics.Debug.Assert(device != null); System.Diagnostics.Debug.Assert(dict != null); TreeNode <DeviceItem> devItem; if (dict.ContainsKey(device.Id)) { System.Diagnostics.Debug.Assert(dict[device.Id].Data == null); System.Diagnostics.Debug.Assert(dict[device.Id].Parent != null); devItem = dict[device.Id]; devItem.Data = new DeviceItem() { Device = device }; } else { devItem = new TreeNode <DeviceItem> { Data = new DeviceItem() { Device = device } }; dict.Add(device.Id, devItem); } return(devItem); }
/// <summary> /// Check if a printer is associated with the current application, if it is, add its interfaceId to a list of associated interfaceIds. /// /// For each different app, it will have a different correctPackageFamilyName. /// Look in the Visual Studio packagemanifest editor to see what it is for your app. /// </summary> /// <param name="deviceInfo">The deviceInformation of the printer.</param> async void FindAssociation(DeviceInformation deviceInfo, string containerId) { // Specifically telling CreateFromIdAsync to retrieve the AppPackageFamilyName. string packageFamilyName = "System.Devices.AppPackageFamilyName"; string[] containerPropertiesToGet = new string[] { packageFamilyName }; // CreateFromIdAsync needs braces on the containerId string. string containerIdwithBraces = "{" + containerId + "}"; // Asynchoronously getting the container information of the printer. PnpObject containerInfo = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, containerIdwithBraces, containerPropertiesToGet); // Printers could be associated with other device apps, only the ones with package family name // matching this app's is associated with this app. The packageFamilyName for this app will be found in this app's packagemanifest string appPackageFamilyName = "Microsoft.SDKSamples.DeviceAppForPrinters.CS_8wekyb3d8bbwe"; var prop = containerInfo.Properties; // If the packageFamilyName of the printer container matches the one for this app, the printer is associated with this app. string[] packageFamilyNameList = (string[])prop[packageFamilyName]; if (packageFamilyNameList != null) { for (int j = 0; j < packageFamilyNameList.Length; j++) { if (packageFamilyNameList[j].Equals(appPackageFamilyName)) { AddToList(deviceInfo); } } } }
/// <summary> /// Register to be notified when a connection is established to the Bluetooth device. /// </summary> private void StartDeviceConnectionWatcher() { this.watcher = PnpObject.CreateWatcher(PnpObjectType.DeviceContainer, new string[] { "System.Devices.Connected" }, String.Empty); this.watcher.Updated += (PnpObjectWatcher sender, PnpObjectUpdate args) => { var connectedProperty = args.Properties["System.Devices.Connected"]; bool isConnected = false; if ((deviceContainerId == args.Id) && Boolean.TryParse(connectedProperty.ToString(), out isConnected) && isConnected) { this.IsServiceInitialized = true; // Once the Client Characteristic Configuration Descriptor is set, the watcher is no longer required this.watcher.Stop(); this.watcher = null; // Notifying subscribers of connection state updates if (this.DeviceConnectionUpdated != null) { this.DeviceConnectionUpdated(isConnected); } } }; this.watcher.Start(); }
/// <summary> /// Determines if a printer device container is associated with the Windows Store Device App. /// </summary> async Task <bool> IsDeviceContainerAssociatedWithAppAsync(string deviceContainerId) { // CreateFromIdAsync needs braces on the containerId string. string formattedContainerId = "{" + deviceContainerId + "}"; // Retrieve the 'package family name' property from the device container which tells string packageFamilyNamePropertyName = "System.Devices.AppPackageFamilyName"; string[] propertiesToRetrieve = new string[] { packageFamilyNamePropertyName }; // Asynchoronously retrieve the device container information. PnpObject deviceContainer = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, formattedContainerId, propertiesToRetrieve); // If the packageFamilyName of the printer container matches the one for this app, the printer is associated with this app. string[] packageFamilyNameList = (string[])deviceContainer.Properties[packageFamilyNamePropertyName]; if (packageFamilyNameList != null) { foreach (string packageFamilyName in packageFamilyNameList) { if (packageFamilyName.CompareTo(this.packageFamilyNameToMatch) == 0) { return(true); } } } return(false); }
private void StartDeviceConnectionWatcher() { this.watcher = PnpObject.CreateWatcher(PnpObjectType.DeviceContainer, new string[] { "System.Devices.Connected" }, String.Empty); this.watcher.Updated += (PnpObjectWatcher sender, PnpObjectUpdate args) => { var connectedProperty = args.Properties["System.Devices.Connected"]; bool isConnected = false; if ((deviceContainerId == args.Id) && Boolean.TryParse(connectedProperty.ToString(), out isConnected) && isConnected) { // this.watcher.Stop(); // this.watcher = null; if (true == isConnected) { if (null != this.Connected) { this.Connected(this, this); } } else { if (null != this.Disconnected) { this.Disconnected(this, this); } } } }; this.watcher.Start(); }
/// <summary> /// Attempt to find the HAL (Hardware Abstraction Layer) device for this computer. /// </summary> /// <param name="properties">Additional property names to obtain for the HAL.</param> /// <returns>PnpObject of the HAL with the additional properties populated.</returns> private static async Task <PnpObject> GetHalDevice(params string[] properties) { var actualProperties = properties.Concat(new[] { DeviceClassKey, DeviceDriverProviderKey }); var rootDevices = (await PnpObject.FindAllAsync(PnpObjectType.Device, actualProperties, RootContainerQuery)); return(rootDevices.FirstOrDefault(rootDevice => IsMicrosoftHal(rootDevice.Properties))); }
private static PnpObject GetHalDevice(params String[] properties) { String[] strArray = properties; String[] strArray1 = { "{A45C254E-DF1C-4EFD-8020-67D146A850E0},10" }; IEnumerable <String> enumerable = strArray.Concat(strArray1); try { PnpObjectCollection pnpObjectCollection = PnpObject.FindAllAsync(PnpObjectType.Device, enumerable, "System.Devices.ContainerId:=\"{00000000-0000-0000-FFFF-FFFFFFFFFFFF}\"").GetResults(); foreach (PnpObject pnpObject in pnpObjectCollection) { if (pnpObject.Properties == null || !pnpObject.Properties.Any()) { continue; } KeyValuePair <String, Object> keyValuePair = pnpObject.Properties.Last(); if (keyValuePair.Value == null || !keyValuePair.Value.ToString().Equals("4d36e966-e325-11ce-bfc1-08002be10318")) { continue; } return(pnpObject); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: " + e.Message); return(null); } return(null); }
public static string GetDeviceProperty(PnpObject device, string propertyName) { object objValue; string value = null; //foreach (var key in device.Properties.Keys) //{ // Debug.WriteLine(key); //} if (device.Properties.TryGetValue(propertyName, out objValue)) { if (objValue is string[]) { var arr = objValue as string[]; if (arr.Length > 0) { value = arr[0]; } } else if (objValue is byte[]) { value = BitConverter.ToString((byte[])objValue); } else { value = objValue?.ToString(); } } return(value); }
private async void DevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs args) { RunButton.IsEnabled = false; var device = DevicesListBox.SelectedItem as DeviceInformation; DevicesListBox.Visibility = Visibility.Collapsed; statusTextBlock.Text = "Initializing device..."; UARTService.Instance.DeviceConnectionUpdated += OnDeviceConnectionUpdated; await UARTService.Instance.InitializeServiceAsync(device); outputGrid.Visibility = Visibility.Visible; try { // Check if the device is initially connected, and display the appropriate message to the user var deviceObject = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, device.Properties["System.Devices.ContainerId"].ToString(), new string[] { "System.Devices.Connected" }); bool isConnected; if (Boolean.TryParse(deviceObject.Properties["System.Devices.Connected"].ToString(), out isConnected)) { OnDeviceConnectionUpdated(isConnected); } } catch (Exception) { statusTextBlock.Text = "Retrieving device properties failed"; } }
/// <summary> /// hdt /// </summary> /// <returns></returns> public static Task <ProcessorArchitecture> GetProcessorArchitectureAsync() { TaskAwaiter <PnpObject> awaiter = SystemInfoEstimate.GetHalDevice(new string[] { "System.ItemNameDisplay" }).GetAwaiter(); PnpObject halDevice = awaiter.GetResult(); ProcessorArchitecture arm; if (halDevice != null && halDevice.Properties["System.ItemNameDisplay"] != null) { string str = halDevice.Properties["System.ItemNameDisplay"].ToString(); if (str.Contains("x64")) { arm = ProcessorArchitecture.X64; } else if (str.Contains("ARM")) { arm = ProcessorArchitecture.Arm; } else { arm = ProcessorArchitecture.X86; } } else { arm = ProcessorArchitecture.Unknown; } return(Task.FromResult <ProcessorArchitecture>(arm)); }
public PnpDev(DeviceInformation devInfo, PnpObject pnpObject, string name, string ipAddress, string macAddress) { DevInfo = devInfo; PnpObject = pnpObject; Name = name; IpAddress = ipAddress; MacAddress = macAddress; }
/// <summary> /// Register to be notified when a connection is established to the Bluetooth device /// </summary> private void StartDeviceConnectionWatcher() { watcher = PnpObject.CreateWatcher(PnpObjectType.DeviceContainer, new string[] { "System.Devices.Connected" }, String.Empty); watcher.Updated += DeviceConnection_Updated; watcher.Start(); }
/// <summary> /// hdt /// </summary> /// <param name="propertyKey"></param> /// <returns></returns> static Task <string> GetRootDeviceInfoAsync(string propertyKey) { TaskAwaiter <PnpObject> awaiter; awaiter = WindowsRuntimeSystemExtensions.GetAwaiter <PnpObject>(PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, "{00000000-0000-0000-FFFF-FFFFFFFFFFFF}", new string[] { propertyKey })); PnpObject pnp = awaiter.GetResult(); string str = pnp.Properties[propertyKey].ToString(); return(Task.FromResult <string>(str)); }
private async Task <PnpObjectCollection> GetDevices() { string[] properties = { "System.ItemNameDisplay", "System.Devices.ContainerId" }; return(await PnpObject.FindAllAsync(PnpObjectType.Device, properties)); }
private void StartDeviceConnectionWatcher() { watcher = PnpObject.CreateWatcher(PnpObjectType.DeviceContainer, new string[] { "System.Devices.Connected" }, String.Empty); Log("Registering device connection watcher updated event handler"); watcher.Updated += DeviceConnection_Updated; Log("Starting device connection watcher"); watcher.Start(); }
#pragma warning disable 1998 /// <summary> /// Get the device category this computer belongs to. /// </summary> /// <example>Computer.Desktop, Computer.Tablet.</example> /// <returns>The category of this device.</returns> public async virtual Task <string> GetDeviceType() { #if WINDOWS_UWP return(AnalyticsInfo.VersionInfo.DeviceFamily); #elif WP8 return(""); #else // WINRT var rootContainer = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, RootContainer, new[] { DisplayPrimaryCategoryKey }); return((string)rootContainer.Properties[DisplayPrimaryCategoryKey]); #endif }
public async Task setupInternal(string deviceName) { try { DeviceInformation deviceInfo = null; var devices = await DeviceInformation.FindAllAsync ( GattDeviceService.GetDeviceSelectorFromUuid(new Guid("0000180A-0000-1000-8000-00805F9B34FB")), // Device Information Service new string[] { "System.Devices.ContainerId" } ); if (devices.Count > 0) { foreach (var device in devices) { if (device.Name.Equals(deviceName)) { deviceInfo = device; break; } } } else { throw new Exception("Could not find any devices. Please make sure your device is paired and powered on!"); } // Check if the device is initially connected, and display the appropriate message to the user var deviceObject = await PnpObject.CreateFromIdAsync ( PnpObjectType.DeviceContainer, deviceInfo.Properties["System.Devices.ContainerId"].ToString(), new string[] { "System.Devices.Connected" } ); bool isConnected; Boolean.TryParse(deviceObject.Properties["System.Devices.Connected"].ToString(), out isConnected); if (isConnected) { await InitializeServiceAsync(deviceInfo); } } catch (Exception e) { throw new Exception("Retrieving device properties failed with message: " + e.Message); } }
private static async Task <string> GetRootDeviceInfoAsync(string propertyKey) { string result = "Unknown"; try { var pnp = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, RootContainer, new[] { propertyKey }); result = (string)pnp.Properties[propertyKey]; } catch { } return(result); }
public DisplayItem(PnpObject container) { name = (string)container.Properties["System.ItemNameDisplay"]; if (name == null || name.Length == 0) { name = "*Unnamed*"; } id = "Id: " + container.Id; properties += "Property store count is: " + container.Properties.Count + "\n"; foreach (var prop in container.Properties) { properties += prop.Key + " := " + prop.Value + "\n"; } }
public async Task <List <PnpDevice> > FindAllAsync(PnpObjectType type, IEnumerable <string> requestedProperties, string aqsFilter) { var pnpObjects = await PnpObject.FindAllAsync(type, requestedProperties, aqsFilter); var list = new List <PnpDevice>(); foreach (var pnpObject in pnpObjects) { list.Add ( new PnpDevice(pnpObject.Id, pnpObject.Properties, pnpObject.Type) ); } return(list); }
public static string GetWindowsVersion() { string str; string[] strArray = { "{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3" }; PnpObject halDevice = GetHalDevice(strArray); if (halDevice == null || !halDevice.Properties.ContainsKey("{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3")) { str = "UNKNOWN"; } else { str = halDevice.Properties["{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3"].ToString(); } return(str); }
/// <summary> /// hdt /// </summary> /// <param name="properties"></param> /// <returns></returns> static Task <PnpObject> GetHalDevice(params string[] properties) { PnpObject result = null; var actualProperties = Enumerable.Concat <string>(properties, new string[] { "{A45C254E-DF1C-4EFD-8020-67D146A850E0},10" }); PnpObjectCollection objects = WindowsRuntimeSystemExtensions.GetAwaiter <PnpObjectCollection>(PnpObject.FindAllAsync(PnpObjectType.Device, actualProperties, "System.Devices.ContainerId:=\"{00000000-0000-0000-FFFF-FFFFFFFFFFFF}\"")).GetResult(); foreach (PnpObject obj in objects) { KeyValuePair <string, object> pair = Enumerable.Last <KeyValuePair <string, object> >((IEnumerable <KeyValuePair <string, object> >)obj.Properties); if ((pair.Value != null) && pair.Value.ToString().Equals("4d36e966-e325-11ce-bfc1-08002be10318")) { result = obj; break; } } return(Task.FromResult <PnpObject>(result)); }
private static async Task <PnpObject> GetHalDevice(params string[] properties) { var actualProperties = properties.Concat(new[] { DeviceClassKey }); var rootDevices = await PnpObject.FindAllAsync(PnpObjectType.Device, actualProperties, RootQuery); foreach (var rootDevice in rootDevices.Where(d => d.Properties != null && d.Properties.Any())) { var lastProperty = rootDevice.Properties.Last(); if (lastProperty.Value != null) { if (lastProperty.Value.ToString().Equals(HalDeviceClass)) { return(rootDevice); } } } return(null); }
async void EnumerateDeviceContainers(object sender, RoutedEventArgs eventArgs) { FocusState focusState = EnumerateContainersButton.FocusState; EnumerateContainersButton.IsEnabled = false; string[] properties = { "System.ItemNameDisplay", "System.Devices.ModelName", "System.Devices.Connected" }; var containers = await PnpObject.FindAllAsync(PnpObjectType.DeviceContainer, properties); DeviceContainersOutputList.Items.Clear(); rootPage.NotifyUser(containers.Count + " device container(s) found", NotifyType.StatusMessage); foreach (PnpObject container in containers) { DeviceContainersOutputList.Items.Add(new DisplayItem(container)); } EnumerateContainersButton.IsEnabled = true; EnumerateContainersButton.Focus(focusState); }
/// <summary> /// Get the version of Windows for this computer. /// </summary> /// <example>6.2</example> /// <returns>Version number of Windows running on this computer.</returns> public static async Task <string> GetWindowsVersionAsync() { // There is no good place to get this so we're going to use the most popular // Microsoft driver version number from the device tree. var requestedProperties = new[] { DeviceDriverVersionKey, DeviceDriverProviderKey }; var microsoftVersionedDevices = (await PnpObject.FindAllAsync(PnpObjectType.Device, requestedProperties, RootContainerQuery)) .Select(d => new { Provider = (string)d.Properties.GetValueOrDefault(DeviceDriverProviderKey), Version = (string)d.Properties.GetValueOrDefault(DeviceDriverVersionKey) }) .Where(d => d.Provider == "Microsoft" && d.Version != null) .ToList(); var versionNumbers = microsoftVersionedDevices .GroupBy(d => d.Version.Substring(0, d.Version.IndexOf('.', d.Version.IndexOf('.') + 1))) .OrderByDescending(d => d.Count()) .ToList(); return(versionNumbers.Count > 0 ? versionNumbers[0].Key : ""); }
/// <summary> /// hdt /// </summary> /// <returns></returns> public static Task <string> GetWindowsVersionAsync() { TaskAwaiter <PnpObject> awaiter; awaiter = SystemInfoEstimate.GetHalDevice(new string[] { "{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3" }).GetAwaiter(); PnpObject hal = awaiter.GetResult(); string str; string[] versionParts; if (hal == null || hal.Properties.ContainsKey("{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3")) { str = null; } else { versionParts = hal.Properties["{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3"].ToString().Split(new char[] { '.' }); str = string.Join(".", Enumerable.ToArray <string>(Enumerable.Take <string>(versionParts, 2))); } return(Task.FromResult <string>(str)); }
async Task <bool> RegisterForConnectionEvents() { UnregisterForConnectionEvents(); string deviceContainerId = "{" + DeviceContainerId + "}"; PnpObject containerPnpObject = await PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, deviceContainerId, new string[] { CONNECTED_FLAG_PROPERTY_NAME }); var connectedProperty = containerPnpObject.Properties[CONNECTED_FLAG_PROPERTY_NAME]; bool isConnected = false; Boolean.TryParse(connectedProperty.ToString(), out isConnected); _connectionWatcher = PnpObject.CreateWatcher(PnpObjectType.DeviceContainer, new string[] { CONNECTED_FLAG_PROPERTY_NAME }, String.Empty); _connectionWatcher.Updated -= DeviceConnection_Updated; _connectionWatcher.Updated += DeviceConnection_Updated; _connectionWatcher.Start(); return(isConnected); }