private async void RunButton_Click(object sender, RoutedEventArgs e) { // Clear any previous messages MainPage.Current.NotifyUser("", NotifyType.StatusMessage); // Find all paired instances of the Rfcomm chat service chatServiceInfoCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (chatServiceInfoCollection.Count > 0) { List<string> items = new List<string>(); foreach (var chatServiceInfo in chatServiceInfoCollection) { items.Add(chatServiceInfo.Name); } cvs.Source = items; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { MainPage.Current.NotifyUser( "No chat services were found. Please pair with a device that is advertising the chat service.", NotifyType.ErrorMessage); } }
/// <summary> /// Moves servo to specified angle /// </summary> /// <param name="Angle">Angle to be moved</param> /// <returns></returns> public static async System.Threading.Tasks.Task<byte[]> MoveServo(byte Angle) { byte[] Response = new byte[1]; /* Gateway's I2C SLAVE address */ int SlaveAddress = 64; // 0x40 try { // Initialize I2C var Settings = new I2cConnectionSettings(SlaveAddress); Settings.BusSpeed = I2cBusSpeed.StandardMode; if (AQS == null || DIS == null) { AQS = I2cDevice.GetDeviceSelector("I2C1"); DIS = await DeviceInformation.FindAllAsync(AQS); } using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings)) { /* Send byte to the gateway to move servo at specified position */ Device.Write(new byte[] { Angle }); } } catch (Exception) { // SUPPRESS ANY ERROR } /* Return dummy or ZERO */ return Response; }
/// <summary> /// When the user presses the run button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list. /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private async void RunButton_Click(object sender, RoutedEventArgs e) { var button = sender as Button; // Disable the button while we do async operations so the user can't Run twice. button.IsEnabled = false; // Clear any previous messages rootPage.NotifyUser("", NotifyType.StatusMessage); // Find all paired instances of the Rfcomm chat service and display them in a list chatServiceDeviceCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid))); if (chatServiceDeviceCollection.Count > 0) { DeviceList.Items.Clear(); foreach (var chatServiceDevice in chatServiceDeviceCollection) { DeviceList.Items.Add(chatServiceDevice.Name); } DeviceList.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { rootPage.NotifyUser( "No chat services were found. Please pair with a device that is advertising the chat service.", NotifyType.ErrorMessage); } button.IsEnabled = true; }
private void ScenarioInit() { m_MonitorStarted = false; m_DeviceInfo = null; m_RenderEffectsManager = null; DisplayEmptyDevicesList(); DisplayEmptyEffectsList(); DisplayCategoriesList(); lblEffects.DataContext = new EffectLabelView { EffectLabelName = "Effects" }; }
public async void initialize(string options) { bleDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess)); if (bleDevices.Count == 0) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "{\"error\":\"No BLE devices were found or bluetooth disabled\",\"message\":\"Pair the device\"}")); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute)); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"initialized\"}")); } }
private async void InitializeRfcommServer() { try { string device1=RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); deviceCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(device1); } catch (Exception exception) { errorStatus.Visibility = Visibility.Visible; errorStatus.Text = exception.Message; } }
public async void Init() { devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); foreach(DeviceInformation cam in devices) { Debug.WriteLine(cam.Name); } camCount = devices.Count; if (camCount > 2) { Start(0); } }
private static async Task ConnectToController(DeviceInformationCollection deviceInformationCollection) { foreach (var d in deviceInformationCollection) { _deviceHandle = await HidDevice.FromIdAsync(d.Id, FileAccessMode.Read); if (_deviceHandle == null) { await _display.WriteAsync("No Xbox controller"); continue; } _deviceHandle.InputReportReceived += InputReportReceived; _isConnected = true; break; } }
private async void MainPage_LoadedAsync(object sender, RoutedEventArgs e) { // Get available devices for capturing media and list them _allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (_allVideoDevices == null || !_allVideoDevices.Any()) { Debug.WriteLine("No devices found."); return; } //add to device list foreach (DeviceInformation camera in _allVideoDevices) { if (CameraSelectionList.Items != null) { CameraSelectionList.Items.Add(camera.Name); } } }
// This gets called when we receive a disconnect notification private void DisconnectNotification(object sender, object arg) { rootPage.NotifyUser("WiFiDirect device disconnected", NotifyType.ErrorMessage); var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { GetDevicesButton.Visibility = Visibility.Visible; PCIpAddress.Visibility = Visibility.Collapsed; DeviceIpAddress.Visibility = Visibility.Collapsed; DisconnectButton.Visibility = Visibility.Collapsed; // Clear the FoundDevicesList FoundDevicesList.Visibility = Visibility.Collapsed; FoundDevicesList.Items.Clear(); }); devInfoCollection = null; }
async void RefreshDeviceList() { StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator; await progressbar.ShowAsync(); try { bleDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess)); if (bleDevices.Count == 0) { await new MessageDialog("No BLE devices were found or bluetooth disabled. Pair the device", "Info").ShowAsync(); Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute)); } lstDevices.ItemsSource = bleDevices; lstDevices.SelectedIndex = -1; // lstServices.ItemsSource = new List<string>(); } catch { } await progressbar.HideAsync(); }
public async void Run(IBackgroundTaskInstance taskInstance) { this.taskInstance = taskInstance; this.deferral = taskInstance.GetDeferral(); // Find all paired instances of the Rfcomm chat service and display them in a list chatServiceDeviceCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (chatServiceDeviceCollection.Count > 0) { deviceName = chatServiceDeviceCollection.First().Name; } if (deviceName != null) await SendMessage(chatServiceDeviceCollection.FirstOrDefault().Id); else { ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = "Device not found"; deferral.Complete(); } }
/// <summary> /// Sends control signal to the specific Arduino and retrieves response bytes. /// </summary> /// <param name="_Room">Room to which data to be send</param> /// <param name="ControlMode">Select specific control mode. Refer control mode at: https:\//www.hackster.io/AnuragVasanwala/home-automation</param> /// <param name="Pin">Pin to be set. ONLY VALID FOR MODE-2</param> /// <param name="PinValue">Value to be set. ONLY VALID FOR MODE-2</param> /// <returns>Returns fourteen response byte. Refer response byte scheme at: https:\//www.hackster.io/AnuragVasanwala/home-automation</returns> public static async System.Threading.Tasks.Task<byte[]> WriteRead(Room _Room, Mode ControlMode, byte Pin = 0, byte PinValue = 0) { while (Lock!=false) { } Lock = true; // Create response byte array of fourteen byte[] Response = new byte[14]; try { // Initialize I2C var Settings = new I2cConnectionSettings(_Room.I2C_Slave_Address); Settings.BusSpeed = I2cBusSpeed.StandardMode; if (AQS == null || DIS == null) { AQS = I2cDevice.GetDeviceSelector("I2C1"); DIS = await DeviceInformation.FindAllAsync(AQS); } using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings)) { Device.Write(new byte[] { byte.Parse(ControlMode.ToString().Replace("Mode", "")), Pin, PinValue }); Device.Read(Response); } } catch (Exception) { // SUPPRESS ERROR AND RETURN EMPTY RESPONSE ARRAY } Lock = false; return Response; }
private async Task EnumerateCamerasAsync() { try { discoveredCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (discoveredCameras == null || discoveredCameras.Count == 0) { Debug.WriteLine("No cameras found!"); return; } // Iterate through the devices to discover which is front camera and which is back camera foreach (var dev in discoveredCameras) { var location = dev.EnclosureLocation; if (location != null) { if (location.Panel == Panel.Back) { backCamera = dev; Debug.WriteLine("Back camera found: " + dev.Name); } if (location.Panel == Panel.Front) { frontCamera = dev; Debug.WriteLine("Front camera found: " + dev.Name); } } } } catch (Exception e) { Debug.WriteLine(e.Message); } }
public static async Task <SSD1306> CreateAtI2C(string i2CControllerName = I2CControllerName, byte ssd1306Address = Ssd1306Address) { I2cConnectionSettings settings = new I2cConnectionSettings(ssd1306Address) { BusSpeed = I2cBusSpeed.FastMode }; string aqs = I2cDevice.GetDeviceSelector(I2CControllerName); DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs); if (dis.Count == 0) { throw new ArgumentException($"The controller '{i2CControllerName}' yielded no devices.", nameof(i2CControllerName)); } var display = await I2cDevice.FromIdAsync(dis[0].Id, settings); if (display == null) { throw new ArgumentException($"I2C device was not found at address {ssd1306Address}.", nameof(ssd1306Address)); } return(CreateAtI2C(display)); }
private async void BoxDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (((ComboBox)sender).SelectedItem != null) { if (((OfflineMapsViewModel)this.DataContext).UseSerialGPS) { DeviceInformationCollection SerialDevices = null; using (SerialDevice device = await SerialDevice.FromIdAsync(((DeviceInformation)((ComboBox)sender).SelectedItem).Id)) { if (device != null) { var aqs = SerialDevice.GetDeviceSelector(device.PortName); SerialDevices = await DeviceInformation.FindAllAsync(aqs); } } if (SerialDevices != null) { await((OfflineMapsViewModel)this.DataContext).FindSerialGPS(SerialDevices); } } } }
/// <summary> /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI /// </summary> /// <returns></returns> public async Task Initialize(string faceKey, string emotionKey) { Debug.WriteLine("Initialize-Facedetector"); _faceKey = faceKey; _emotionKey = emotionKey; _faceMetaData = new FaceMetaData(_faceKey, _emotionKey); _faceMetaData.DetectedFaces += FaceMetaData_DetectedFaces; _displayOrientation = _displayInformation.CurrentOrientation; if (_orientationSensor != null) { _deviceOrientation = _orientationSensor.GetCurrentOrientation(); } // Clear any rectangles that may have been left over from a previous instance of the effect FacesCanvas.Children.Clear(); DeviceInformationCollection allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); CameraListBox.ItemsSource = allVideoDevices; }
private async Task <I2cDevice> InitializeDisplay() { // search for I2C Devices if needed //List<byte> result = await FindDevicesAsync(); try { string i2cDeviceSelector = I2cDevice.GetDeviceSelector(); DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(i2cDeviceSelector); DeviceInformation DI = devices[0]; var LCD_settings = new I2cConnectionSettings(0x27); LCD_settings.BusSpeed = I2cBusSpeed.StandardMode; LCD_settings.SharingMode = I2cSharingMode.Shared; return(await I2cDevice.FromIdAsync(DI.Id, LCD_settings)); } catch (Exception e) { return(null); } }
private async void initialize() { if (EventHandlerForDevice.Current.Device == null) { stackpanel2.Visibility = Visibility.Collapsed; rootPage.NotifyUser("Device is not connected", NotifyType.ErrorMessage); } else { MainPage.Current.NotifyUser("Connected to " + EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage); // So we can reset future tasks ResetReadCancellationTokenSource(); ResetWriteCancellationTokenSource(); } DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(LightSensor.GetDeviceSelector(), Constants.RequestedProperties); foreach (DeviceInformation deviceInfo in deviceInfoCollection) { lightSensor = await LightSensor.FromIdAsync(deviceInfo.Id); } }
//中島追加 public async void DeviceSetter() { try { //デバイスUUIDを取得 NamedGuid dHelperLightBlueBean = DeviceHelper.GetGuid("LightBlue Bean"); //該当するデバイスを列挙 dInfoLightBlueBean = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(dHelperLightBlueBean.Guid)); // Devices.Clear(); for (int cnt = 0; cnt < dInfoLightBlueBean.Count; cnt++) { Devices.Add(new DeviceMember(cnt, dInfoLightBlueBean[cnt].Name)); } this.RaisePropertyChanged("DeviceMember"); } catch { MessageHelper.DisplayBasicMessage("センサとペアリングされていますか?"); } }
//</SnippetEnumerateMidiInputDevices> //<SnippetEnumerateMidiOutputDevices> private async Task EnumerateMidiOutputDevices() { // Find all output MIDI devices string midiOutportQueryString = MidiOutPort.GetDeviceSelector(); DeviceInformationCollection midiOutputDevices = await DeviceInformation.FindAllAsync(midiOutportQueryString); midiOutPortListBox.Items.Clear(); // Return if no external devices are connected if (midiOutputDevices.Count == 0) { this.midiOutPortListBox.Items.Add("No MIDI output devices found!"); this.midiOutPortListBox.IsEnabled = false; return; } // Else, add each connected input device to the list foreach (DeviceInformation deviceInfo in midiOutputDevices) { this.midiOutPortListBox.Items.Add(deviceInfo.Name); this.midiOutPortListBox.IsEnabled = true; } }
/// <summary> /// 向目标设备发送控制信号 /// </summary> /// <param name="_Room">目标位置</param> /// <param name="ControlMode"></param> /// <param name="Pin">需要设置低高电压的Pin.(Mode2)</param> /// <param name="PinValue">0?1.(Mode2)</param> /// <returns>14位的返回数值.</returns> public static async System.Threading.Tasks.Task <byte[]> WriteRead(Room _Room, Mode ControlMode, byte Pin = 0, byte PinValue = 0) { while (Lock != false) { } Lock = true; byte[] Response = new byte[14]; try { var Settings = new I2cConnectionSettings(_Room.I2C_Slave_Address) { BusSpeed = I2cBusSpeed.StandardMode }; if (AQS == null || DIS == null) { AQS = I2cDevice.GetDeviceSelector("I2C1"); DIS = await DeviceInformation.FindAllAsync(AQS); } using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings)) { Device.Write(new byte[] { byte.Parse(ControlMode.ToString().Replace("Mode", "")), Pin, PinValue }); Device.Read(Response); } } catch (Exception) { } Lock = false; return(Response); }
//private functions private async Task UpdateFoundMipRobotList() { string deviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(BluetoothRobotConstants.SEND_DATA_SERVICE_UUID); DeviceInformationCollection collection = await DeviceInformation.FindAllAsync(deviceSelector); foreach (DeviceInformation info in collection) { //exclude any found mip if (FoundRobotList.FirstOrDefault(m => m.SendDataServiceInfo == info) == null) { T robot = new T(); robot.SendDataServiceInfo = info; //callback when mip was connected robot.DidConnectedEvent += (sender, connectedMipRobot) => { //prevent any duplicated mip if (ConnectedRobotList.FirstOrDefault(m => m == connectedMipRobot) == null) { ConnectedRobotList.Add((T)connectedMipRobot); } }; //callback when mip was disconnected robot.DidDisconnectedEvent += (sender, disconnectedMipRobot) => { ConnectedRobotList.Remove((T)disconnectedMipRobot); FoundRobotList.Remove((T)disconnectedMipRobot); }; //TODO: show log for found new mip FoundRobotList.Add(robot); } } }
public void Initialize(byte address = 0x40, I2cBusSpeed speed = I2cBusSpeed.StandardMode) { //MainPage rootPage = MainPage.Current; DeviceInformationCollection devices = null; Address = address; Speed = speed; //await rootPage.uart.SendText("I2C Device at Address " + address.ToString() + " Initializing\n\r"); Task.Run(async() => { var settings = new I2cConnectionSettings(Address) { BusSpeed = Speed }; settings.SharingMode = I2cSharingMode.Shared; // Get a selector string that will return all I2C controllers on the system string aqs = I2cDevice.GetDeviceSelector(); // Find the I2C bus controller device with our selector string devices = await DeviceInformation.FindAllAsync(aqs); //search for the controller if (!devices.Any()) { throw new IOException("No I2C controllers were found on the system"); } //see if we can find the hat device = await I2cDevice.FromIdAsync(devices[0].Id, settings); }).Wait(); //await rootPage.uart.SendText("I2C Device at Address " + address.ToString() + " Initialized\n\r"); }
/*public static async void GetSmartCardReader() * { * while (true == true) * { * DeviceInformationCollection devices = await DeviceInformation.FindAllAsync * (SmartCardReader.GetDeviceSelector()); * * if (devices.Count > 0) * { * List<SmartCardReader> readers = new List<SmartCardReader>(); * * foreach (DeviceInformation device in devices) * { * readers.Add(await SmartCardReader.FromIdAsync(device.Id)); * } * * Thread scanSmartCard = new Thread(new ParameterizedThreadStart(ScanSmartCard)); * scanSmartCard.Start(readers); * Console.WriteLine("Card Reader Ready"); * Thread.CurrentThread.Abort(); * } * * Thread.Sleep(2000); * } * }*/ public static void ScanSmartCard() { List <SmartCardReader> readers = new List <SmartCardReader>(); DeviceWatcher smartCardReaderWatcher = DeviceInformation.CreateWatcher(); smartCardReaderWatcher.Added += async(sender, args) => { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(SmartCardReader.GetDeviceSelector()); foreach (DeviceInformation device in devices) { if (device.Id == args.Id) { readers.Add(await SmartCardReader.FromIdAsync(args.Id)); readers[readers.Count - 1].CardAdded += GetCardID; Console.WriteLine("{0} is running and ready", readers[readers.Count - 1].Name); //can be changed to output in a popup } } }; smartCardReaderWatcher.Removed += (sender, args) => { for (int idCounter = 0; idCounter < readers.Count; idCounter++) { if (readers[idCounter].DeviceId == args.Id) { readers[idCounter].CardAdded -= GetCardID; Console.WriteLine("{0} has been removed", readers[idCounter].Name); //can be changed to output in a popup readers.RemoveAt(idCounter); break; } } }; smartCardReaderWatcher.Start(); }
public async Task <bool[]> DeviceExistsAsync(Guid guid) { bool[] success = new bool[2] { false, false }; string deviceID = ""; DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(guid)); if (devices.Count > 0) { foreach (DeviceInformation info in devices) { success[0] = true; Debug.Log("Found Device: " + info.Name); deviceID = info.Id; } } if (success[0]) { BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceID); success[1] = device != null; Debug.Log("Device Name: " + device.Name); foreach (GattDeviceService service in device.GattServices) { Debug.Log("Device Service UUID: " + service.Uuid); foreach (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic characteristic in service.GetAllCharacteristics()) { Debug.Log("Characteristics UUID: " + characteristic.Uuid); } } } return(success); }
public async Task StartLiveStream() { Debug.WriteLine("StartLiveStream"); await CleanupCameraAsync(); if (_devices == null) { try { _devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); } catch (Exception ex) { Debug.WriteLine(ex.Message); _devices = null; } if ((_devices == null) || (_devices.Count == 0)) { // No camera sources found Debug.WriteLine("No cameras found"); NotifyUser(false, "No cameras found."); return; } _appModel.CameraNamesList = _devices.Select(device => device.Name); return; } // If just above 0 you fool if (_appModel.SelectedCameraIndex >= 0) { Debug.WriteLine("StartLive: already 0"); await ChangeLiveStream(); return; } // If already have the list, set to the default _appModel.SelectedCameraIndex = 0; }
/// <summary> /// Attempts to initialize the serial port, /// and communications to the controller. /// </summary> /// <returns>The async Task.</returns> public async Task InitializeSerialAsync() { // Clear old values serialPort = null; serialInitialized = false; DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector()); foreach (DeviceInformation info in devices) { SerialDevice serialPortTemp = await SerialDevice.FromIdAsync(info.Id); if (serialPortTemp != null && !serialPortTemp.PortName.Contains("UART")) { serialPort = serialPortTemp; } } if (serialPort == null) { throw new Exception("Could not open the serial device. The device was invalid or not found."); } serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000); serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000); serialPort.BaudRate = 9600; serialPort.Parity = SerialParity.None; serialPort.StopBits = SerialStopBitCount.One; serialPort.DataBits = 8; serialPort.Handshake = SerialHandshake.None; readTokenSource = new CancellationTokenSource(); writeTokenSource = new CancellationTokenSource(); serialInitialized = true; await Task.Run(async() => { await SerialInitialized.Invoke(); }); }
private async Task <bool> Connect() { if (rfCommDeviceService == null) { string selector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector); DeviceInformation device = devices.SingleOrDefault(x => x.Name.Equals("OBDII", StringComparison.OrdinalIgnoreCase)); if (device != null) { rfCommDeviceService = await RfcommDeviceService.FromIdAsync(device.Id); streamSocket = new StreamSocket(); await streamSocket.ConnectAsync(rfCommDeviceService.ConnectionHostName, rfCommDeviceService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); reader = new DataReader(streamSocket.InputStream); readCancellationTokenSource = new CancellationTokenSource(); readCancelLock = new object(); writer = new DataWriter(streamSocket.OutputStream); writeCancellationTokenSource = new CancellationTokenSource(); writeCancelLock = new object(); OnConnect(this, "Connected."); return(true); } else { OnException(this, new Exception("Could not connect.")); return(false); } } return(true); }
/// <summary> /// Sends control signal to the specific Arduino and retrieves response bytes. /// </summary> /// <param name="I2C_Slave_Address">Slave Arduino's address</param> /// <param name="ControlMode">Select specific control mode. Refer control mode at: https:\//www.hackster.io/AnuragVasanwala/home-automation</param> /// <param name="Pin">Pin to be set. ONLY VALID FOR MODE-2</param> /// <param name="PinValue">Value to be set. ONLY VALID FOR MODE-2</param> /// <returns>Returns fourteen response byte. Refer response byte scheme at: https:\//www.hackster.io/AnuragVasanwala/home-automation</returns> public static async System.Threading.Tasks.Task <byte[]> WriteRead(int I2C_Slave_Address, Mode ControlMode, byte Pin = 0, byte PinValue = 0) { while (Lock != false) { } Lock = true; // Create response byte array of fourteen byte[] Response = new byte[14]; try { // Initialize I2C var Settings = new I2cConnectionSettings(I2C_Slave_Address); Settings.BusSpeed = I2cBusSpeed.StandardMode; if (AQS == null || DIS == null) { AQS = I2cDevice.GetDeviceSelector("I2C1"); DIS = await DeviceInformation.FindAllAsync(AQS); } using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings)) { Device.Write(new byte[] { byte.Parse(ControlMode.ToString().Replace("Mode", "")), Pin, PinValue }); Device.Read(Response); } } catch (Exception) { // SUPPRESS ERROR AND RETURN EMPTY RESPONSE ARRAY } Lock = false; return(Response); }
private static async void SetTimeToDs3231(DateTime time) { try { // Initialize I2C var settings = new I2cConnectionSettings(SlaveAddress) { BusSpeed = I2cBusSpeed.StandardMode }; if (_aqs == null || _dis == null) { _aqs = I2cDevice.GetDeviceSelector("I2C1"); _dis = await DeviceInformation.FindAllAsync(_aqs); } using (var device = await I2cDevice.FromIdAsync(_dis[0].Id, settings)) { var writeSeconds = DecToBcd((byte)time.Second); var writeMinutes = DecToBcd((byte)time.Minute); var writeHours = DecToBcd((byte)time.Hour); var writeDayofweek = DecToBcd((byte)time.DayOfWeek); var writeDay = DecToBcd((byte)time.Day); var writeMonth = DecToBcd((byte)time.Month); var writeYear = DecToBcd((byte)(time.Year % 100)); byte[] writeTime = { 0x00, writeSeconds, writeMinutes, writeHours, writeDayofweek, writeDay, writeMonth, writeYear }; device.Write(writeTime); } } catch (Exception ex) { Debug.Write(ex.Message); } }
public static async System.Threading.Tasks.Task <byte> WriteRead_OneByte(byte ByteToBeSend) { byte[] ReceivedData = new byte[1]; /* Arduino Nano's I2C SLAVE address */ int SlaveAddress = 64; // 0x40 try { // Initialize I2C var Settings = new I2cConnectionSettings(SlaveAddress); Settings.BusSpeed = I2cBusSpeed.StandardMode; if (AQS == null || DIS == null) { AQS = I2cDevice.GetDeviceSelector("I2C1"); DIS = await DeviceInformation.FindAllAsync(AQS); } using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings)) { /* Send byte to Arduino Nano */ Device.Write(new byte[] { ByteToBeSend }); /* Read byte from Arduino Nano */ Device.Read(ReceivedData); } } catch (Exception) { // SUPPRESS ANY ERROR } /* Return received data or ZERO on error */ return(ReceivedData[0]); }
/// <summary> /// Checks whether the device supports smart card reader mode /// </summary> /// <returns>None</returns> public static async Task <DeviceInformation> GetFirstSmartCardReaderInfo(SmartCardReaderKind readerKind = SmartCardReaderKind.Any) { // Check if the SmartCardConnection API exists on this currently running SKU of Windows if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.SmartCards.SmartCardConnection")) { // This SKU of Windows does not support NFC card reading, only desktop and phones/mobile devices support NFC card reading return(null); } // Device selector string is from SmartCardReader.GetDeviceSelector(SmartCardReaderKind.Nfc) except that we remove the conditional // about the interface being enabled, since we want to get the device object regardless of whether the user turned it off in the CPL string query = "System.Devices.InterfaceClassGuid:=\"{DEEBE6AD-9E01-47E2-A3B2-A66AA2C036C9}\""; if (readerKind != SmartCardReaderKind.Any) { query += " AND System.Devices.SmartCards.ReaderKind:=" + (int)readerKind; } DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(query); // There is a bug on some devices that were updated to WP8.1 where an NFC SmartCardReader is // enumerated despite that the device does not support it. As a workaround, we can do an additonal check // to ensure the device truly does support it. var workaroundDetect = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{50DD5230-BA8A-11D1-BF5D-0000F805F530}\""); if (workaroundDetect.Count == 0 || devices.Count == 0) { // Not supported return(null); } // Smart card reader supported, but may be disabled return((from d in devices where d.IsEnabled orderby d.IsDefault descending select d).FirstOrDefault()); }
private async Task <bool> retrieveBoard() { DeviceInformationCollection set = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); foreach (var devInfo in set) { try { Debug.WriteLine("device = " + devInfo.Name + ", " + devInfo.Pairing); if (devInfo.Name.Contains("MetaWear")) { BluetoothLEDevice selectedDevice = await BluetoothLEDevice.FromIdAsync(devInfo.Id); if (selectedDevice != null) { var newBoard = MetaWearBoard.getMetaWearBoardInstance(selectedDevice); var initResult = await newBoard.Initialize(); if (initResult == 0) { board = newBoard.cppBoard; return(true); } } else { Debug.WriteLine("windows is confused; found a BLE device-info (" + devInfo.Name + ") but could not find it"); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } return(false); }
private async void Init() { try { DeviceInformationCollection DeviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); //var numDevices = DeviceInfoCollection.Length; //Debug.LogFormat("{0} devices found!", numDevices); // By clearing the backing data, we are effectively clearing the ListBox _pairedDevices = new ObservableCollection <DeviceInformation>(); _pairedDevices.Clear(); //if (numDevices == 0) //{ // Debug.Log("No paired devices found"); // System.Diagnostics.Debug.WriteLine("InitializeRfcommDeviceService: No paired devices found."); //} //else //{ // Found paired devices. foreach (var deviceInfo in DeviceInfoCollection) { Debug.LogFormat("Found paired device: {0}", deviceInfo.Id); //if (deviceInfo.Id.Contains("f8:63:3f:4a:3e:da")) { ConnectToDevice(deviceInfo); //} _pairedDevices.Add(deviceInfo); } //} } catch (Exception ex) { Debug.LogFormat("Init exception: {0}", ex.Message); } }
/// <summary> /// This is the click handler for the 'StartPreview' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void StartPreview_Click(object sender, RoutedEventArgs e) { try { // Check if the machine has a webcam DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (devices.Count > 0) { rootPage.NotifyUser("", NotifyType.ErrorMessage); if (mediaCaptureMgr == null) { // Using Windows.Media.Capture.MediaCapture APIs to stream from webcam mediaCaptureMgr = new MediaCapture(); await mediaCaptureMgr.InitializeAsync(); VideoStream.Source = mediaCaptureMgr; await mediaCaptureMgr.StartPreviewAsync(); previewStarted = true; ShowSettings.Visibility = Visibility.Visible; StartPreview.IsEnabled = false; } } else { rootPage.NotifyUser("A webcam is required to run this sample.", NotifyType.ErrorMessage); } } catch (Exception ex) { mediaCaptureMgr = null; rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); } }
public override async Task <List <IBluetoothDevice> > GetPairedDevices() { var devices = new List <IBluetoothDevice>(); var selector = BluetoothDevice.GetDeviceSelector(); DeviceInformationCollection DeviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); foreach (var deviceInfo in DeviceInfoCollection) { var device = new UWPBluetoothDevice() { Name = deviceInfo.Name, Address = string.Empty }; device.BluetoothDevice = deviceInfo; var id = string.Empty; if (deviceInfo.Id.Contains("BTHENUM#{")) { var index = deviceInfo.Id.IndexOf("BTHENUM#{") + 9; id = deviceInfo.Id.Substring(index, 36); } if (!String.IsNullOrEmpty(id)) { var guid = Guid.Parse(id); device.UniqueIdentifiers.Add(guid); } devices.Add(device); } return(devices); }
public async Task InitAsync() { /* Create selector to select all devices with capability to do serial communication. */ string selector = SerialDevice.GetDeviceSelector(); /* Query device registry with created selector. */ DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector); /* Find device that we need by its name. */ DeviceInformation device = devices .Where(x => x.Name == GATEWAY_NAME) .FirstOrDefault(); /* Create wrapper around the port based on device id. */ SerialDevice serialDevice = await SerialDevice.FromIdAsync(device.Id); serialDevice.WriteTimeout = TimeSpan.FromMilliseconds(1000); serialDevice.ReadTimeout = TimeSpan.FromMilliseconds(250); serialDevice.BaudRate = 115200; serialDevice.Parity = SerialParity.None; serialDevice.StopBits = SerialStopBitCount.One; serialDevice.DataBits = 7; serialDevice.Handshake = SerialHandshake.None; serialDevice.IsRequestToSendEnabled = true; _reader = new DataReader(serialDevice.InputStream); _reader.InputStreamOptions = InputStreamOptions.Partial; }
public async Task <BLEDeviceInfo[]> ScanBluetoothAdvertisers() { // For a more responsive user experience, // see BluetoothLEAdvertisementWatcher or // DeviceInformation.CreateWatcher() // instead of DeviceInformation.FindAllAsync(). const string bluetoothLeDevicesFilter = "(System.Devices.Aep.ProtocolId:=\"{" + BLEProtocolId + "}\")"; DeviceInformationCollection bleDevices = await DeviceInformation.FindAllAsync(bluetoothLeDevicesFilter, RequestedProperties, DeviceInformationKind.AssociationEndpoint); var result = new List <BLEDeviceInfo>(bleDevices.Count); for (int i = 0; i < bleDevices.Count; i++) { var model = BLEDeviceInfo.FromRawDeviceInformation(bleDevices[i]) with { OriginalOrder = i }; if (await CheckForCustomCharacteristic(model)) { result.Add(model); } } result.Sort(BLEDeviceInfoComparer.Instance); return(result.ToArray()); }
private async Task <DeviceInformation> ChooseCameraDevice() { switchIcon.Visibility = Visibility.Visible; cameraIcon.Visibility = Visibility.Visible; StartIcon.Visibility = Visibility.Collapsed; Debug.WriteLine("Choose a Camera Device"); //Get all Devices _CameraDeviceGroup = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); for (int i = 0; i < _CameraDeviceGroup.Count; i++) { Debug.WriteLine(_CameraDeviceGroup[i].Name.ToString()); } // try to get the back facing device for a phone var backFacingDevice = _CameraDeviceGroup .First(c => c.EnclosureLocation?.Panel == Windows.Devices.Enumeration.Panel.Front); // but if that doesn't exist, take the first camera device available var preferredDevice = backFacingDevice ?? _CameraDeviceGroup.Last(); _CurrentCamera = preferredDevice; return(_CurrentCamera); }
private async void Button_Click(object sender, RoutedEventArgs e) { rfcommServiceInfoCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush)); var count = rfcommServiceInfoCollection.Count; Debug.WriteLine("Count of RFCOMM Service: " + count); if (count > 0) { lock (this) { streamSocket = new StreamSocket(); } var defaultSvcInfo = rfcommServiceInfoCollection.FirstOrDefault(); rfcommDeviceService = await RfcommDeviceService.FromIdAsync(defaultSvcInfo.Id); if (rfcommDeviceService == null) { Debug.WriteLine("Rfcomm Device Service is NULL, ID = {0}", defaultSvcInfo.Id); return; } Debug.WriteLine("ConnectionHostName: {0}, ConnectionServiceName: {1}", rfcommDeviceService.ConnectionHostName, rfcommDeviceService.ConnectionServiceName); await streamSocket.ConnectAsync(rfcommDeviceService.ConnectionHostName, rfcommDeviceService.ConnectionServiceName); dataWriter = new DataWriter(streamSocket.OutputStream); connectButton.Visibility = Visibility.Collapsed; } }
private async void UpdateDevices() { // Get a list of all MIDI devices this.DeviceInformationCollection = await DeviceInformation.FindAllAsync(deviceSelectorString); deviceList.Clear(); //if (!this.DeviceInformationCollection.Any()) deviceListBox.Items.Add("No MIDI devices found!"); foreach (var deviceInformation in this.DeviceInformationCollection) { deviceList.Add(deviceInformation.Name); } if (deviceList.Count >= 2) { midiToggle.IsEnabled = true; } else { midiToggle.IsEnabled = false; midiToggle.IsOn = false; } }
internal async Task <bool> InitializeAsync() { //USB\VID_045E&PID_0719\E02F1950 - receiver //USB\VID_045E & PID_02A1 & IG_00\6 & F079888 & 0 & 00 - XboxController //0x01, 0x05 = game controllers DeviceInformationCollection deviceInformationCollection = null; while (true) { deviceInformationCollection = await GetDeviceInformationCollection(); if (deviceInformationCollection != null && deviceInformationCollection.Count > 0) { break; } await Task.Delay(5000); } await ConnectToController(deviceInformationCollection); return(true); }
public async Task Init() { try { // Instantiate the I2CConnectionSettings using the device address of the TCS34725 I2cConnectionSettings settings = new I2cConnectionSettings(TCS34725Params.Address); settings.BusSpeed = I2cBusSpeed.FastMode; // Use the I2CBus device selector to create an advanced query syntax string string aqs = I2cDevice.GetDeviceSelector(I2CControllerName); // Use the Windows.Devices.Enumeration.DeviceInformation class to create a // collection using the advanced query syntax string DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs); // Instantiate the the TCS34725 I2C device using the device id of the I2CBus // and the I2CConnectionSettings colorSensor = await I2cDevice.FromIdAsync(dis[0].Id, settings); } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace); throw; } }
/// <summary> /// Enumerates all storages and populates the device selection list. /// </summary> async private Task ShowDeviceSelectorAsync() { _deviceInfoCollection = null; // Find all storage devices using Windows.Devices.Enumeration _deviceInfoCollection = await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector()); if (_deviceInfoCollection.Count > 0) { var items = new List<object>(); foreach (DeviceInformation deviceInfo in _deviceInfoCollection) { items.Add(new { Name = deviceInfo.Name, }); } DeviceList.ItemsSource = items; DeviceSelector.Visibility = Visibility.Visible; } else { rootPage.NotifyUser("No removable storages were found. Please attach a removable storage to the system (e.g. a camera or camera memory)", NotifyType.StatusMessage); } }
private async Task PopulateDeviceList() { outputDevicesListBox.Items.Clear(); outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); outputDevicesListBox.Items.Add("-- Pick output device --"); foreach (var device in outputDevices) { outputDevicesListBox.Items.Add(device.Name); } }
/// <summary> /// Creates a device collection from devices within reach. /// </summary> public async Task Scan() { //seek devices using the query deviceCollection = await DeviceInformation.FindAllAsync(deviceSelector); }
private async Task InitI2C() { try { var i2CSettings = new I2cConnectionSettings(0x48) { BusSpeed = I2cBusSpeed.FastMode, SharingMode = I2cSharingMode.Shared }; var i2C1 = I2cDevice.GetDeviceSelector("I2C1"); _devices = await DeviceInformation.FindAllAsync(i2C1); _adc = await I2cDevice.FromIdAsync(_devices[0].Id, i2CSettings); } catch (Exception ex) { throw new Exception("I2C Initialization Failed", ex); } _adc.Write(new byte[] { 0x01, 0xc2, 0x20 }); _adc.Write(new byte[] { 0x02, 0x00, 0x00 }); _adc.Write(new byte[] { 0x03, 0xff, 0xff }); }
/// <summary> /// When the user presses the run button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list. /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private async void findDevices_Click(object sender, RoutedEventArgs e) { var button = sender as Button; // Disable the button while we do async operations so the user can't Run twice. button.IsEnabled = false; // Clear any previous messages statusTextBlock.Text = ""; // Find all paired instances of the Rfcomm chat service and display them in a list chatServiceDeviceCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (chatServiceDeviceCollection.Count > 0) { deviceName = chatServiceDeviceCollection.First().Name; statusTextBlock.Text = "STATUS: Found device: " + chatServiceDeviceCollection.FirstOrDefault().Name; } else { statusTextBlock.Text = "STATUS: No devices found!"; } button.IsEnabled = true; }
private async void EnumerateWebcamsAsync() { try { m_devInfoCollection = null; devListView.Items.Clear(); m_devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (m_devInfoCollection.Count == 0) { var dialog = new MessageDialog("No WebCams found!"); await dialog.ShowAsync(); } else { for (int i = 0; i < m_devInfoCollection.Count; i++) { var devInfo = m_devInfoCollection[i]; var location = devInfo.EnclosureLocation; if (location != null) { if (location.Panel == Windows.Devices.Enumeration.Panel.Front) { devListView.Items.Add(devInfo.Name + "-Front"); } else if (location.Panel == Windows.Devices.Enumeration.Panel.Back) { devListView.Items.Add(devInfo.Name + "-Back"); } else { devListView.Items.Add(devInfo.Name); } } else { devListView.Items.Add(devInfo.Name); } } devListView.SelectedIndex = 1; // Select the HovercCam Solo8 //devListView.SelectedIndex = devListView.Items.IndexOf("HoverCam Solo8"); } // myGlobals.newProc(1); } catch (Exception e) { var dialog = new MessageDialog(e.ToString()); await dialog.ShowAsync(); } }
private async void EnumerateWebcamsAsync() { try { ShowStatusMessage("Enumerating Webcams..."); m_devInfoCollection = null; EnumedDeviceList2.Items.Clear(); m_devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (m_devInfoCollection.Count == 0) { ShowStatusMessage("No WebCams found."); } else { for (int i = 0; i < m_devInfoCollection.Count; i++) { var devInfo = m_devInfoCollection[i]; var location = devInfo.EnclosureLocation; if (location != null) { if (location.Panel == Windows.Devices.Enumeration.Panel.Front) { EnumedDeviceList2.Items.Add(devInfo.Name + "-Front"); } else if (location.Panel == Windows.Devices.Enumeration.Panel.Back) { EnumedDeviceList2.Items.Add(devInfo.Name + "-Back"); } else { EnumedDeviceList2.Items.Add(devInfo.Name); } } else { EnumedDeviceList2.Items.Add(devInfo.Name); } } EnumedDeviceList2.SelectedIndex = 0; ShowStatusMessage("Enumerating Webcams completed successfully."); btnStartDevice2.IsEnabled = true; } } catch (Exception e) { ShowExceptionMessage(e); } }
private async void EnumerateMicrophonesAsync() { try { ShowStatusMessage("Enumerating Microphones..."); m_microPhoneInfoCollection = null; EnumedMicrophonesList2.Items.Clear(); m_microPhoneInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.AudioCapture); try { if (m_microPhoneInfoCollection == null || m_microPhoneInfoCollection.Count == 0) { ShowStatusMessage("No Microphones found."); } else { for (int i = 0; i < m_microPhoneInfoCollection.Count; i++) { var devInfo = m_microPhoneInfoCollection[i]; var location = devInfo.EnclosureLocation; if (location != null) { if (location.Panel == Windows.Devices.Enumeration.Panel.Front) { EnumedMicrophonesList2.Items.Add(devInfo.Name + "-Front"); } else if (location.Panel == Windows.Devices.Enumeration.Panel.Back) { EnumedMicrophonesList2.Items.Add(devInfo.Name + "-Back"); } else { EnumedMicrophonesList2.Items.Add(devInfo.Name); } } else { EnumedMicrophonesList2.Items.Add(devInfo.Name); } } EnumedMicrophonesList2.SelectedIndex = 0; ShowStatusMessage("Enumerating Microphones completed successfully."); } } catch (Exception e) { ShowExceptionMessage(e); } } catch (Exception e) { ShowExceptionMessage(e); } }
/// <summary> /// 'Initialize Audio and Video' button action function /// Dispose existing MediaCapture object and set it up for audio and video /// Enable or disable appropriate buttons /// - DISABLE 'Initialize Audio and Video' /// - DISABLE 'Start Audio Record' /// - ENABLE 'Initialize Audio Only' /// - ENABLE 'Start Video Record' /// - ENABLE 'Take Photo' /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void initVideo_Click(object sender, RoutedEventArgs e) { // Disable all buttons until initialization completes SetInitButtonVisibility(Action.DISABLE); SetVideoButtonVisibility(Action.DISABLE); SetAudioButtonVisibility(Action.DISABLE); try { if (devices == null) { devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); ListDeviceDetails(); } if (mediaCapture != null) { // Cleanup MediaCapture object if (isPreviewing) { await mediaCapture.StopPreviewAsync(); isPreviewing = false; } if (isRecording) { await mediaCapture.StopRecordAsync(); isRecording = false; //recordVideo.Content = "Start Video Record"; //recordAudio.Content = "Start Audio Record"; } mediaCapture.Dispose(); mediaCapture = null; } status.Text = "Initializing camera to capture audio and video..."; // Use default initialization mediaCapture = new MediaCapture(); //await mediaCapture.InitializeAsync(); //0 might be the built in camera into your PC //in my case 1 is the microscope...so you might change the code below await mediaCapture.InitializeAsync( new MediaCaptureInitializationSettings { VideoDeviceId = devices[0].Id }); // Set callbacks for failure and recording limit exceeded status.Text = "Device successfully initialized for video recording!"; mediaCapture.Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed); mediaCapture.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded); // Start Preview previewElement.Source = mediaCapture; await mediaCapture.StartPreviewAsync(); isPreviewing = true; status.Text = "Camera preview succeeded"; // Enable buttons for video and photo capture SetVideoButtonVisibility(Action.ENABLE); } catch (Exception ex) { status.Text = "Unable to initialize camera for audio/video mode: " + ex.Message; SetInitButtonVisibility(Action.ENABLE); } }
/// <summary> /// Add any connected MIDI devices to the list /// </summary> private async void UpdateDevices() { // Get a list of all MIDI devices this.deviceInformationCollection = await DeviceInformation.FindAllAsync(this.midiSelector); // If no devices are found, update the ListBox if ((this.deviceInformationCollection == null) || (this.deviceInformationCollection.Count == 0)) { // Start with a clean list this.portList.Items.Clear(); this.portList.Items.Add("No MIDI ports found"); this.portList.IsEnabled = false; } // If devices are found, enumerate them and add them to the list else { // Start with a clean list this.portList.Items.Clear(); foreach (var device in deviceInformationCollection) { this.portList.Items.Add(device.Name); } this.portList.IsEnabled = true; } }
private async Task GetCameraDevices() { _cameraInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); _microphoneInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.AudioCapture); isFrontFacingSupported = _cameraInfoCollection.Count > 1; }
private async void EnumerateDevices(Object sender, Windows.UI.Xaml.RoutedEventArgs evt) { string AudioSelector = MediaDevice.GetAudioRenderSelector(); DeviceInformationCollection DeviceInfoCollection; DeviceInfoCollection = await DeviceInformation.FindAllAsync(AudioSelector); var noteList = new ObservableCollection<DeviceView>(); m_DeviceInfo = DeviceInfoCollection; for ( int i = 0; i < DeviceInfoCollection.Count; i++ ) { noteList.Add(new DeviceView { DeviceName = DeviceInfoCollection[i].Name }); } DevicesList.ItemsSource = noteList; DevicesList.IsEnabled = true; }
private async Task InitializeRfcommServer() { try { string device1 = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort); deviceCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(device1); } catch (Exception exception) { //errorStatus.Visibility = Visibility.Visible; errorStatusText = exception.Message; Debug.WriteLine("CommunicationChannelBT: " + errorStatusText); } }
public void close(string options) { bleDevices = null; currentDevice = null; currentDeviceServices = null; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"closed\"}")); }
/// <summary> /// Required before starting recording /// </summary> /// <returns></returns> private async Task<string> CreateAudioGraphAsync() { // var inputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioCaptureSelector()); // LOLLO TEST _outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); if (_outputDevices == null || _outputDevices.Count < 1) { return "AudioGraph Creation Error: no output devices found"; } AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media) { QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency, PrimaryRenderDevice = _outputDevices[0] }; CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings); if (result.Status != AudioGraphCreationStatus.Success) { // Cannot create graph return string.Format("AudioGraph Creation Error because {0}", result.Status.ToString()); } _audioGraph = result.Graph; // Because we are using lowest latency setting, we need to handle device disconnection errors _audioGraph.UnrecoverableErrorOccurred += OnGraph_UnrecoverableErrorOccurred; //// Create a device output node // away, so we get no echo //CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await _audioGraph.CreateDeviceOutputNodeAsync(); //if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) //{ // // Cannot create device output node // return string.Format("Audio Device Output unavailable because {0}", deviceOutputNodeResult.Status.ToString()); //} //_deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode; // Create a device input node using the default audio input device CreateAudioDeviceInputNodeResult deviceInputNodeResult = await _audioGraph.CreateDeviceInputNodeAsync(MediaCategory.Other); if (deviceInputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) { // Cannot create device input node return string.Format("Audio Device Input unavailable because {0}", deviceInputNodeResult.Status.ToString()); } _deviceInputNode = deviceInputNodeResult.DeviceInputNode; //// LOLLO set the volume, rather useless coz it is like a mixer and the default value is 1. //if (_deviceOutputNode.OutgoingGain < 1.0) _deviceOutputNode.OutgoingGain = 1.0; //if (_deviceInputNode.OutgoingGain < 1.0) _deviceInputNode.OutgoingGain = 1.0; return string.Empty; }
public Scenario1_ChatClient() { this.InitializeComponent(); chatSocket = null; chatWriter = null; chatService = null; chatServiceInfoCollection = null; App.Current.Suspending += App_Suspending; }