Inheritance: IDeviceInformation
 public async Task ConnectToDevice(DeviceInformation device)
 {
     this.State = ConnectionState.Connecting;
     try
     {
         serialConnection = await SerialDevice.FromIdAsync(device.Id);
         if (serialConnection != null)
         {
             serialConnection.BaudRate = 115200;
             serialConnection.DataBits = 8;
             serialConnection.Parity = SerialParity.None;
             writer = new DataWriter(serialConnection.OutputStream);
             reader = new DataReader(serialConnection.InputStream);
             Task listen = ListenForMessagesAsync();
             this.State = ConnectionState.Connected;
         }
         else {
             Debugger.ReportToDebugger(this, "Unable to create service.\nMake sure that the 'serialcommunication' capability is declared with a function of type 'name:serialPort' in Package.appxmanifest.", Debugger.Device.Pc);
             this.State = ConnectionState.Failure;
         }
     }
     catch (TaskCanceledException ex)
     {
         this.State = ConnectionState.Failure;
         Debugger.ReportToDebugger(this, ex.Message, Debugger.Device.Pc);
     }
     catch (Exception ex)
     {
         this.State = ConnectionState.Failure;
         Debugger.ReportToDebugger(this, ex.Message, Debugger.Device.Pc);
     }
 }
Example #2
0
        private async Task<bool> GetHrAndBatteryDevice()
        {
            StatusInformation = "Start search for devices, HR";
            var devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));
            if (null == devices || devices.Count <= 0) return true;
            foreach (var device in devices.Where(device => device.Name == "Polar H7 498C1817"))
            {
                _devicePolarHr = device;
                StatusInformation2 = "Found hr device";
                break;
            }

            StatusInformation = "Start search for devices, Battery";
            devices = await DeviceInformation.FindAllAsync(
                GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.Battery));
            if (null == devices || devices.Count <= 0) return true;
            foreach (var device in devices.Where(device => device.Name == "Polar H7 498C1817"))
            {
                _devicePolarBattery = device;
                StatusInformation2 = "Found battery device";
                break;
            }
            StatusInformation = $"Found HR [{(_devicePolarHr != null)}] Battery [{(_devicePolarBattery != null)}]";
            return (_devicePolarHr != null && _devicePolarBattery != null);
        }
        // Using device type decideds which device object to initilise, this allows for dynamic object creation.
        public static DeviceBase GetDeviceObject(DeviceInformation deviceInfo, DeviceType type)
        {
            DeviceBase device = null;
            // Main switch statement to handle the creation of the device objects.
            switch (type)
            {
                case DeviceType.GenericAccess:
                    device = new GenericAccessDevice();
                    break;
                case DeviceType.HeartRate:
                    device = new HeartRateMonitorDevice();
                    break;
            }

            if (device == null)
            {
                // Display error if device does not have a value and return null.
                MessageHelper.DisplayBasicMessage(StringResources.InitialisationError);
                return device;
            }

            device.Initialise(deviceInfo.Id);

            return device;
        }
        public async Task<int> ProjectAsync(Type viewType, DeviceInformation device = null)
        {
            int mainViewId = ApplicationView.GetForCurrentView().Id;
            int? secondViewId = null;

            var view = CoreApplication.CreateNewView();
            await view.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                secondViewId = ApplicationView.GetForCurrentView().Id;
                var rootFrame = new Frame();
                rootFrame.Navigate(viewType, null);
                Window.Current.Content = rootFrame;
                Window.Current.Activate();
            });

            if (secondViewId.HasValue)
            {
                if(device == null)
                    await ProjectionManager.StartProjectingAsync(secondViewId.Value, mainViewId);
                else
                    await ProjectionManager.StartProjectingAsync(secondViewId.Value, mainViewId, device);
            }

            return mainViewId;
        }
