Exemplo n.º 1
0
        public void AvailableDevices_should_remain_sorted_by_path_when_new_device_becomes_available(
                [Values("1", "3", "5")] string newDevicePath
            )
        {
            // Assign
            var devices = new List<DeviceInformation>
            {
                new DeviceInformation("2"),
                new DeviceInformation("4"),
            };

            var deviceManager = Substitute.For<IDeviceManager>();
            deviceManager.EnumerateAllDevices().Returns(devices);

            var monitor = new DeviceMonitor(deviceManager, string.Empty);

            var newDevice = new DeviceInformation(newDevicePath);
            devices.Add(newDevice);

            // Act
            deviceManager.DeviceChanged += Raise.EventWith(new DeviceChangeArgs(DeviceChange.Added, newDevice.Path));

            // Assert
            monitor.AvailableDevices
                .Should().Contain(devices, newDevice);
            monitor.AvailableDevices
                .Select(d => d.Path).Should().BeInAscendingOrder();
        }
Exemplo n.º 2
0
 private Device CreateDevice(DeviceInformation deviceInformation)
 {
   return new Device
          {
            Title = string.Join(", ", deviceInformation.DeviceVendor, deviceInformation.DeviceModelName),
            Browser = deviceInformation.Browser
          };
 }
Exemplo n.º 3
0
 void InsertDeviceInfo(DeviceInformation deviceInfo)
 {
     int insertIndex = AvailableDevices.Count;
     for (int i = 0; i < AvailableDevices.Count; ++i)
     {
         if (string.Compare(AvailableDevices[i].Path, deviceInfo.Path, StringComparison.InvariantCultureIgnoreCase) > 0)
         {
             insertIndex = i;
             break;
         }
     }
     AvailableDevices.Insert(insertIndex, deviceInfo);
 }
Exemplo n.º 4
0
        private void StartWatcher()
        {
            startWatcherButton.IsEnabled = false;
            ResultCollection.Clear();

            // First get the device selector chosen by the UI.
            DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;

            if (null == deviceSelectorInfo.Selector)
            {
                // If the a pre-canned device class selector was chosen, call the DeviceClass overload
                deviceWatcher = DeviceInformation.CreateWatcher(deviceSelectorInfo.DeviceClassSelector);
            }
            else if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
            {
                // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
                // Kind will be determined by the selector
                deviceWatcher = DeviceInformation.CreateWatcher(
                    deviceSelectorInfo.Selector,
                    null // don't request additional properties for this sample
                    );
            }
            else
            {
                // Kind is specified in the selector info
                deviceWatcher = DeviceInformation.CreateWatcher(
                    deviceSelectorInfo.Selector,
                    null, // don't request additional properties for this sample
                    deviceSelectorInfo.Kind);
            }

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Watcher {1}.",
                                      ResultCollection.Count,
                                      DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
            deviceWatcher.Start();
            stopWatcherButton.IsEnabled = true;
        }
