Ejemplo n.º 1
0
        public void RemoveAlgorithmsFromDevices()
        {
            var devices = _cachedNiceHashMinerAlgorithms.Keys.Select(uuid => AvailableDevices.GetDeviceWithUuid(uuid)).Where(d => d != null);

            // remove
            foreach (var dev in devices)
            {
                dev.RemovePluginAlgorithms(PluginUUID);
            }
        }
Ejemplo n.º 2
0
 private void LoadAvailableDevices()
 {
     try
     {
         AvailableDevices.Load(new AdbClient().GetDevices());
     }
     catch (Exception ex)
     {
         log.Error("Couldn't load available devices", ex);
     }
 }
Ejemplo n.º 3
0
        private void RendererDiscovererItemAdded(object sender, DeviceAddedArgs e)
        {
            var item = e.Receiver;

            _logger.LogInformation(
                $"{nameof(RendererDiscovererItemAdded)}: New item discovered: " +
                $"{e.Receiver.FriendlyName} - Ip = {item.Host}:{item.Port}");
            AvailableDevices.Add(item);

            OnCastableDeviceAdded?.Invoke(item.Id, item.FriendlyName, item.Type, item.Host, item.Port);
        }
Ejemplo n.º 4
0
        void RefreshDisplayDevices()
        {
            using (new XLock(API.DefaultDisplay))
            {
                List <DisplayDevice> devices = new List <DisplayDevice>();
                xinerama_supported = false;
                try
                {
                    xinerama_supported = QueryXinerama(devices);
                }
                catch
                {
                    Debug.Print("Xinerama query failed.");
                }

                if (!xinerama_supported)
                {
                    // We assume that devices are equivalent to the number of available screens.
                    // Note: this won't work correctly in the case of distinct X servers.
                    for (int i = 0; i < API.ScreenCount; i++)
                    {
                        DisplayDevice dev = new DisplayDevice();
                        dev.IsPrimary = i == Functions.XDefaultScreen(API.DefaultDisplay);
                        devices.Add(dev);
                        deviceToScreen.Add(dev, i);
                    }
                }

                try
                {
                    xrandr_supported = QueryXRandR(devices);
                }
                catch { }

                if (!xrandr_supported)
                {
                    Debug.Print("XRandR query failed, falling back to XF86.");
                    try
                    {
                        xf86_supported = QueryXF86(devices);
                    }
                    catch { }

                    if (!xf86_supported)
                    {
                        Debug.Print("XF86 query failed, no DisplayDevice support available.");
                    }
                }

                AvailableDevices.Clear();
                AvailableDevices.AddRange(devices);
                Primary = FindDefaultDevice(devices);
            }
        }
Ejemplo n.º 5
0
        public Task SetCastRenderer(string host, int port)
        {
            if (!AvailableDevices.Any(d => d.Host == host && d.Port == port))
            {
                AvailableDevices.Add(Receiver.Default(host, port));
            }

            var renderer = AvailableDevices.Find(d => d.Host == host && d.Port == port);

            return(SetCastRenderer(renderer));
        }
Ejemplo n.º 6
0
 private void DevicesListView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
 {
     algorithmSettingsControl1.Deselect();
     // show algorithms
     _selectedComputeDevice =
         AvailableDevices.GetCurrentlySelectedComputeDevice(e.ItemIndex, ShowUniqueDeviceList);
     algorithmsListView1.SetAlgorithms(_selectedComputeDevice, _selectedComputeDevice.Enabled);
     groupBoxAlgorithmSettings.Text = string.Format(Tr("Algorithm settings for {0} :"),
                                                    _selectedComputeDevice.Name);
     minDeviceProfitField.Enabled   = true;
     minDeviceProfitField.EntryText = _selectedComputeDevice.MinimumProfit.ToString("F2").Replace(',', '.');
 }