Example #5
0
 private void DeviceAdded(DeviceWatcher sender, DeviceInformation args)
 {
     if (ExternalDeviceAdded != null)
     {
         ExternalDeviceAdded(this, args.Id);
     }
 }
        /// <summary>
        /// Invoked when the device watcher detects that the proximity sensor was added.
        /// </summary>
        /// <param name="sender">The device watcher.</param>
        /// <param name="device">The device that was added.</param>
        private async void OnProximitySensorAddedAsync(DeviceWatcher sender, DeviceInformation device)
        {
            if (this.proximitySensor == null)
            {
                var addedSensor = ProximitySensor.FromId(device.Id);

                if (addedSensor != null)
                {
                    var minimumDistanceSatisfied = true;

                    //if we care about minimum distance
                    if (this.MinimumDistanceInMillimeters > Int32.MinValue)
                    {
                        if ((this.MinimumDistanceInMillimeters > addedSensor.MaxDistanceInMillimeters) ||
                            (this.MinimumDistanceInMillimeters < addedSensor.MinDistanceInMillimeters))
                        {
                            minimumDistanceSatisfied = false;
                        }
                    }

                    if (minimumDistanceSatisfied)
                    {
                        this.proximitySensor = addedSensor;

                        await SetActiveFromReadingAsync(this.proximitySensor.GetCurrentReading());

                        this.proximitySensor.ReadingChanged += ProximitySensor_ReadingChangedAsync;
                    }
                }
            }
        }
Example #7
0
        private HidGamepad(DeviceInformation deviceInformation, HidDevice device)
        {
            _deviceInformation = deviceInformation;

            _device = device;
            _device.InputReportReceived += HandleInputReportRecieved;
        }
 public UsbConnection(DeviceInformation deviceInfo)
 {
     UpdateRate = 1000;
     DevicePath = deviceInfo.Id;
     SerialNumber = DevicePath.Split('#')[2];
     Name = deviceInfo.Name;
 }
 /// <summary>
 /// Invoked when the device watcher finds a matching custom sensor device 
 /// </summary>
 /// <param name="watcher">device watcher</param>
 /// <param name="customSensorDevice">device information for the custom sensor that was found</param>
 public async void OnCustomSensorAdded(DeviceWatcher watcher, DeviceInformation customSensorDevice)
 {
     try
     {
         customSensor = await CustomSensor.FromIdAsync(customSensorDevice.Id);
         if (customSensor != null)
         {
             CustomSensorReading reading = customSensor.GetCurrentReading();
             if (!reading.Properties.ContainsKey(CO2LevelKey))
             {
                 rootPage.NotifyUser("The found custom sensor doesn't provide CO2 reading", NotifyType.ErrorMessage);
                 customSensor = null;
             }
         }
         else
         {
             rootPage.NotifyUser("No custom sensor found", NotifyType.ErrorMessage);
         }
     }
     catch (Exception e)
     {
         await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
         {
             rootPage.NotifyUser("The user may have denied access to the custom sensor. Error: " + e.Message, NotifyType.ErrorMessage);
         });
     }
 }
        /// <summary>
        /// Finds the GattDeviceService for a specified device by serviceUuid
        /// IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it.
        /// </summary>
        /// <returns>Returns the gatt device service of the first device that supports it. Returns null if access is denied.</returns>
        /// <exception cref="DeviceNotFoundException">Thrown if there isn't a device which provides the service Uuid.</exception>
        public async static Task<GattDeviceService> GetDeviceService(DeviceInformation device, string serviceUuid)
        {
            Validator.RequiresNotNullOrEmpty(serviceUuid, "serviceUuid");

            Validator.RequiresNotNull(device, "device");

            return await GattDeviceService.FromIdAsync(device.Id);
        }