Exemplo n.º 5
0
        private void StartWatcher()
        {
            startWatcherButton.IsEnabled = false;
            ResultCollection.Clear();

            // Get the device selector chosen by the UI then add additional constraints for devices that
            // can be paired or are already paired.
            DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
            //string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
            string selector = deviceSelectorInfo.Selector;

            if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
            {
                // Kind will be determined by the selector
                deviceWatcher = DeviceInformation.CreateWatcher(
                    selector,
                    null // don't request additional properties for this sample
                    );
            }
            else
            {
                // Kind is specified in the selector info
                deviceWatcher = DeviceInformation.CreateWatcher(
                    selector,
                    null, // don't request additional properties for this sample
                    deviceSelectorInfo.Kind);
            }

            // Hook up handlers for the watcher events before starting the watcher

            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);

                            // If the item being updated is currently "selected", then update the pairing buttons
                            DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
                            if (deviceInfoDisp == selectedDeviceInfoDisp)
                            {
                                UpdatePairingButtons();
                            }
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }

                    rootPage.NotifyUser(
                        String.Format("{0} devices found.", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    rootPage.NotifyUser(
                        String.Format("{0} devices found. Watcher {1}.",
                                      ResultCollection.Count,
                                      DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
                        NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Stopped += handlerStopped;

            rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
            deviceWatcher.Start();
            stopWatcherButton.IsEnabled = true;
        }
 private void OnNewDeviceDiscovered(DeviceWatcher sender, DeviceInformation info)
 {
     _discoveredDevices.Add(new Device(info));
 }
Exemplo n.º 7
0
        public async Task SendHeartbeat()
        {
            var currentInfo = await DeviceInformation.Create(ConnectionInfo.DeviceID, ConnectionInfo.OrganizationID);

            await HubConnection.SendAsync("DeviceHeartbeat", currentInfo);
        }
Exemplo n.º 8
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                            // Relay.
                        this.arduino.digitalWrite(9, 0);                                    // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                         // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            this.PublishMotion(value == PinState.HIGH);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty);
                //this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty, new LogSniffer());
                this.mqttClient.OnStateChanged += (sender, state) =>
                {
                    Log.Informational("MQTT client state changed: " + state.ToString());
                    return(Task.CompletedTask);
                };
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Exemplo n.º 9
0
 public IDeviceStream OpenDeviceStream(DeviceInformation deviceInfo)
 {
     Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(deviceInfo.Path));
     Contract.Ensures(Contract.Result<IDeviceStream>() != null);
     return null;
 }
Exemplo n.º 10
0
 internal AudioDeviceInfo(DeviceInformation info)
 {
     this.info = info;
 }
Exemplo n.º 11
0
        public static void ParseTextForDeviceInformation(string text, List<DeviceInformation> deviceInformation)
        {
            List<string> deviceBlob = text.Split('|').ToList();
            deviceBlob.RemoveAt(0);

            foreach (string deviceText in deviceBlob)
            {
                if (deviceText == "\0")
                    continue;

                //bfgminer may have multiple entries for the same key, e.g. Hardware Errors
                //seen with customer data/hardware
                //remove dupes using Distinct()
                var deviceAttributes = deviceText.Split(',').ToList().Distinct();

                Dictionary<string, string> keyValuePairs = deviceAttributes
                  .Where(value => value.Contains('='))
                  .Select(value => value.Split('='))
                  .ToDictionary(pair => pair[0], pair => pair[1]);

                //seen Count == 0 with user API logs
                if (keyValuePairs.Count > 0)
                {
                    DeviceInformation newDevice = new DeviceInformation();

                    newDevice.Kind = keyValuePairs.ElementAt(0).Key;
                    newDevice.Index = int.Parse(keyValuePairs[newDevice.Kind]);
                    newDevice.Enabled = keyValuePairs["Enabled"].Equals("Y");
                    newDevice.Status = keyValuePairs["Status"];

                    //the RPC API returns numbers formatted en-US, e.g. 1,000.00
                    //specify CultureInfo.InvariantCulture for parsing or unhandled exceptions will
                    //occur on other locales
                    //can test for this with:
                    //Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");
                    //Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");

                    if (newDevice.Kind.Equals("GPU"))
                    {
                        if (keyValuePairs.ContainsKey("Temperature")) //check required for bfgminer
                            newDevice.Temperature = double.Parse(keyValuePairs["Temperature"], CultureInfo.InvariantCulture);
                        newDevice.FanSpeed = int.Parse(keyValuePairs["Fan Speed"], CultureInfo.InvariantCulture);
                        newDevice.FanPercent = int.Parse(keyValuePairs["Fan Percent"], CultureInfo.InvariantCulture);
                        newDevice.GpuClock = int.Parse(keyValuePairs["GPU Clock"], CultureInfo.InvariantCulture);
                        newDevice.MemoryClock = int.Parse(keyValuePairs["Memory Clock"], CultureInfo.InvariantCulture);
                        newDevice.GpuVoltage = double.Parse(keyValuePairs["GPU Voltage"], CultureInfo.InvariantCulture);
                        newDevice.GpuActivity = int.Parse(keyValuePairs["GPU Activity"], CultureInfo.InvariantCulture);
                        newDevice.PowerTune = int.Parse(keyValuePairs["Powertune"], CultureInfo.InvariantCulture);
                        newDevice.Intensity = keyValuePairs["Intensity"];
                    }

                    newDevice.AverageHashrate = double.Parse(keyValuePairs["MHS av"], CultureInfo.InvariantCulture) * 1000;

                    //seen both MHS 5s and MHS 1s
                    if (keyValuePairs.ContainsKey("MHS 5s"))
                        newDevice.CurrentHashrate = double.Parse(keyValuePairs["MHS 5s"], CultureInfo.InvariantCulture) * 1000;
                    else if (keyValuePairs.ContainsKey("MHS 1s"))
                        newDevice.CurrentHashrate = double.Parse(keyValuePairs["MHS 1s"], CultureInfo.InvariantCulture) * 1000;

                    newDevice.AcceptedShares = int.Parse(keyValuePairs["Accepted"], CultureInfo.InvariantCulture);
                    newDevice.RejectedShares = int.Parse(keyValuePairs["Rejected"], CultureInfo.InvariantCulture);
                    newDevice.HardwareErrors = int.Parse(keyValuePairs["Hardware Errors"], CultureInfo.InvariantCulture);
                    newDevice.Utility = double.Parse(keyValuePairs["Utility"], CultureInfo.InvariantCulture);

                    deviceInformation.Add(newDevice);
                }
            }
        }
Exemplo n.º 12
0
 public DiscoveredDevice(DeviceInformation deviceInfo)
 {
     DeviceInfo = deviceInfo;
 }
Exemplo n.º 13
0
        public async void Refresh_Click(object sender, RoutedEventArgs e)
        {
            if (Interlocked.Exchange(ref LockResource, 1) == 0)
            {
                try
                {
                    CommonAccessCollection.HardDeviceList.Clear();

                    foreach (DriveInfo Drive in DriveInfo.GetDrives().Where((Drives) => Drives.DriveType == DriveType.Fixed || Drives.DriveType == DriveType.Removable)
                             .Where((NewItem) => CommonAccessCollection.HardDeviceList.All((Item) => Item.Folder.Path != NewItem.RootDirectory.FullName)))
                    {
                        try
                        {
                            StorageFolder Device = await StorageFolder.GetFolderFromPathAsync(Drive.RootDirectory.FullName);

                            BasicProperties Properties = await Device.GetBasicPropertiesAsync();

                            IDictionary <string, object> PropertiesRetrieve = await Properties.RetrievePropertiesAsync(new string[] { "System.Capacity", "System.FreeSpace", "System.Volume.FileSystem", "System.Volume.BitLockerProtection" });

                            CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(Device, await Device.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, Drive.DriveType));
                        }
                        catch (Exception ex)
                        {
                            LogTracer.Log(ex, $"Hide the device \"{Drive.RootDirectory.FullName}\" for error");
                        }
                    }

                    foreach (DeviceInformation Device in await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector()))
                    {
                        try
                        {
                            StorageFolder DeviceFolder = StorageDevice.FromId(Device.Id);

                            if (CommonAccessCollection.HardDeviceList.All((Item) => (string.IsNullOrEmpty(Item.Folder.Path) || string.IsNullOrEmpty(DeviceFolder.Path)) ? Item.Folder.Name != DeviceFolder.Name : Item.Folder.Path != DeviceFolder.Path))
                            {
                                BasicProperties Properties = await DeviceFolder.GetBasicPropertiesAsync();

                                IDictionary <string, object> PropertiesRetrieve = await Properties.RetrievePropertiesAsync(new string[] { "System.Capacity", "System.FreeSpace", "System.Volume.FileSystem", "System.Volume.BitLockerProtection" });

                                if (PropertiesRetrieve["System.Capacity"] is ulong && PropertiesRetrieve["System.FreeSpace"] is ulong)
                                {
                                    CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, DriveType.Removable));
                                }
                                else
                                {
                                    IReadOnlyList <IStorageItem> InnerItemList = await DeviceFolder.GetItemsAsync(0, 2);

                                    if (InnerItemList.Count == 1 && InnerItemList[0] is StorageFolder InnerFolder)
                                    {
                                        BasicProperties InnerProperties = await InnerFolder.GetBasicPropertiesAsync();

                                        IDictionary <string, object> InnerPropertiesRetrieve = await InnerProperties.RetrievePropertiesAsync(new string[] { "System.Capacity", "System.FreeSpace", "System.Volume.FileSystem", "System.Volume.BitLockerProtection" });

                                        if (InnerPropertiesRetrieve["System.Capacity"] is ulong && InnerPropertiesRetrieve["System.FreeSpace"] is ulong)
                                        {
                                            CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), InnerPropertiesRetrieve, DriveType.Removable));
                                        }
                                        else
                                        {
                                            CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, DriveType.Removable));
                                        }
                                    }
                                    else
                                    {
                                        CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, DriveType.Removable));
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogTracer.Log(ex, $"Hide the device \"{Device.Name}\" for error");
                        }
                    }
                }
                finally
                {
                    _ = Interlocked.Exchange(ref LockResource, 0);
                }
            }
        }