Ejemplo n.º 7
0
        public void AddAlgorithmsToDevices()
        {
            var payingRates = NHSmaData.CurrentPayingRatesSnapshot();

            CheckExec(nameof(AddAlgorithmsToDevices), () => {
                if (!_initInternalsCalled && _plugin is IInitInternals impl)
                {
                    _initInternalsCalled = true;
                    impl.InitInternals();
                }
                // update settings for algos per device
                var devices = _cachedNiceHashMinerAlgorithms.Keys.Select(uuid => AvailableDevices.GetDeviceWithUuid(uuid)).Where(d => d != null);
                foreach (var dev in devices)
                {
                    var algos = _cachedNiceHashMinerAlgorithms[dev.Uuid];
                    foreach (var algo in algos)
                    {
                        algo.UpdateEstimatedProfit(payingRates);
                        // try get data from configs
                        var pluginConf = dev.GetPluginAlgorithmConfig(algo.AlgorithmStringID);
                        if (pluginConf == null)
                        {
                            continue;
                        }
                        // set plugin algo
                        algo.Speeds  = pluginConf.Speeds;
                        algo.Enabled = pluginConf.Enabled;
                        if (ConfigManager.IsVersionChanged && PluginUUID == "0e0a7320-94ec-11ea-a64d-17be303ea466" && algo.AlgorithmName.Contains(AlgorithmType.RandomXmonero.ToString()) && (pluginConf.ExtraLaunchParameters == "" || pluginConf.ExtraLaunchParameters == "--cpu-priority=0"))
                        {
                            algo.ExtraLaunchParameters = "--cpu-priority 0";
                        }
                        else
                        {
                            algo.ExtraLaunchParameters = pluginConf.ExtraLaunchParameters;
                        }
                        algo.PowerUsage    = pluginConf.PowerUsage;
                        algo.ConfigVersion = pluginConf.GetVersion();
                        // check if re-bench is needed
                        var isReBenchmark = ShouldReBenchmarkAlgorithmOnDevice(dev.BaseDevice, algo.ConfigVersion, algo.IDs);
                        if (isReBenchmark)
                        {
                            Logger.Info(LogTag, $"Algorithms {algo.AlgorithmStringID} SET TO RE-BENCHMARK");
                        }
                        algo.IsReBenchmark = isReBenchmark;
                    }
                    // finally update algorithms
                    // remove old
                    dev.RemovePluginAlgorithms(PluginUUID);
                    dev.AddPluginAlgorithms(algos);
                }
            });
        }