Example #11
0
        private static async void HandleDeviceAdded(DeviceWatcher sender, DeviceInformation args)
        {
            var device = await HidDevice.FromIdAsync(args.Id, FileAccessMode.Read);
            var gamepad = new HidGamepad(args, device);

            _gamepads.Add(args.Id, gamepad);
            GamepadAdded?.Invoke(sender, gamepad);
        }
        /// <summary>
        /// Invoked when the device watcher finds a proximity sensor
        /// </summary>
        /// <param name="sender">The device watcher</param>
        /// <param name="device">Device information for the proximity sensor that was found</param>
        private async void OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device)
        {
            if (null == sensor)
            {
                ProximitySensor foundSensor = ProximitySensor.FromId(device.Id);
                if (null != foundSensor)
                {
                    if (null != foundSensor.MaxDistanceInMillimeters)
                    {
                        // Check if this is the sensor that matches our ranges.

                        // TODO: Customize these values to your application's needs.
                        // Here, we are looking for a sensor that can detect close objects
                        // up to 3cm away, so we check the upper bound of the detection range.
                        const uint distanceInMillimetersLValue = 30; // 3 cm
                        const uint distanceInMillimetersRValue = 50; // 5 cm

                        if (foundSensor.MaxDistanceInMillimeters >= distanceInMillimetersLValue &&
                            foundSensor.MaxDistanceInMillimeters <= distanceInMillimetersRValue)
                        {
                            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                            {
                                rootPage.NotifyUser("Found a proximity sensor that meets the detection range", NotifyType.StatusMessage);
                            });
                        }
                        else
                        {
                            // We'll use the sensor anyway, to demonstrate how events work.
                            // Your app may decide not to use the sensor.
                            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                            {
                                rootPage.NotifyUser("Proximity sensor does not meet the detection range, using it anyway", NotifyType.StatusMessage);
                            });
                        }
                    }
                    else
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            rootPage.NotifyUser("Proximity sensor does not report detection ranges, using it anyway", NotifyType.StatusMessage);
                        });
                    }

                    if (null != foundSensor)
                    {
                        sensor = foundSensor;
                    }
                }
                else
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        rootPage.NotifyUser("Could not get a proximity sensor from the device id", NotifyType.ErrorMessage);
                    });
                }
            }
        }
 private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
 {
     await coreDispatcher.RunAsync(
         CoreDispatcherPriority.Normal,
         () =>
         {
             FoundDeviceList.Add(args);
         });
 }
        private void DeviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DeviceList.SelectedIndex > -1)
            {
                _selectedDevice = (DeviceList.SelectedItem as DeviceViewModel).Information;
                _owner.OnDeviceSelected(_selectedDevice);

                Hide();
            }
        }
Example #15
0
 private async void CameraSelectionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     string selectedCameraItem = e.AddedItems.FirstOrDefault().ToString();
     foreach (DeviceInformation item in _allVideoDevices)
     {
         if (string.Equals(item.Name, selectedCameraItem))
         {
             _desiredDevice = item;
             await StartDeviceAsync();
         }
     }
 }
        private async void StartProjecting(DeviceInformation selectedDisplay)
        {
            // If projection is already in progress, then it could be shown on the monitor again
            // Otherwise, we need to create a new view to show the presentation
            if (rootPage.ProjectionViewPageControl == null)
            {
                // First, create a new, blank view
                var thisDispatcher = Window.Current.Dispatcher;
                await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // ViewLifetimeControl is a wrapper to make sure the view is closed only
                    // when the app is done with it
                    rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();

                    // Assemble some data necessary for the new page
                    var initData = new ProjectionViewPageInitializationData();
                    initData.MainDispatcher = thisDispatcher;
                    initData.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
                    initData.MainViewId = thisViewId;

                    // Display the page in the view. Note that the view will not become visible
                    // until "StartProjectingAsync" is called
                    var rootFrame = new Frame();
                    rootFrame.Navigate(typeof(ProjectionViewPage), initData);
                    Window.Current.Content = rootFrame;

                    // The call to Window.Current.Activate is required starting in Windos 10.
                    // Without it, the view will never appear.
                    Window.Current.Activate();
                });
            }

            try
            {
                // Start/StopViewInUse are used to signal that the app is interacting with the
                // view, so it shouldn't be closed yet, even if the user loses access to it
                rootPage.ProjectionViewPageControl.StartViewInUse();

                // Show the view on a second display that was selected by the user
                rootPage.NotifyUser("Starting projection on " + selectedDisplay.Name, NotifyType.StatusMessage);
                await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, selectedDisplay);

                rootPage.NotifyUser("Projection started with success on " + selectedDisplay.Name, NotifyType.StatusMessage);
                rootPage.ProjectionViewPageControl.StopViewInUse();
            }
            catch (InvalidOperationException)
            {
                rootPage.NotifyUser("Start projection failed", NotifyType.ErrorMessage);
            }
        }
        private MediaCaptureInitializationSettings InitCaptureSettings(DeviceInformation device)
        {
            MediaCaptureInitializationSettings captureInitSettings = new MediaCaptureInitializationSettings();
            captureInitSettings.AudioDeviceId = "";
            captureInitSettings.VideoDeviceId = device.Id;

            captureInitSettings.StreamingCaptureMode = settings.IsVolumeOn
                ? StreamingCaptureMode.AudioAndVideo
                : StreamingCaptureMode.Video;

            captureInitSettings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview;

            return captureInitSettings;
        }
        public static ConnectedDeviceDefinition GetDeviceInformation(wde.DeviceInformation deviceInformation, DeviceType deviceType)
        {
            var retVal = WindowsDeviceFactoryBase.GetDeviceDefinitionFromWindowsDeviceId(deviceInformation.Id, deviceType);

            //foreach (var keyValuePair in deviceInformation.Properties)
            //{
            //    if (keyValuePair.Key == ProductNamePropertyName) retVal.ProductName = (string)keyValuePair.Value;
            //    System.Diagnostics.Debug.WriteLine($"{keyValuePair.Key} {keyValuePair.Value}");
            //}

            retVal.ProductName = deviceInformation.Name;

            return(retVal);
        }
        public UwpHidDeviceInformation([NotNull] UwpHidDeviceFactory factory, [NotNull] DeviceInformation deviceInformation)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            if (deviceInformation == null)
            {
                throw new ArgumentNullException(nameof(deviceInformation));
            }

            this.factory = factory;
            this.deviceInformation = deviceInformation;
        }