Exemplo n.º 14
0
        async Task InitializeCameraAsync()
        {
            if (mediaCapture == null)
            {
                DeviceInformation cameraDevice = null;
                var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                if (cameraOptions == CameraOptions.Rear)
                {
                    cameraDevice = devices.FirstOrDefault(c => c.EnclosureLocation != null && c.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
                }
                else
                {
                    cameraDevice = devices.FirstOrDefault(c => c.EnclosureLocation != null && c.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
                }

                if (cameraDevice == null)
                {
                    Debug.WriteLine("No camera found");
                    return;
                }

                mediaCapture = new MediaCapture();

                try
                {
                    await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
                    {
                        VideoDeviceId        = cameraDevice.Id,
                        AudioDeviceId        = string.Empty,
                        StreamingCaptureMode = StreamingCaptureMode.Video,
                        PhotoCaptureSource   = PhotoCaptureSource.Photo
                    });

                    isInitialized = true;
                }

                catch (UnauthorizedAccessException)
                {
                    Debug.WriteLine("Camera access denied");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception initializing MediaCapture - {0}: {1}", cameraDevice.Id, ex.ToString());
                }

                if (isInitialized)
                {
                    if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
                    {
                        externalCamera = true;
                    }
                    else
                    {
                        // Camera is on device
                        externalCamera = false;

                        // Mirror preview if camera is on front panel
                        mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
                    }
                    await StartPreviewAsync();
                }
            }
        }
Exemplo n.º 15
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(Lwm2mClient).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                       Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                            // Relay.
                        this.arduino.digitalWrite(9, 0);                                    // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                         // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            bool Input = (value == PinState.HIGH);
                            this.lastMotion = Input;
                            this.digitalInput0?.Set(Input);
                            this.presenceSensor0?.Set(Input);
                            this.genericSensor0?.Set(Input ? 1.0 : 0.0);
                            this.motionResource?.TriggerAll();
                            this.momentaryResource?.TriggerAll();
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                //this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                //	new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.coapEndpoint = new CoapEndpoint(new int[] { 5783 }, new int[] { 5784 }, null, null,
                                                     false, false);

                this.lightResource = this.coapEndpoint.Register("/Light", (req, resp) =>
                {
                    string s;

                    if (this.lastLight.HasValue)
                    {
                        s = ToString(this.lastLight.Value, 2) + " %";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Unacknowledged, "Light, in %.", null, null,
                                                                new int[] { PlainText.ContentFormatCode });

                this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.motionResource = this.coapEndpoint.Register("/Motion", (req, resp) =>
                {
                    string s;

                    if (this.lastMotion.HasValue)
                    {
                        s = this.lastMotion.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Acknowledged, "Motion detector.", null, null,
                                                                 new int[] { PlainText.ContentFormatCode });

                this.motionResource?.TriggerAll(new TimeSpan(0, 1, 0));

                this.momentaryResource = this.coapEndpoint.Register("/Momentary", (req, resp) =>
                {
                    if (req.IsAcceptable(Xml.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }
                    else if (req.IsAcceptable(Json.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsJson(req, resp);
                    }
                    else if (req.IsAcceptable(PlainText.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                    else if (req.Accept.HasValue)
                    {
                        throw new CoapException(CoapCode.NotAcceptable);
                    }
                    else
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                }, Notifications.Acknowledged, "Momentary values.", null, null,
                                                                    new int[] { Xml.ContentFormatCode, Json.ContentFormatCode, PlainText.ContentFormatCode });

                this.momentaryResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.lwm2mClient = new Lwm2mClient("MIoT:Sensor:" + this.deviceId, this.coapEndpoint,
                                                   new Lwm2mSecurityObject(),
                                                   new Lwm2mServerObject(),
                                                   new Lwm2mAccessControlObject(),
                                                   new Lwm2mDeviceObject("Waher Data AB", "SensorLwm2m", this.deviceId, "1.0", "Sensor", "1.0", "1.0"),
                                                   new DigitalInput(this.digitalInput0           = new DigitalInputInstance(0, this.lastMotion, "Motion Detector", "PIR")),
                                                   new AnalogInput(this.analogInput0             = new AnalogInputInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor", "%")),
                                                   new GenericSensor(this.genericSensor0         = new GenericSensorInstance(0, null, string.Empty, 0, 1, "Motion Detector", "PIR"),
                                                                     this.genericSensor1         = new GenericSensorInstance(1, this.lastLight, "%", 0, 100, "Ambient Light Sensor", "%")),
                                                   new IlluminanceSensor(this.illuminanceSensor0 = new IlluminanceSensorInstance(0, this.lastLight, "%", 0, 100)),
                                                   new PresenceSensor(this.presenceSensor0       = new PresenceSensorInstance(0, this.lastMotion, "PIR")),
                                                   new PercentageSensor(this.percentageSensor0   = new PercentageSensorInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor")));

                await this.lwm2mClient.LoadBootstrapInfo();

                this.lwm2mClient.OnStateChanged += (sender, e) =>
                {
                    Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + ".");
                };

                this.lwm2mClient.OnBootstrapCompleted += (sender, e) =>
                {
                    Log.Informational("Bootstrap procedure completed.");
                };

                this.lwm2mClient.OnBootstrapFailed += (sender, e) =>
                {
                    Log.Error("Bootstrap procedure failed.");

                    this.coapEndpoint.ScheduleEvent(async(P) =>
                    {
                        try
                        {
                            await this.RequestBootstrap();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }, DateTime.Now.AddMinutes(15), null);
                };

                this.lwm2mClient.OnRegistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server registration completed.");
                };

                this.lwm2mClient.OnRegistrationFailed += (sender, e) =>
                {
                    Log.Error("Server registration failed.");
                };

                this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server deregistration completed.");
                };

                this.lwm2mClient.OnDeregistrationFailed += (sender, e) =>
                {
                    Log.Error("Server deregistration failed.");
                };

                this.lwm2mClient.OnRebootRequest += async(sender, e) =>
                {
                    Log.Warning("Reboot is requested.");

                    try
                    {
                        await this.RequestBootstrap();
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.RequestBootstrap();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Exemplo n.º 16
0
        public async Task Connect()
        {
            try
            {
                ConnectionInfo = ConfigService.GetConnectionInfo();

                HubConnection = new HubConnectionBuilder()
                                .WithUrl(ConnectionInfo.Host + "/AgentHub")
                                .Build();

                RegisterMessageHandlers();

                await HubConnection.StartAsync();
            }
            catch (Exception ex)
            {
                Logger.Write(ex, "Failed to connect to server.  Internet connection may be unavailable.", EventType.Warning);
                return;
            }

            try
            {
                var device = await DeviceInformation.Create(ConnectionInfo.DeviceID, ConnectionInfo.OrganizationID);

                var result = await HubConnection.InvokeAsync <bool>("DeviceCameOnline", device);

                if (!result)
                {
                    // Orgnanization ID wasn't found, or this device is already connected.
                    // The above can be caused by temporary issues on the server.  So we'll do
                    // nothing here and wait for it to get resolved.
                    Logger.Write("There was an issue registering with the server.  The server might be undergoing maintenance, or the supplied organization ID might be incorrect.");
                    await Task.Delay(TimeSpan.FromMinutes(1));

                    await HubConnection.StopAsync();

                    return;
                }

                if (string.IsNullOrWhiteSpace(ConnectionInfo.ServerVerificationToken))
                {
                    IsServerVerified = true;
                    ConnectionInfo.ServerVerificationToken = Guid.NewGuid().ToString();
                    await HubConnection.SendAsync("SetServerVerificationToken", ConnectionInfo.ServerVerificationToken);

                    ConfigService.SaveConnectionInfo(ConnectionInfo);
                }
                else
                {
                    await HubConnection.SendAsync("SendServerVerificationToken");
                }

                HeartbeatTimer?.Dispose();
                HeartbeatTimer          = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds);
                HeartbeatTimer.Elapsed += HeartbeatTimer_Elapsed;
                HeartbeatTimer.Start();
            }
            catch (Exception ex)
            {
                Logger.Write(ex, "Error starting websocket connection.", EventType.Error);
            }
        }
Exemplo n.º 17
0
        } // end Dispose

 

        /// <summary>Sets the device used on the operating system.</summary>

        /// <param name="deviceInfo">The device info used to determine the device to use.</param>

        public void SetDevice(DeviceInformation deviceInfo)

        {

            D = new Device(deviceInfo.DriverGuid);

            D.SetCooperativeLevel(owner, CooperativeLevel.Priority);

        } // end SetDevice
Exemplo n.º 18
0
 public Earbuds(DeviceInformation deviceInformation)
 {
     BtID     = BluetoothDevices.ConvertDeviceIdType(deviceInformation.Id, AddressType.Bluetooth);
     BleID    = BluetoothDevices.ConvertDeviceIdType(deviceInformation.Id, AddressType.BLE);
     LOG_TAG += BleID.Substring(41);
 }
Exemplo n.º 19
0
 public PseudoDeviceManager(double min, double max, TimeSpan period)
 {
     EmulatorStream = new PseudoDeviceStream(min, max, period);
     EmulatorDeviceInfo = new DeviceInformation(DeviceConstants.SearchPattern, Strings.Emulated_Device_Description);
 }
 public GattDeviceCollection(DeviceInformation device)
 {
     this.device = device;
 }
Exemplo n.º 21
0
 public DeviceInformationDisplay(DeviceInformation deviceInfoIn)
 {
     deviceInfo = deviceInfoIn;
     UpdateGlyphBitmapImage();
 }
Exemplo n.º 22
0
        private async Task StartPreviewAsync()
        {
            try
            {
                var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                var    deviceList = devices.ToList();
                var    device     = devices.FirstOrDefault(x => x.Name.Contains(settings.CameraKey));
                string deviceId   = device == null ? "" : device.Id;


                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings()
                {
                    SharingMode = MediaCaptureSharingMode.ExclusiveControl, VideoDeviceId = deviceId
                });

                var resolutions = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).ToList();

                var availableResolutions = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Cast <VideoEncodingProperties>().OrderByDescending(v => v.Width * v.Height * (v.FrameRate.Numerator / v.FrameRate.Denominator));
                //1080p or lower
                var reslution = availableResolutions.FirstOrDefault(v => v.Height <= 1080);

                // set used resolution
                await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, reslution);

                mediaCapture2 = new MediaCapture();
                await mediaCapture2.InitializeAsync(new MediaCaptureInitializationSettings()
                {
                    SharingMode = MediaCaptureSharingMode.SharedReadOnly, VideoDeviceId = deviceId
                });

                mediaCapture3 = new MediaCapture();
                await mediaCapture3.InitializeAsync(new MediaCaptureInitializationSettings()
                {
                    SharingMode = MediaCaptureSharingMode.SharedReadOnly, VideoDeviceId = deviceId
                });

                mediaCapture4 = new MediaCapture();
                await mediaCapture4.InitializeAsync(new MediaCaptureInitializationSettings()
                {
                    SharingMode = MediaCaptureSharingMode.SharedReadOnly, VideoDeviceId = deviceId
                });

                displayRequest.RequestActive();
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

                // Create the definition, which will contain some initialization settings
                var definition = new FaceDetectionEffectDefinition();

                // To ensure preview smoothness, do not delay incoming samples
                definition.SynchronousDetectionEnabled = false;

                // In this scenario, choose detection speed over accuracy
                definition.DetectionMode = FaceDetectionMode.HighQuality;
                imageAnalysisRunning     = false;

                // Add the effect to the preview stream
                _faceDetectionEffect = (FaceDetectionEffect)await mediaCapture.AddVideoEffectAsync(definition, MediaStreamType.VideoPreview);

                // Choose the shortest interval between detection events
                _faceDetectionEffect.DesiredDetectionInterval = TimeSpan.FromMilliseconds(300);

                // Start detecting faces
                _faceDetectionEffect.Enabled = true;

                // Register for face detection events
                _faceDetectionEffect.FaceDetected += _faceDetectionEffect_FaceDetectedAsync;
                timerFailsafe.Start();
            }
            catch (Exception)
            {
                // This will be thrown if the user denied access to the camera in privacy settings
                Console.Write("The app was denided access to the camera");
                faceLastDate = DateTime.Now.Subtract(new TimeSpan(1, 1, 1));
                return;
            }

            try
            {
                captionsControl.MainCapture.Source = mediaCapture;
                speechControl.MainCapture.Source   = mediaCapture2;
                tagsControl.MainCapture.Source     = mediaCapture3;
                facesControl.MainCapture.Source    = mediaCapture4;
                await mediaCapture.StartPreviewAsync();

                await mediaCapture2.StartPreviewAsync();

                await mediaCapture3.StartPreviewAsync();

                await mediaCapture4.StartPreviewAsync();
            }
            catch (Exception)
            {
                //mediaCapture.CaptureDeviceExclusiveControlStatusChanged += MediaCapture_CaptureDeviceExclusiveControlStatusChanged; ;
            }
        }
Exemplo n.º 23
0
        public async Task InitializeCameraAsync(CaptureElement previewControl)
        {
            this.previewControl = previewControl;

            if (this.mediaCapture == null)
            {
                var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                DeviceInformation cameraDevice =
                    allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null &&
                                                   x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);

                // If there is no camera on the specified panel, get any camera
                cameraDevice = cameraDevice ?? allVideoDevices.FirstOrDefault();

                if (cameraDevice == null)
                {
                    Dialog.Show("No camera device found.");
                    return;
                }

                // Create MediaCapture and its settings
                this.mediaCapture = new MediaCapture();

                var mediaInitSettings = new MediaCaptureInitializationSettings {
                    VideoDeviceId = cameraDevice.Id
                };

                // Initialize MediaCapture
                try
                {
                    await this.mediaCapture.InitializeAsync(mediaInitSettings);

                    var resolutions = this.mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);

                    this.isInitialized = true;
                }
                catch (UnauthorizedAccessException)
                {
                    Dialog.Show("The app was denied access to the camera");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString());
                }

                // If initialization succeeded, start the preview
                if (this.isInitialized)
                {
                    // Figure out where the camera is located
                    if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
                    {
                        // No information on the location of the camera, assume it's an external camera, not integrated on the device
                        this.externalCamera = true;
                    }
                    else
                    {
                        // Camera is fixed on the device
                        this.externalCamera = false;

                        // Only mirror the preview if the camera is on the front panel
                        this.mirroringPreview = cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front;
                    }

                    await this.StartPreviewAsync();
                }
            }

            this.RegisterOrientationEventHandlers();
        }
Exemplo n.º 24
0
        private async void DeviceAdded(DeviceWatcher sender, DeviceInformation args)
        {
            try
            {
                var devices = (await KnownFolders.RemovableDevices.GetFoldersAsync()).OrderBy(x => x.Path);
                foreach (StorageFolder device in devices)
                {
                    var letter = device.Path;
                    if (!foundDrives.Any(x => x.tag == letter))
                    {
                        var    content = device.DisplayName;
                        string icon    = null;
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low,
                                                                                      async() =>
                        {
                            if (content.Contains("DVD"))
                            {
                                icon = "\uE958";
                            }
                            else
                            {
                                icon = "\uE88E";
                            }

                            ulong totalSpaceProg      = 0;
                            ulong freeSpaceProg       = 0;
                            string free_space_text    = "Unknown";
                            string total_space_text   = "Unknown";
                            Visibility capacityBarVis = Visibility.Visible;
                            try
                            {
                                StorageFolder drive    = await StorageFolder.GetFolderFromPathAsync(letter);
                                var retrivedProperties = await drive.Properties.RetrievePropertiesAsync(new string[] { "System.FreeSpace", "System.Capacity" });

                                var sizeAsGBString = ByteSizeLib.ByteSize.FromBytes((ulong)retrivedProperties["System.FreeSpace"]).GigaBytes;
                                freeSpaceProg      = Convert.ToUInt64(sizeAsGBString);

                                sizeAsGBString = ByteSizeLib.ByteSize.FromBytes((ulong)retrivedProperties["System.Capacity"]).GigaBytes;
                                totalSpaceProg = Convert.ToUInt64(sizeAsGBString);

                                free_space_text  = ByteSizeLib.ByteSize.FromBytes((ulong)retrivedProperties["System.FreeSpace"]).ToString();
                                total_space_text = ByteSizeLib.ByteSize.FromBytes((ulong)retrivedProperties["System.Capacity"]).ToString();
                            }
                            catch (UnauthorizedAccessException)
                            {
                                capacityBarVis = Visibility.Collapsed;
                            }
                            catch (NullReferenceException)
                            {
                                capacityBarVis = Visibility.Collapsed;
                            }

                            if (!foundDrives.Any(x => x.tag == letter))
                            {
                                foundDrives.Add(new DriveItem()
                                {
                                    driveText             = content,
                                    glyph                 = icon,
                                    maxSpace              = totalSpaceProg,
                                    spaceUsed             = totalSpaceProg - freeSpaceProg,
                                    tag                   = letter,
                                    progressBarVisibility = capacityBarVis,
                                    spaceText             = free_space_text + " free of " + total_space_text,
                                });
                            }
                        });
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                await consentDialog.ShowAsync();
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
        /// </summary>
        /// <returns></returns>
        private async Task InitializeCameraAsync()
        {
            Debug.WriteLine("InitializeCameraAsync");

            if (_mediaCapture == null)
            {
                // Create MediaCapture and its settings
                _mediaCapture         = new MediaCapture();
                _mediaCapture.Failed += MediaCapture_Failed;

                // Initialize MediaCapture
                try
                {
                    var cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (cameraDevices == null)
                    {
                        Debug.WriteLine("No camera device found!");
                        return;
                    }

                    foreach (var device in cameraDevices)
                    {
                        if (device.EnclosureLocation == null)
                        {
                            _cameraId = device.Id;
                            break;
                        }

                        switch (device.EnclosureLocation.Panel)
                        {
                        default:
                            _cameraId = device.Id;
                            break;

                        case Devices.Enumeration.Panel.Back:
                            break;
                        }
                    }

                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = _cameraId });

                    _isInitialized = true;
                }
                catch (UnauthorizedAccessException)
                {
                    Debug.WriteLine("The app was denied access to the camera");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", _cameraId, ex);
                }

                // If initialization succeeded, start the preview
                if (_isInitialized)
                {
                    // Only mirror the preview if the camera is on the front panel
                    _mirroringPreview = true;

                    if (OptimizeForLowLight)
                    {
                        await InitializeForLowLight();
                    }

                    PreviewControl.Source = _mediaCapture;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();

                    AdjustSettings();
                }
            }
        }
Exemplo n.º 26
0
 VideoCapture(MediaFrameSourceGroup frameSourceGroup, MediaFrameSourceInfo frameSourceInfo, DeviceInformation deviceInfo)
 {
     _frameSourceGroup = frameSourceGroup;
     _frameSourceInfo  = frameSourceInfo;
     _deviceInfo       = deviceInfo;
 }
Exemplo n.º 27
0
        public static async Task LoadDriveAsync(bool IsRefresh = false)
        {
            if (Interlocked.Exchange(ref LoadDriveLockResource, 1) == 0)
            {
                try
                {
                    if (!IsDriveLoaded || IsRefresh)
                    {
                        IsDriveLoaded = true;

                        if (IsRefresh)
                        {
                            DriveList.Clear();
                        }

                        foreach (DriveInfo Drive in DriveInfo.GetDrives().Where((Drives) => Drives.DriveType == DriveType.Fixed || Drives.DriveType == DriveType.Removable || Drives.DriveType == DriveType.Network)
                                 .Where((NewItem) => DriveList.All((Item) => !Item.Path.Equals(NewItem.RootDirectory.FullName, StringComparison.OrdinalIgnoreCase))))
                        {
                            try
                            {
                                StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(Drive.RootDirectory.FullName);

                                if (DriveList.All((Item) => (string.IsNullOrEmpty(Item.Path) || string.IsNullOrEmpty(Folder.Path)) ? !Item.Name.Equals(Folder.Name, StringComparison.OrdinalIgnoreCase) : !Item.Path.Equals(Folder.Path, StringComparison.OrdinalIgnoreCase)))
                                {
                                    DriveList.Add(await DriveDataBase.CreateAsync(Folder, Drive.DriveType));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device \"{Drive.RootDirectory.FullName}\" for error");
                            }
                        }

                        foreach (DeviceInformation Drive in await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector()))
                        {
                            try
                            {
                                StorageFolder Folder = StorageDevice.FromId(Drive.Id);

                                if (DriveList.All((Item) => (string.IsNullOrEmpty(Item.Path) || string.IsNullOrEmpty(Folder.Path)) ? !Item.Name.Equals(Folder.Name, StringComparison.OrdinalIgnoreCase) : !Item.Path.Equals(Folder.Path, StringComparison.OrdinalIgnoreCase)))
                                {
                                    DriveList.Add(await DriveDataBase.CreateAsync(Folder, DriveType.Removable));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device for error");
                            }
                        }

                        foreach (StorageFolder Folder in await GetWslDriveAsync())
                        {
                            try
                            {
                                if (DriveList.All((Item) => (string.IsNullOrEmpty(Item.Path) || string.IsNullOrEmpty(Folder.Path)) ? !Item.Name.Equals(Folder.Name, StringComparison.OrdinalIgnoreCase) : !Item.Path.Equals(Folder.Path, StringComparison.OrdinalIgnoreCase)))
                                {
                                    DriveList.Add(await DriveDataBase.CreateAsync(Folder, DriveType.Network));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device \"{Folder.Name}\" for error");
                            }
                        }

                        switch (PortalDeviceWatcher.Status)
                        {
                        case DeviceWatcherStatus.Created:
                        case DeviceWatcherStatus.Aborted:
                        case DeviceWatcherStatus.Stopped:
                        {
                            PortalDeviceWatcher.Start();
                            break;
                        }
                        }

                        if (!NetworkDriveCheckTimer.IsEnabled)
                        {
                            NetworkDriveCheckTimer.Start();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An exception was threw in {nameof(LoadDriveAsync)}");
                }
                finally
                {
                    _ = Interlocked.Exchange(ref LoadDriveLockResource, 0);
                }
            }
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
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;
 }
Exemplo n.º 30
0
 public BluetoothLEDeviceDisplay(DeviceInformation deviceInfoIn)
 {
     DeviceInformation = deviceInfoIn;
     UpdateGlyphBitmapImage();
 }
Exemplo n.º 31
0
        }//enable/disable preview

        private async void changeCameraButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            try
            {
                string errorText = "";
                if (currentCamera == backCamera)
                {
                    if (frontCamera != null)
                    {
                        currentCamera = frontCamera;
                    }
                    else
                    {
                        errorText = Localize("errorFront");
                    }
                }
                else
                if (currentCamera == frontCamera)
                {
                    if (backCamera != null)
                    {
                        currentCamera = backCamera;
                    }
                    else
                    {
                        errorText = Localize("errorBack");
                    }
                }

                //if camera change cannot be done, show error message, else change currentCamera
                if (errorText != "")
                {
                    var dlg = new MessageDialog(errorText);
                    await dlg.ShowAsync();
                }
                else
                {
                    ShowProgressBar();
                    await DisposeResourcesAsync();

                    StopPreviewRenderAndCapture();
                    await InitializePreviewAsync();

                    ShowCommandBar();
                }
            }
            catch (OutOfMemoryException)
            {
                var dlg = new MessageDialog(Localize("memoryError"));
                await dlg.ShowAsync();

                Frame.Navigate(typeof(MainPage));
            }
            catch (Exception ex)
            {
                if (ex.HResult != -2005270523)
                {
                    Frame.Navigate(typeof(MainPage));
                }
            }
        }
Exemplo n.º 32
0
 //Tries to reconnect to the device passed in the parameter.
 public void TryReconnectToDevice(DeviceInformation device)
 {
     LoggerWrapper.Instance.WriteToConsole("Should try to reestablish connection to: " + device.Name);
     _reconnectTimer = new Timer(OnReconnectTry, device, 0, Settings.WAIT_TIME_BETWEEN_RECONNECT_TRIES);
 }
Exemplo n.º 33
0
        private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            device = args;

            Debug.WriteLine("Device Added");
        }
Exemplo n.º 34
0
 public BluetoothDeviceRT(DeviceInformation info) : base(0)
 {
     DeviceInfo = info;
 }
Exemplo n.º 35
0
 public DeviceItem(DeviceInformation info)
 {
     this.DeviceInformation = info;
 }
Exemplo n.º 36
0
        /// <summary>
        /// Executes when a device is updated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="deviceInfoUpdate"></param>
        private async void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
        {
            DeviceInformation di = null;
            bool addNewDI        = false;

            try
            {
                // Protect against race condition if the task runs after the app stopped the deviceWatcher.
                if (sender == deviceWatcher)
                {
                    ObservableBluetoothLEDevice dev;

                    // Need to lock as another DeviceWatcher might be modifying BluetoothLEDevices
                    try
                    {
                        await BluetoothLEDevicesLock.WaitAsync();

                        dev = BluetoothLEDevices.FirstOrDefault(device => device.DeviceInfo.Id == deviceInfoUpdate.Id);
                        if (dev != null)
                        {   // Found a device in the list, updating it
                            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                                Windows.UI.Core.CoreDispatcherPriority.Normal,
                                async() =>
                            {
                                dev.Update(deviceInfoUpdate);
                                await UpdateBatteryLevel(dev);
                            });
                        }
                        else
                        {
                            // Need to add this device. Can't do that here as we have the lock
                            addNewDI = true;
                        }
                    }
                    finally
                    {
                        BluetoothLEDevicesLock.Release();
                    }

                    if (addNewDI == true)
                    {
                        try
                        {
                            await BluetoothLEDevicesLock.WaitAsync();

                            di = unusedDevices.FirstOrDefault(device => device.Id == deviceInfoUpdate.Id);
                            if (di != null)
                            {   // We found this device before.
                                unusedDevices.Remove(di);
                                di.Update(deviceInfoUpdate);
                            }
                        }
                        finally
                        {
                            BluetoothLEDevicesLock.Release();
                        }

                        if (di != null)
                        {
                            await AddDeviceToList(di);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("DeviceWatcher_Updated: " + ex.Message);
            }
        }
Exemplo n.º 37
0
 /// <summary>
 /// Reset the buttons when the device is reopened
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="onDeviceConnectedEventArgs"></param>
 private void OnDeviceConnected(EventHandlerForDevice sender, DeviceInformation onDeviceConnectedEventArgs)
 {
     UpdateButtonStates();
 }
Exemplo n.º 38
0
        public MipRobot(DeviceInformation deviceInfo) : base(deviceInfo)
        {
            //TODO: update DeviceName

            //TODO: update ProductId
        }
Exemplo n.º 39
0
 public IDeviceStream OpenDeviceStream(DeviceInformation deviceInfo)
 {
     return EmulatorStream;
 }
Exemplo n.º 40
0
 public BluetoothLEDeviceDisplay(DeviceInformation deviceInfoIn)
 {
     DeviceInformation = deviceInfoIn;
 }
Exemplo n.º 41
0
 internal AudioDeviceInfo(DeviceInformation info)
 {
     this.info = info;            
 }
Exemplo n.º 42
0
   public virtual void ShowDialog(CecConfigGUI gui, CecLogicalAddress address, ref LibCecSharp lib,
 bool devicePresent, CecVendorId vendor, bool isActiveSource, ushort physicalAddress,
 CecVersion version, CecPowerStatus power, string osdName, string menuLanguage)
   {
       DeviceInformation di = new DeviceInformation(Gui, Address, ref Lib, devicePresent, vendor, isActiveSource, physicalAddress, version, power, osdName, menuLanguage);
         Gui.DisplayDialog(di, false);
   }
Exemplo n.º 43
0
 public UpdateDeviceInfo(CecConfigGUI gui, ref LibCecSharp lib, DeviceInformation dialog)
     : base(gui, ref lib, dialog.Address)
 {
     Dialog = dialog;
 }
Exemplo n.º 44
0
        private void FlagSuspiciousMiner(MinerProcess minerProcess, DeviceInformation deviceInformation)
        {
            if (deviceInformation.Status.ToLower().Contains("sick"))
                minerProcess.HasSickDevice = true;
            if (deviceInformation.Status.ToLower().Contains("dead"))
                minerProcess.HasDeadDevice = true;
            if (deviceInformation.CurrentHashrate == 0)
                minerProcess.HasZeroHashrateDevice = true;

            //only check GPUs for subpar hashrate
            //ASICs spike too much for this to be reliable there
            //don't check average hashrate if using dynamic intensity
            if (deviceInformation.Kind.Equals("GPU", StringComparison.OrdinalIgnoreCase) &&
                !EngineConfiguration.XgminerConfiguration.DesktopMode)
            {
                //avoid div by 0
                if (deviceInformation.AverageHashrate > 0)
                {
                    double performanceRatio = deviceInformation.CurrentHashrate / deviceInformation.AverageHashrate;
                    if (performanceRatio <= 0.50)
                        minerProcess.HasPoorPerformingDevice = true;
                }
            }

            if (miningCoinConfigurations == null)
                //started mining but haven't yet assigned mining members
                //cannot check the following yet
                return;

            //Work Utility not returned by legacy API miners
            if (!minerProcess.Miner.LegacyApi)
            {
                double effectiveHashrate = WorkUtilityToHashrate(deviceInformation.WorkUtility);
                //avoid div by 0
                if (deviceInformation.AverageHashrate > 0)
                {
                    double performanceRatio = effectiveHashrate / deviceInformation.AverageHashrate;
                    if (performanceRatio <= 0.25)
                        minerProcess.StoppedAcceptingShares = true;
                }
            }
        }
Exemplo n.º 45
0
        private void PopulateMobileMinerStatistics(MiningStatistics miningStatistics, DeviceInformation deviceInformation,
            string coinName)
        {
            miningStatistics.MinerName = "MultiMiner";
            miningStatistics.CoinName = coinName;
            Coin coinConfiguration = EngineConfiguration.CoinConfigurations.Single(c => c.PoolGroup.Name.Equals(coinName));
            PoolGroup coin = coinConfiguration.PoolGroup;

            //don't send non-coin Ids to MobileMiner
            if (coin.Kind != PoolGroup.PoolGroupKind.MultiCoin)
                miningStatistics.CoinSymbol = coin.Id;

            CoinAlgorithm algorithm = MinerFactory.Instance.GetAlgorithm(coin.Algorithm);

            //MobileMiner currently only supports SHA and Scrypt
            //attempt to treat them as "Families" for now
            if ((algorithm.Family == CoinAlgorithm.AlgorithmFamily.SHA2) ||
                (algorithm.Family == CoinAlgorithm.AlgorithmFamily.SHA3))
                //SHA family algorithms grouped together
                miningStatistics.Algorithm = AlgorithmFullNames.SHA256;
            else
                //assume Scrypt for rest until MobileMiner supports more
                miningStatistics.Algorithm = AlgorithmFullNames.Scrypt;

            miningStatistics.PopulateFrom(deviceInformation);
        }
Exemplo n.º 46
0
Arquivo: Main.cs Projeto: ptaa32/ARDOP
        public bool StartCodec(ref string strFault)
        {
            bool functionReturnValue = false;
            //Returns true if successful
            Thread.Sleep(100);
            // This delay is necessary for reliable starup following a StopCodec
            lock (objCodecLock) {
            dttLastSoundCardSample = Now;
            bool blnSpectrumSave = MCB.DisplaySpectrum;
            bool blnWaterfallSave = MCB.DisplayWaterfall;
            System.DateTime dttStartWait = Now;
            MCB.DisplayWaterfall = false;
            MCB.DisplaySpectrum = false;
            string[] strCaptureDevices = EnumerateCaptureDevices();
            string[] strPlaybackDevices = EnumeratePlaybackDevices();
            functionReturnValue = false;
            DeviceInformation objDI = new DeviceInformation();
            int intPtr = 0;
            // Playback devices
            try {
                cllPlaybackDevices = null;

                cllPlaybackDevices = new Microsoft.DirectX.DirectSound.DevicesCollection();
                if ((devSelectedPlaybackDevice != null)) {
                    devSelectedPlaybackDevice.Dispose();
                    devSelectedPlaybackDevice = null;
                }

                foreach (DeviceInformation objDI in cllPlaybackDevices) {
                    DeviceDescription objDD = new DeviceDescription(objDI);
                    if (strPlaybackDevices(intPtr) == MCB.PlaybackDevice) {
                        if (MCB.DebugLog)
                            Logs.WriteDebug("[Main.StartCodec] Setting SelectedPlaybackDevice = " + MCB.PlaybackDevice);
                        devSelectedPlaybackDevice = new Device(objDD.info.DriverGuid);
                        functionReturnValue = true;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                    intPtr += 1;
                }
                if (!functionReturnValue) {
                    strFault = "Playback Device setup, Device " + MCB.PlaybackDevice + " not found in Windows enumerated Playback Devices";
                }
            } catch (Exception ex) {
                strFault = Err.Number.ToString + "/" + Err.Description;
                Logs.Exception("[StartCodec], Playback Device setup] Err: " + ex.ToString);
                functionReturnValue = false;
            }
            if (functionReturnValue) {
                // Capture Device
                CaptureBufferDescription dscheckboxd = new CaptureBufferDescription();
                try {
                    functionReturnValue = false;
                    cllCaptureDevices = null;
                    cllCaptureDevices = new CaptureDevicesCollection();
                    intPtr = 0;
                    for (int i = 0; i <= cllCaptureDevices.Count - 1; i++) {
                        if (MCB.CaptureDevice == strCaptureDevices(i)) {
                            objCaptureDeviceGuid = cllCaptureDevices(i).DriverGuid;
                            devCaptureDevice = new Capture(objCaptureDeviceGuid);
                            stcSCFormat.SamplesPerSecond = 12000;
                            // 12000 Hz sample rate
                            stcSCFormat.Channels = 1;
                            stcSCFormat.BitsPerSample = 16;
                            stcSCFormat.BlockAlign = 2;
                            stcSCFormat.AverageBytesPerSecond = 2 * 12000;
                            stcSCFormat.FormatTag = WaveFormatTag.Pcm;
                            objApplicationNotify = null;
                            objCapture = null;
                            // Set the buffer sizes
                            intCaptureBufferSize = intNotifySize * intNumberRecordNotifications;
                            // Create the capture buffer
                            dscheckboxd.BufferBytes = intCaptureBufferSize;
                            stcSCFormat.FormatTag = WaveFormatTag.Pcm;
                            dscheckboxd.Format = stcSCFormat;
                            // Set the format during creatation
                            if ((objCapture != null)) {
                                objCapture.Dispose();
                                objCapture = null;
                            }
                            //objCapture = New CaptureBuffer(dscheckboxd, devCaptureDevice)
                            intNextCaptureOffset = 0;
                            WriteTextToSpectrum("CODEC Start OK", Brushes.LightGreen);
                            while (Now.Subtract(dttStartWait).TotalSeconds < 3) {
                                Application.DoEvents();
                                Thread.Sleep(100);
                            }
                            objCapture = new CaptureBuffer(dscheckboxd, devCaptureDevice);
                            InititializeNotifications();
                            objCapture.Start(true);
                            // start with looping
                            InititializeSpectrum(Color.Black);

                            functionReturnValue = true;
                        }
                    }
                    if (!functionReturnValue) {
                        strFault = "Could not find DirectSound capture device " + MCB.CaptureDevice.ToUpper;
                        //Logs.Exception("[Main.StartCodec] Could not find DirectSound capture device " & MCB.CaptureDevice & " in Windows enumerated Capture Devices")
                    }
                } catch (Exception ex) {
                    strFault = Err.Number.ToString + "/" + Err.Description;
                    functionReturnValue = false;
                    //Logs.Exception("[Main.StartCodec] Err: " & ex.ToString)
                }
            }

            if (functionReturnValue) {
                if (MCB.DebugLog)
                    Logs.WriteDebug("[Main.StartCodec] Successful start of codec");
                objProtocol.ARDOPProtocolState = ProtocolState.DISC;
            } else {
                if (MCB.DebugLog)
                    Logs.WriteDebug("[Main.StartCodec] CODEC Start Failed");
                WriteTextToSpectrum("CODEC Start Failed", Brushes.Red);
                objProtocol.ARDOPProtocolState = ProtocolState.OFFLINE;
                while (Now.Subtract(dttStartWait).TotalSeconds < 3) {
                    Application.DoEvents();
                    Thread.Sleep(100);
                }
                tmrStartCODEC.Interval = 5000;
                tmrStartCODEC.Start();
            }
            InititializeSpectrum(Color.Black);
            MCB.DisplayWaterfall = blnWaterfallSave;
            MCB.DisplaySpectrum = blnSpectrumSave;
            }
            return functionReturnValue;
        }
Exemplo n.º 47
0
Arquivo: Main.cs Projeto: ptaa32/ARDOP
 public DeviceDescription(DeviceInformation d)
 {
     info = d;
 }
Exemplo n.º 48
-1
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (DeviceFound())
            {
                await SuscribeToHrValues();
                await DisplayBatteryLevel();
                DeviceFoundMessage = $@"[{_devicePolarHr.Name}]
Connected";
                ButtonLoad.Content = "Disconnect ...";
            }
            else
            {
                ButtonLoad.Content = "Connect ...";
                _devicePolarHr = null;
                _devicePolarBattery = null;
            }
        }