Ejemplo n.º 8
0
 public void AddAlgorithmsToDevices()
 {
     CheckExec(nameof(AddAlgorithmsToDevices), () => {
         if (!_initInternalsCalled && _plugin is IInitInternals impl)
         {
             _initInternalsCalled = true;
             impl.InitInternals();
         }
         // update settings for algos per device
         var devices = _cachedNiceHashMinerAlgorithms.Keys.Select(uuid => AvailableDevices.GetDeviceWithUuid(uuid)).Where(d => d != null);
         foreach (var dev in devices)
         {
             var configs = dev.GetDeviceConfig();
             var algos   = _cachedNiceHashMinerAlgorithms[dev.Uuid];
             foreach (var algo in algos)
             {
                 if (algo is Algorithms.PluginAlgorithm == false)
                 {
                     continue;
                 }
                 var pluginConf = configs.PluginAlgorithmSettings.Where(c => c.GetAlgorithmStringID() == algo.AlgorithmStringID).FirstOrDefault();
                 if (pluginConf == null)
                 {
                     pluginConf = dev.PluginAlgorithmSettings.Where(c => c.GetAlgorithmStringID() == algo.AlgorithmStringID).FirstOrDefault();
                 }
                 if (pluginConf == null)
                 {
                     continue;
                 }
                 // set plugin algo
                 var pluginAlgo     = algo as Algorithms.PluginAlgorithm;
                 pluginAlgo.Speeds  = pluginConf.Speeds;
                 pluginAlgo.Enabled = pluginConf.Enabled;
                 pluginAlgo.ExtraLaunchParameters = pluginConf.ExtraLaunchParameters;
                 pluginAlgo.PowerUsage            = pluginConf.PowerUsage;
                 pluginAlgo.ConfigVersion         = pluginConf.GetVersion();
                 // check if re-bench is needed
                 var isReBenchmark = ShouldReBenchmarkAlgorithmOnDevice(dev.BaseDevice, pluginAlgo.ConfigVersion, pluginAlgo.IDs);
                 if (isReBenchmark)
                 {
                     Logger.Info(LogTag, $"Algorithms {pluginAlgo.AlgorithmStringID} SET TO RE-BENCHMARK");
                 }
                 pluginAlgo.IsReBenchmark = isReBenchmark;
             }
             // finally update algorithms
             // remove old
             dev.RemovePluginAlgorithms(PluginUUID);
             dev.AddPluginAlgorithms(algos);
         }
     });
 }
        private async void OnDisconnectDeviceCommand()
        {
            if (!Disconnecting)
            {
                if (SelectedDevice != null)
                {
                    if (CrossBleAdapter.Current.Status == AdapterStatus.PoweredOn || CrossBleAdapter.Current.Status == AdapterStatus.Unsupported)
                    {
                        try
                        {
                            Disconnecting = true;
                            DisconnectDeviceCommand.RaiseCanExecuteChanged();
                            //BatteryToken?.Cancel();
                            //SystemToken?.Cancel();
                            //ProgramToken?.Cancel();
                            bleService.Disconnect();
                            var timeOut = 0;
                            while (SelectedDevice.ConnectState != DeviceState.Disconnected && timeOut < 30)
                            {
                                await Task.Delay(TimeSpan.FromSeconds(1));

                                timeOut++;
                            }
                            Disconnecting = false;
                            DisconnectDeviceCommand.RaiseCanExecuteChanged();
                            if (SelectedDevice.ConnectState != DeviceState.Disconnected)
                            {
                                await dialogService.DisplayAlertAsync("Bluetooth", "Device failed to disconnect", "Ok");
                            }
                            else
                            {
                                foundDevices.Clear();
                                AvailableDevices.Clear();
                                SelectedDevice = null;
                                // RaisePropertyChanged(nameof(SelectedDevice));
                            }
                        }
                        catch (Exception e)
                        {
                            //  Crashes.TrackError(e);
                            Disconnecting = false;
                            DisconnectDeviceCommand.RaiseCanExecuteChanged();
                        }
                    }
                    else
                    {
                        await dialogService.DisplayAlertAsync("Bluetooth", "Please check your Bluetooth Settings", "Ok");
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public async Task OnDiscoverDevices()
        {
            WpfUtilities.RunOnUiThread(() => { AvailableDevices.Clear(); }, Application.Current.Dispatcher);

            CommunicationHandlerFactory.DiscoverDevices();
            await Task.Delay(500);

            foreach (var device in CommunicationHandlerFactory.AvailableDevices)
            {
                var handler = CommunicationHandlerFactory.AvailableHandlers.First(h => h.IsDriverForDevice(device));
                var driver  = new DeviceDriver(device, handler.SupportsSetupDialog, new DelegateCommand((p) => OnRunDeviceHandlerSetup(handler, p)));
                WpfUtilities.RunOnUiThread(() => { AvailableDevices.Add(driver); }, Application.Current.Dispatcher);
            }
        }
Ejemplo n.º 11
0
 private void CallBackForUserDetails(User user)
 {
     Device.BeginInvokeOnMainThread(() =>
     {
         var record = AvailableDevices.Where(a => a.IPAddress == user.IPAddress);
         if (record.Any())
         {
             AvailableDevices.Remove(record.First());
         }
         AvailableDevices.Add(new User()
         {
             IPAddress = user.IPAddress, Name = user.Name
         });
     });
 }
Ejemplo n.º 12
0
        public AudioDevice(string deviceName)
        {
            if (deviceName != null && !AvailableDevices.Contains(deviceName))
            {
                throw new InvalidOperationException(string.Format("AudioDevice \"{0}\" does not exist.", deviceName));
            }

            Context = new OpenTK.Audio.AudioContext(deviceName, 0, 15, true, true, AudioContext.MaxAuxiliarySends.UseDriverDefault);
            CheckAlcError();
            deviceHandle = Alc.GetContextsDevice(Alc.GetCurrentContext());
            CheckAlcError();
            Efx = new EffectsExtension();
            CheckAlcError();

            int[] val = new int[4];
            DeviceName    = Context.CurrentDevice;
            VendorName    = AL.Get(ALGetString.Vendor);
            Renderer      = AL.Get(ALGetString.Renderer);
            DriverVersion = AL.Get(ALGetString.Version);
            int major, minor;

            Alc.GetInteger(deviceHandle, AlcGetInteger.MajorVersion, 1, val);
            major = val[0];
            Alc.GetInteger(deviceHandle, AlcGetInteger.MinorVersion, 1, val);
            minor   = val[0];
            Version = new Version(major, minor);
            Alc.GetInteger(deviceHandle, AlcGetInteger.EfxMajorVersion, 1, val);
            major = val[0];
            Alc.GetInteger(deviceHandle, AlcGetInteger.EfxMinorVersion, 1, val);
            minor      = val[0];
            EfxVersion = new Version(major, minor);
            Alc.GetInteger(deviceHandle, AlcGetInteger.EfxMaxAuxiliarySends, 1, val);
            MaxRoutes  = val[0];
            Extensions = new List <string>(AL.Get(ALGetString.Extensions).Split(' ')).AsReadOnly();

            AL.DistanceModel(ALDistanceModel.ExponentDistance);

            CheckAudioCapabilities(LogLevel.Verbose);
            LogDiagnostics(LogLevel.Verbose);

            Factory  = new AudioFactory(this);
            Listener = new AudioListener(this);
            Listener.Orientation(Vector3.UnitY, Vector3.UnitZ);

            updateTaskCancelation = new CancellationTokenSource();
            updateTask            = Task.Factory.StartNew(Update);
        }
Ejemplo n.º 13
0
 private void CopyBenchmarks()
 {
     Helpers.ConsolePrint("CopyBenchmarks", "Checking for benchmarks to copy");
     foreach (var cDev in AvailableDevices.Devices)
     {
         // check if copy
         if (!cDev.Enabled && cDev.BenchmarkCopyUuid != null)
         {
             var copyCdevSettings = AvailableDevices.GetDeviceWithUuid(cDev.BenchmarkCopyUuid);
             if (copyCdevSettings != null)
             {
                 Helpers.ConsolePrint("CopyBenchmarks", $"Copy from {cDev.Uuid} to {cDev.BenchmarkCopyUuid}");
                 cDev.CopyBenchmarkSettingsFrom(copyCdevSettings);
             }
         }
     }
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Determines which command to run.
 /// </summary>
 public static bool Run(AvailableDevices availableDevices, string[] args)
 {
     if (args.Length == 2 && args[0] == "help")
     {
         PrintHelp(args[1]);
         return(true);
     }
     else if (args.Length == 2 && args[0] == "dump")
     {
         return(RomMod.TryDumpSRecordFile(args[1]));
     }
     else if (args.Length == 3 && args[0] == "test")
     {
         return(RomMod.TryApply(args[1], args[2], true, false) || RomMod.TryApply(args[1], args[2], false, false));
     }
     else if (args.Length == 3 && args[0] == "apply")
     {
         return(RomMod.TryApply(args[1], args[2], true, true));
     }
     else if (args.Length == 3 && args[0] == "applied")
     {
         return(RomMod.TryApply(args[1], args[2], false, false));//TODO is this deprecated?
     }
     else if (args.Length == 3 && args[0] == "remove")
     {
         return(RomMod.TryApply(args[1], args[2], false, true));
     }
     else if (args.Length == 4 && args[0] == "baseline")
     {
         return(RomMod.TryGenerateBaseline(args[1], args[2], args[3]));
     }
     else if (args.Length == 4 && args[0] == "baselinedefine")
     {
         return(RomMod.TryBaselineAndDefine(availableDevices, args[1], args[2], args[3], Settings.Default.EcuFlashDefRepoPath));
     }
     else if (args.Length == 4 && args[0] == "define")
     {
         return(RomMod.TryDefine(availableDevices, args[1], args[2], args[3], Settings.Default.EcuFlashDefRepoPath));
     }
     else if (args.Length == 4 && args[0] == "hewbuild")
     {
         return(RomMod.TryHewBuild(availableDevices, args[1], args[2], args[3], Settings.Default.EcuFlashDefRepoPath));
     }
     PrintHelp();
     return(false);
 }
Ejemplo n.º 15
0
        private static bool TryBaselineAndDefine(AvailableDevices ad, string patchPath, string romPath, string build, string defPath)
        {
            using (Stream romStream = File.OpenRead(romPath))
            {
                Mod patcher = new Mod(patchPath, build);

                if (!patcher.TryReadPatches())
                {
                    return(false);
                }
                if (!patcher.TryDefinition(ad, defPath))
                {
                    return(false);
                }
                return(patcher.TryPrintBaselines(patchPath, romStream));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Release all acquired devices
        /// </summary>
        static void ReleaseDevices()
        {
            Trace.WriteDebugLine("[GamePad] ReleaseDevices()");

            foreach (GamePadState state in AvailableDevices)
            {
                if (state.Joystick == null)
                {
                    continue;
                }

                //state.Joystick.Unacquire();
                //state.Joystick.Dispose();
            }

            AvailableDevices.Clear();
        }
Ejemplo n.º 17
0
        public static void AfterDeviceQueryInitialization()
        {
            // extra check (probably will never happen but just in case)
            AvailableDevices.RemoveInvalidDevs();

            // set enabled/disabled devs
            foreach (var cDev in AvailableDevices.Devices)
            {
                foreach (var devConf in GeneralConfig.LastDevicesSettup)
                {
                    cDev.SetFromComputeDeviceConfig(devConf);
                }
            }
            // create/init device benchmark configs files and configs
            foreach (var cDev in AvailableDevices.Devices)
            {
                var keyUuid = cDev.Uuid;
                BenchmarkConfigFiles[keyUuid] = new DeviceBenchmarkConfigFile(keyUuid);
                // init
                {
                    DeviceBenchmarkConfig currentConfig = null;
                    if (BenchmarkConfigFiles[keyUuid].IsFileExists())
                    {
                        currentConfig = BenchmarkConfigFiles[keyUuid].ReadFile();
                    }
                    // config exists and file load success set from file
                    if (currentConfig != null)
                    {
                        cDev.SetAlgorithmDeviceConfig(currentConfig);
                        // if new version create backup
                        if (_isNewVersion)
                        {
                            BenchmarkConfigFiles[keyUuid].CreateBackup();
                        }
                    }
                    else
                    {
                        // no config file or not loaded, create new
                        BenchmarkConfigFiles[keyUuid].Commit(cDev.GetAlgorithmDeviceConfig());
                    }
                }
            }
            // save settings
            GeneralConfigFileCommit();
        }
Ejemplo n.º 18
0
        private void UpdateDisplayIndices(LinuxDisplay display, DisplayDevice device)
        {
            if (!DisplayIds.ContainsKey(display.Id))
            {
                Debug.Print("[KMS] Adding display {0} as {1}", display.Id, AvailableDevices.Count);
                DisplayIds.Add(display.Id, AvailableDevices.Count);
            }
            int index = DisplayIds[display.Id];

            if (index >= AvailableDevices.Count)
            {
                AvailableDevices.Add(device);
            }
            else
            {
                AvailableDevices[index] = device;
            }
        }
        public Sdl2DisplayDeviceDriver()
        {
            int displays = SDL.GetNumVideoDisplays();

            for (int d = 0; d < displays; d++)
            {
                Rect bounds;
                SDL.GetDisplayBounds(d, out bounds);

                DisplayMode current_mode;
                SDL.GetCurrentDisplayMode(d, out current_mode);

                var mode_list = new List <DisplayResolution>();
                int num_modes = SDL.GetNumDisplayModes(d);
                for (int m = 0; m < num_modes; m++)
                {
                    DisplayMode sdl_mode;
                    SDL.GetDisplayMode(d, m, out sdl_mode);
                    mode_list.Add(new DisplayResolution(
                                      bounds.X, bounds.Y,
                                      sdl_mode.Width, sdl_mode.Height,
                                      TranslateFormat(sdl_mode.Format),
                                      sdl_mode.RefreshRate));
                }

                var current_resolution = new DisplayResolution(
                    bounds.X, bounds.Y,
                    current_mode.Width, current_mode.Height,
                    TranslateFormat(current_mode.Format),
                    current_mode.RefreshRate);

                var device = new DisplayDevice(
                    current_resolution, d == 0, mode_list, TranslateBounds(bounds), d);

                AvailableDevices.Add(device);
                if (d == 0)
                {
                    Primary = device;
                }
            }
        }
Ejemplo n.º 20
0
        private static void stopMiningOnDeviceWithUuid(string uuid)
        {
            string errMsgForUuid = $"Cannot stop device with uuid {uuid}";
            // get device with uuid if it exists, devs can be single device uuid
            var deviceWithUUID = AvailableDevices.GetDeviceWithUuidOrB64Uuid(uuid);

            if (deviceWithUUID == null)
            {
                throw new RpcException($"{errMsgForUuid}. Device not found.", ErrorCode.NonExistentDevice);
            }
            if (deviceWithUUID.IsDisabled)
            {
                throw new RpcException($"{errMsgForUuid}. Device is disabled.", ErrorCode.DisabledDevice);
            }
            var(success, msg) = ApplicationStateManager.StopDevice(deviceWithUUID);
            if (!success)
            {
                // TODO this can also be an error
                throw new RpcException($"{errMsgForUuid}. {msg}.", ErrorCode.RedundantRpc);
            }
        }
Ejemplo n.º 21
0
        public CameraSnapshot()
        {
            InitializeComponent();

            if (AvailableDevices.Count == 0)
            {
                foreach (var devices in WebcamDevice.VideoDevices)
                {
                    AvailableDevices.Add(devices);
                }
            }

            SelectedDevice = AvailableDevices.LastOrDefault(id => SelectedDeviceId == id.UsbId)
                             ?? AvailableDevices.LastOrDefault();

            Unloaded += delegate
            {
                SelectedDeviceId     = SelectedDevice?.UsbId;
                Webcam.VideoSourceId = "";
            };
        }
        public async Task EnumerateDevicesAsync()
        {
            try
            {
                var DeviceInfos = await DeviceInformation.FindAllAsync(DeviceSelector);

                AvailableDevices.Clear();

                if (DeviceInfos.Count > 0)
                {
                    foreach (var deviceInfo in DeviceInfos)
                    {
                        AvailableDevices.Add(deviceInfo);
                    }
                }
            }
            catch (Exception)
            {
                CloseDevice();
            }
        }
Ejemplo n.º 23
0
        private void UpdateDisplays(int fd)
        {
            lock (this)
            {
                AvailableDevices.Clear();
                DisplayIds.Clear();

                var displays = new List <LinuxDisplay>();
                if (QueryDisplays(fd, displays))
                {
                    foreach (var display in displays)
                    {
                        AddDisplay(display);
                    }
                }

                if (AvailableDevices.Count == 0)
                {
                    Debug.Print("[KMS] Failed to find any active displays");
                }
            }
        }
Ejemplo n.º 24
0
 public void PopulateAvailableDevices()
 {
     AvailableDevices = new AvailableDevices();
     if (Directory.Exists(Settings.Default.EcuFlashDefRepoPath) && (Directory.GetDirectories(Settings.Default.EcuFlashDefRepoPath).Length > 0 || Directory.GetFiles(Settings.Default.EcuFlashDefRepoPath).Length < 1))
     {
         Trace.WriteLine("Loading definitions from: " + Settings.Default.EcuFlashDefRepoPath);
         AvailableDevices.Populate(Settings.Default.EcuFlashDefRepoPath);
     }
     else
     {
         if (!Directory.Exists(Settings.Default.EmbeddedDefRepoPath))
         {
             Directory.CreateDirectory(Settings.Default.EmbeddedDefRepoPath);
         }
         if (Directory.GetFiles(Settings.Default.EmbeddedDefRepoPath).Length < 1)
         {
             CopyEmbeddedDefs();
         }
         Trace.WriteLine("Loading definitions from: " + Settings.Default.EmbeddedDefRepoPath);
         AvailableDevices.Populate(Settings.Default.EmbeddedDefRepoPath);
     }
 }
        private async void OnScanForDevicesCommand()
        {
            if (!ScanningForDevices)
            {
                ScanningForDevices = true;
                ScanForDevicesCommand.RaiseCanExecuteChanged();

                if (CrossBleAdapter.Current.Status == AdapterStatus.PoweredOn || CrossBleAdapter.Current.Status == AdapterStatus.Unsupported)
                {
                    AvailableDevices.Clear();
                    foundDevices.Clear();
                    try
                    {
                        bleService.ScanForDevicesCommand(TimeSpan.FromSeconds(10), device =>
                        {
                            if (device != null)
                            {
                                foundDevices.Add(device.Name, device);
                                AvailableDevices.Add(device.Name);
                            }
                        });
                        await Task.Delay(TimeSpan.FromSeconds(10));

                        ScanningForDevices = false;
                        ScanForDevicesCommand.RaiseCanExecuteChanged();
                    }
                    catch (Exception e)
                    {
                        // Crashes.TrackError(e);
                        ScanningForDevices = false;
                        ScanForDevicesCommand.RaiseCanExecuteChanged();
                    }
                }
                else
                {
                    await dialogService.DisplayAlertAsync("Bluetooth", "Please check your Bluetooth Settings", "Ok");
                }
            }
        }
Ejemplo n.º 26
0
        private static bool SetDevicesEnabled(string devs, bool enabled)
        {
            bool allDevices = devs == "*";
            // get device with uuid if it exists, devs can be single device uuid
            var deviceWithUUID = AvailableDevices.GetDeviceWithUuidOrB64Uuid(devs);

            // Check if RPC should execute
            // check if redundant rpc
            if (allDevices && enabled && ApplicationStateManager.IsEnableAllDevicesRedundantOperation())
            {
                throw new RpcException("All devices are already enabled.", ErrorCode.RedundantRpc);
            }
            // all disable
            if (allDevices && !enabled && ApplicationStateManager.IsDisableAllDevicesRedundantOperation())
            {
                throw new RpcException("All devices are already disabled.", ErrorCode.RedundantRpc);
            }
            // if single and doesn't exist
            if (!allDevices && deviceWithUUID == null)
            {
                throw new RpcException("Device not found", ErrorCode.NonExistentDevice);
            }
            // if we have the device but it is redundant
            if (!allDevices && deviceWithUUID.IsDisabled == !enabled)
            {
                var stateStr = enabled ? "enabled" : "disabled";
                throw new RpcException($"Devices with uuid {devs} is already {stateStr}.", ErrorCode.RedundantRpc);
            }

            // if got here than we can execute the call
            ApplicationStateManager.SetDeviceEnabledState(null, (devs, enabled));
            // TODO invoke the event for controls that use it
            OnDeviceUpdate?.Invoke(null, new DeviceUpdateEventArgs(AvailableDevices.Devices.ToList()));
            // TODO this used to return 'anyStillRunning' but we are actually checking if there are any still enabled left
            var anyStillEnabled = AvailableDevices.Devices.Any();

            return(anyStillEnabled);
        }
Ejemplo n.º 27
0
        private void OnLoadDevicesCommand()
        {
            IsBusy = true;

            try
            {
                if (BluetoothAdapter.DefaultAdapter != null && BluetoothAdapter.DefaultAdapter.IsEnabled)
                {
                    foreach (var pairedDevice in BluetoothAdapter.DefaultAdapter.BondedDevices)
                    {
                        AvailableDevices.Add(pairedDevice);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 28
0
        protected Miner(string minerDeviceName, List <MiningPair> miningPairs, string groupKey)
        {
            MiningPairs = miningPairs;
            IsInit      = MiningPairs != null && MiningPairs.Count > 0;
            if (IsInit)
            {
                foreach (var pair in miningPairs)
                {
                    // for PRODUCTION we still need these indexes get rid of this when possible
                    var cDev  = AvailableDevices.GetDeviceWithUuidOrB64Uuid(pair.Device.UUID);
                    var index = cDev?.Index ?? -1;
                    if (index < 0)
                    {
                        continue;
                    }
                    DevIndexes.Add(index);
                }
            }

            GroupKey = groupKey;

            MinerDeviceName = minerDeviceName;
            Logger.Info(MinerTag(), "NEW MINER CREATED");
        }
        async Task LoadAvailableDevicesAsync()
        {
            try
            {
                IsLoadingDevices = true;

                var availableNetworks = await DeviceDriveManager.Current.GetAvailableDevicesAsync(null);

                foreach (var network in availableNetworks)
                {
                    AvailableDevices.Add(network);
                }

                // We have a list of devices, do nothing, just wait for a device selection
                IsWaitingForNetwork   = false;
                WaitingLabel          = string.Empty;
                IsLoadingDevices      = false;
                NoDevicesFoundVisible = !AvailableDevices.Any();
            }
            catch (TaskCanceledException)
            {
                // Swallow
            }
        }
Ejemplo n.º 30
0
        public void RefreshDisplayDevices()
        {
            lock (display_lock)
            {
                // Store an array of the current available DisplayDevice objects.
                // This is needed to preserve the original resolution.
                var previousDevices = AvailableDevices.ToArray();

                AvailableDevices.Clear();

                // We save all necessary parameters in temporary variables
                // and construct the device when every needed detail is available.
                // The main DisplayDevice constructor adds the newly constructed device
                // to the list of available devices.
                DisplayDevice     opentk_dev;
                DisplayResolution opentk_dev_current_res = null;
                var  opentk_dev_available_res            = new List <DisplayResolution>();
                bool opentk_dev_primary = false;
                uint device_count = 0, mode_count = 0;

                // Get available video adapters and enumerate all monitors
                while (User32.DeviceContext.EnumDisplayDevices(null, device_count++, out var dev1, 0))
                {
                    if ((dev1.StateFlags & DisplayDeviceStateFlags.AttachedToDesktop) == 0)
                    {
                        continue;
                    }

                    // The second function should only be executed when the first one fails
                    // (e.g. when the monitor is disabled)
                    if (User32.DeviceContext.EnumDisplaySettingsEx(dev1.DeviceName, DisplayModeSetting.CurrentSettings,
                                                                   out DeviceMode monitor_mode, 0) ||
                        User32.DeviceContext.EnumDisplaySettingsEx(dev1.DeviceName, DisplayModeSetting.RegistrySettings,
                                                                   out monitor_mode, 0))
                    {
                        VerifyMode(dev1, monitor_mode);

                        var scale = GetScale(ref monitor_mode);
                        opentk_dev_current_res = new DisplayResolution(
                            (int)(monitor_mode.DisplayOptions.Position.X / scale),
                            (int)(monitor_mode.DisplayOptions.Position.Y / scale),
                            (int)(monitor_mode.WidthInPixels / scale),
                            (int)(monitor_mode.HeightInPixels / scale),
                            (int)monitor_mode.BitsPerPixel,
                            monitor_mode.DisplayFrequency
                            );

                        opentk_dev_primary = (dev1.StateFlags & DisplayDeviceStateFlags.PrimaryDevice) != 0;
                    }

                    opentk_dev_available_res.Clear();
                    mode_count = 0;
                    while (User32.DeviceContext.EnumDisplaySettingsEx(dev1.DeviceName, (DisplayModeSetting)mode_count++, out monitor_mode, 0))
                    {
                        VerifyMode(dev1, monitor_mode);

                        var scale = GetScale(ref monitor_mode);
                        var res   = new DisplayResolution(
                            (int)(monitor_mode.DisplayOptions.Position.X / scale),
                            (int)(monitor_mode.DisplayOptions.Position.Y / scale),
                            (int)(monitor_mode.WidthInPixels / scale),
                            (int)(monitor_mode.HeightInPixels / scale),
                            (int)monitor_mode.BitsPerPixel,
                            monitor_mode.DisplayFrequency
                            );

                        opentk_dev_available_res.Add(res);
                    }

                    // Construct the OpenTK DisplayDevice through the accumulated parameters.
                    // The constructor will automatically add the DisplayDevice to the list
                    // of available devices.
#pragma warning disable 612,618
                    opentk_dev = new DisplayDevice(
                        opentk_dev_current_res,
                        opentk_dev_primary,
                        opentk_dev_available_res,
                        opentk_dev_current_res.Bounds,
                        dev1.DeviceName
                        );
#pragma warning restore 612,618

                    // Set the original resolution if the DisplayDevice was previously available.
                    foreach (var existingDevice in previousDevices)
                    {
                        if ((string)existingDevice.Id == (string)opentk_dev.Id)
                        {
                            opentk_dev.OriginalResolution = existingDevice.OriginalResolution;
                        }
                    }

                    AvailableDevices.Add(opentk_dev);

                    if (opentk_dev_primary)
                    {
                        Primary = opentk_dev;
                    }

                    Debug.Print("DisplayDevice {0} ({1}) supports {2} resolutions.",
                                device_count, opentk_dev.IsPrimary ? "primary" : "secondary",
                                opentk_dev.AvailableResolutions.Count);
                }
            }
        }