Example #20
0
        private void watcher_Added(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformation args)
        {
            string name = GetPortableDeviceName(args.Id);
            string type = GetPortableDeviceType(args.Id);

            if (!deviceTypeList.ContainsKey(name))
            {
                deviceTypeList.Add(GetPortableDeviceName(args.Id), GetPortableDeviceType(args.Id));
            }
            this.BeginInvoke((Action)(() =>
            {
                //perform on the UI thread
                PrintDrives();
            }));
        }
 /// <summary>
 /// Invoked when the device watcher finds a proximity sensor
 /// </summary>
 /// <param name="sender">The device watcher</param>
 /// <param name="device">Device information for the proximity sensor that was found</param>
 private async void OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device)
 {
     if (null == sensor)
     {
         sensor = ProximitySensor.FromId(device.Id);
         if (null == sensor)
         {
             // failed to find the sensor corresponding to the id
             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 rootPage.NotifyUser("Could not get a proximity sensor from the device id", NotifyType.ErrorMessage);
             });
         }
     }
 }
        private async void Picker_DisconnectButtonClicked(DialDevicePicker sender, DialDisconnectButtonClickedEventArgs args)
        {
            // casting 必須在 UI Thread 下執行
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                try
                {                    
                    // 取得被選擇的 dial device
                    DialDevice selectedDialDevice = await DialDevice.FromIdAsync(args.Device.Id);
                    // 更新 picker status
                    picker.SetDisplayStatus(selectedDialDevice, DialDeviceDisplayStatus.Connecting);
                    // 取得 dial app 
                    DialApp app = selectedDialDevice.GetDialApp(txtAppName.Text);
                  
                    // 請求斷綫
                    DialAppStopResult result = await app.StopAsync();

                    if (result == DialAppStopResult.Stopped)
                    {
                        picker.SetDisplayStatus(args.Device, DialDeviceDisplayStatus.Disconnected);
                        activeDialDevice = null;
                        activeDeviceInformation = null;
                        picker.Hide();
                        tblMsg.Text += "Stoped, success";
                    }
                    else
                    {
                        if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
                        {
                            // 如果失敗的話要記得多 retry 的機制
                            picker.SetDisplayStatus(args.Device, DialDeviceDisplayStatus.Error);
                            tblMsg.Text += $"Stoped, {result}";
                        }
                        else
                        {
                            // 如果設備沒有支援 Stop 機制,則直接清楚連綫就好
                            activeDialDevice = null;
                            activeDeviceInformation = null;
                            tblMsg.Text += "the device does not support Stop";
                        }
                    }
                }
                catch (Exception ex)
                {
                    tblMsg.Text += ex.Message;
                }
            });
        }
        /// <summary>
        /// Retrieves the sensors GATT device service from a specified DeviceInformation and saves it for further usage.
        /// IMPORTANT: Has to be called from UI thread the first time the app uses the device to be able to ask the user for permission to use it
        /// </summary>
        /// <returns>Indicates if the gatt service could be retrieved and set successfully</returns>
        public async Task<bool> Initialize(DeviceInformation deviceInfo)
        {
            Validator.RequiresNotNull(deviceInfo);
            if (!deviceInfo.Id.Contains(SensorServiceUuid))
                throw new ArgumentException("Wrong DeviceInformation passed. You need to get the right DeviceInformation via SPECIFICSENSORCLASS.SensorServiceUuid.");

            if (this.deviceService != null)
            {
                Clean();
            }

            this.deviceService = await GattDeviceService.FromIdAsync(deviceInfo.Id);
            if (this.deviceService == null)
                return false;
            return true;
        }
Example #24
0
        static private async void DeviceWatcher_Added(DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformation deviceInfo)
        {
            Debug.WriteLine(String.Format("Added {0}{1}", deviceInfo.Id, deviceInfo.Name));

            // Protect against race condition if the task runs after the app stopped the deviceWatcher.
            if (sender == deviceWatcher)
            {
                CSLibrary.DeviceFinder.DeviceInfomation di = new CSLibrary.DeviceFinder.DeviceInfomation();
                di.deviceName = deviceInfo.Name;
                di.ID         = (uint)_deviceDB.Count;
                di.nativeDeviceInformation = (object)deviceInfo;

                _deviceDB.Add(deviceInfo);

                RaiseEvent <DeviceFinderArgs>(OnSearchCompleted, new DeviceFinderArgs(di));
            }
        }
 /// <summary>
 /// Invoked when the device watcher finds a proximity sensor
 /// </summary>
 /// <param name="sender">The device watcher</param>
 /// <param name="device">Device information for the proximity sensor that was found</param>
 private async void OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device)
 {
     if (null == sensor)
     {
         ProximitySensor foundSensor = ProximitySensor.FromId(device.Id);
         if (null != foundSensor)
         {
             sensor = foundSensor;
         }
         else
         {
             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 rootPage.NotifyUser("Could not get a proximity sensor from the device id", NotifyType.ErrorMessage);
             });
         }
     }
 }
Example #26
0
 private static void GetBtDevicesAndList()
 {
     IReadOnlyList<string> list= new List<string>();
     Console.WriteLine("Start Get Devices");
     var bts = DeviceInformation.FindAllAsync(); // .FindAllAsync().GetResults();
     do
     {
         Thread.Sleep(100);
     } while (bts.Status != AsyncStatus.Completed);
     var i = 0;
     foreach (var di in bts.GetResults())
     {
         i++;
         if (di.Name == deviceName)
             _parrot = di;
     }
     Console.WriteLine("{0} Devices Found", i);
 }
Example #27
0
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                try
                {
                    // Set status to Connecting
                    picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);

                    // Getting the selected device improves debugging
                    DeviceInformation selectedDevice = args.SelectedDevice;
                    try
                    {
                        await ProjectionManager.StartProjectingAsync(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()), thisViewId, selectedDevice);

                    }
                    catch (Exception ex)
                    {
                        if (!ProjectionManager.ProjectionDisplayAvailable)
                            throw ex;
                    }

                    try
                    {
                        
                            activeDevice = selectedDevice;
                        
                            // Set status to Connected
                            picker.SetDisplayStatus(args.SelectedDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                            picker.Hide();
                    }
                    catch (Exception)
                    {
                        try { picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
                    }
                }
                catch (Exception ex)
                {
                    
                }
            });
        }
Example #28
0
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (ButtonLoad.Content.ToString() == "Connect ...")
            {
                await SuscribeToHrValues();
                await DisplayBatteryLevel();
                DeviceFoundMessage = $@"[{_devicePolarHr.Name}]
Connected";
                ButtonLoad.Content = "Disconnect ...";
            }
            else
            {
                ButtonLoad.Content = "Connect ...";
                BatteryValue = "";
                DeviceFoundMessage = "";
                _devicePolarHr = null;
                _devicePolarBattery = null;
            }
        }
        private async void ConnectToDevice()
        {
            foreach(var item in deviceCollection)
            {
                if (item.Name == deviceName)
                {
                    selectedDevice = item;
                    break;
                }
            }

            if (selectedDevice == null)
            {
                errorStatus.Visibility = Visibility.Visible;
                errorStatus.Text = "Cannot find the device specified; Please check the device name";
                return;
            }
            else
            {
                deviceService = await RfcommDeviceService.FromIdAsync(selectedDevice.Id);

                if (deviceService != null)
                {
                    //connect the socket   
                    try
                    {
                        await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName);
                    }
                    catch (Exception ex)
                    {
                        errorStatus.Visibility = Visibility.Visible;
                        errorStatus.Text = "Cannot connect bluetooth device:" + ex.Message;
                    }

                }
                else
                {
                    errorStatus.Visibility = Visibility.Visible;
                    errorStatus.Text = "Didn't find the specified bluetooth device";
                }
            }
           
        }
Example #30
0
        public static ConnectedDeviceDefinition GetDeviceInformation(wde.DeviceInformation deviceInformation, DeviceType deviceType, ILogger logger)
        {
            if (deviceInformation == null)
            {
                throw new ArgumentNullException(nameof(deviceInformation));
            }

            var retVal = WindowsDeviceFactoryBase.GetDeviceDefinitionFromWindowsDeviceId(deviceInformation.Id, deviceType, logger);

            //foreach (var keyValuePair in deviceInformation.Properties)
            //{
            //    if (keyValuePair.Key == ProductNamePropertyName) retVal.ProductName = (string)keyValuePair.Value;
            //    System.Diagnostics.Debug.WriteLine($"{keyValuePair.Key} {keyValuePair.Value}");
            //}

            retVal.ProductName = deviceInformation.Name;

            return(retVal);
        }
 /// <summary>
 /// Invoked when the device watcher finds a proximity sensor
 /// </summary>
 /// <param name="sender">The device watcher</param>
 /// <param name="device">Device information for the proximity sensor that was found</param>
 private async void OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device)
 {
     if (null == sensor)
     {
         ProximitySensor foundSensor = ProximitySensor.FromId(device.Id);
         if (null != foundSensor)
         {
             // Optionally check the ProximitySensor.MaxDistanceInCentimeters/MinDistanceInCentimeters
             // properties here. Refer to Scenario 1 for details.
             sensor = foundSensor;
         }
         else
         {
             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 rootPage.NotifyUser("Could not get a proximity sensor from the device id", NotifyType.ErrorMessage);
             });
         }
     }
 }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // Request the right to have background tasks run in the future. This need only be done once
            // after the app is installed, but it is harmless to do it every time the app is launched.
            if (await BackgroundExecutiondManager.RequestAccessAsync() == BackgroundAccessStatus.Denied)
            {
                // TODO: What?
            }

            // Acquire the set of background tasks that we already have registered. Store them into a dictionary, keyed
            // by task name. (For each LE device, we will use a task name that is derived from its Bluetooth address).
            Dictionary <string, BackgroundTaskRegistration> taskRegistrations = new Dictionary <string, BackgroundTaskRegistration>();

            foreach (BackgroundTaskRegistration reg in BackgroundTaskRegistration.AllTasks.Values)
            {
                taskRegistrations[reg.Name] = reg;
            }


            // Get the list of paired Bluetooth LE devicdes, and add them to our 'devices' list. Associate each device with
            // its pre-existing registration if any, and remove that registration from our dictionary.
            Devices.Clear();
            foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()))
            {
                BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id);

                SmartPack device = new SmartPack(bleDevice);
                if (taskRegistrations.ContainsKey(device.TaskName))
                {
                    device.TaskRegistration = taskRegistrations[device.TaskName];
                    taskRegistrations.Remove(device.TaskName);
                }
                Devices.Add(device);
            }
            // Unregister any remaining background tasks that remain in our dictionary. These are tasks that we registered
            // for Bluetooth LE devices that have since been unpaired.
            foreach (BackgroundTaskRegistration reg in taskRegistrations.Values)
            {
                reg.Unregister(false);
            }
        }
Example #33
0
        /// <summary>
        /// Connect to the device
        /// </summary>
        /// <param name="portName">the name of the device to connect.</param>
        public override async void Connect(string portName = null)
        {
            if (this.Connected)
                return;

            try
            {
                this._currentDevice = (await this.AvailableDevicesAsync()).SingleOrDefault(d => d.Name == portName);
                this._socket = new StreamSocket();
                this._rfcommService = await RfcommDeviceService.FromIdAsync(this._currentDevice.Id);
                await this._socket.ConnectAsync(this._rfcommService.ConnectionHostName, this._rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
                this._writer = new DataWriter(this._socket.OutputStream);
                this._reader = new DataReader(this._socket.InputStream);
                this._connected = true;

                this.DataReceivedAsync();
            }
            catch
            {
                this._connected = false;
            }
        }
        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);
            }

        }
        /// <summary>
        /// comPortInput_Click: Action to take when 'Connect' button is clicked
        /// - Get the selected device index and use Id to create the SerialDevice object
        /// - Configure default settings for the serial port
        /// - Create the ReadCancellationTokenSource token
        /// - Start listening on the serial port input
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void SelectDevice(DeviceInformation device)
        {
            try
            {
                serialPort = await SerialDevice.FromIdAsync(device.Id);

                // Configure serial settings
                serialPort.BaudRate = 9600;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;

                // Create cancellation token object to close I/O operations when closing the device
                ReadCancellationTokenSource = new CancellationTokenSource();

                _streamReader = new InputStreamReader(serialPort.InputStream, 31);
                _streamReader.OnLineRead += OnLineRead;
                _streamReader.StartReading();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        /// <summary>
        /// Invoked when the device watcher finds a matching custom sensor device 
        /// </summary>
        /// <param name="watcher">device watcher</param>
        /// <param name="customSensorDevice">device information for the custom sensor that was found</param>
        public async void OnCustomSensorAdded(DeviceWatcher watcher, DeviceInformation customSensorDevice)
        {
            try
            {
                customSensor = await CustomSensor.FromIdAsync(customSensorDevice.Id);
                if (customSensor != null)
                {
                    CustomSensorReading reading = customSensor.GetCurrentReading();
                    if (!reading.Properties.ContainsKey(CO2LevelKey))
                    {
                        rootPage.NotifyUser("The found custom sensor doesn't provide CO2 reading", NotifyType.ErrorMessage);
                        customSensor = null;
                    }
                    else
                    {
                        // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                        // This value will be used later to activate the sensor.
                        // In the case below, we defined a 200ms report interval as being suitable for the purpose of this app.
                        UInt32 minReportInterval = customSensor.MinimumReportInterval;
                        desiredReportInterval = minReportInterval > 200 ? minReportInterval : 200;
                    }

                }
                else
                {
                    rootPage.NotifyUser("No custom sensor found", NotifyType.ErrorMessage);
                }
            }
            catch(Exception e)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("The user may have denied access to the custom sensor. Error: " + e.Message, NotifyType.ErrorMessage);
                });
            }
        }
 /// <summary>
 /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
 /// </summary>
 /// <param name="deviceInformation"></param>
 public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation)
 {
     device = deviceInformation;
 }
 /// <summary>
 /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
 /// </summary>
 /// <param name="deviceInformation"></param>
 /// <param name="deviceSelector">The AQS used to find this device</param>
 public UsbDeviceInformation(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector)
 {
     device = deviceInformation;
     this.deviceSelector = deviceSelector;
 }
Example #39
0
 /// <summary>
 /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
 /// </summary>
 /// <param name="deviceInformation"></param>
 /// <param name="deviceSelector">The AQS used to find this device</param>
 public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector)
 {
     device = deviceInformation;
     this.deviceSelector = deviceSelector;
 }
Example #40
0
 public DeviceViewModel(Windows.Devices.Enumeration.DeviceInformation information)
 {
     _information = information;
 }
Example #41
0
 /// <summary>
 /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
 /// </summary>
 /// <param name="deviceInformation"></param>
 /// <param name="deviceSelector">The AQS used to find this device</param>
 public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector)
 {
     device = deviceInformation;
     this.deviceSelector = deviceSelector;
     //  ecsBoxDetected = Is_ECS_BOX();
 }
Example #42
0
 private void InputWatcher_Added(DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformation args)
 {
     SetDevice();
 }