public void AddFakeCamera()
        {
            FakeCameraDevice device = new FakeCameraDevice();

            ConnectedDevices.Add(device);
            SelectedCameraDevice = device;
        }
Exemple #2
0
        public void Connect(EventHandler <SaleaeStringEventArgs> saleaeApiMonitor = null,
                            EventHandler <LoggingEventArgs> loggingEventHandler   = null)
        {
            saleae = new SocketAPI(host, port);

            if (saleaeApiMonitor != null)
            {
                saleae.SaleaeStringEvent += saleaeApiMonitor;
            }
            CallerLoggingEventHandler = loggingEventHandler;

            connDevs = saleae.GetConnectedDevices();
            dev      = (from d in connDevs where d.type == "LOGIC_PRO_16_DEVICE" select d).FirstOrDefault();
            if (dev.index == 0)
            {   // Can't find logic pro 16.  Just pick the first one.
                var dLst   = (from d in connDevs where d.index > 0 select d);
                var minIdx = (from d in dLst select d.index).Min();
                dev = (from d in dLst where d.index == minIdx select d).FirstOrDefault();
            }

            if (dev.index != 0)
            {
                saleae.SelectActiveDevice(dev.index);
            }
            else
            {   // Can't find any device.  Not sure what is wrong.
                saleae = null;
            }

            OnPropertyChanged("HasConnection");
        }
Exemple #3
0
        private async Task Enumerate()
        {
            try
            {
                var enumerator = new Enumerator();
                Logger.Log(LogSeverity.Info, $"Starting enumeration, targeting any compatible devices.");
                while (enumerator.Devices.Count == 0)
                {
                    await enumerator.Run(Target);

                    await Task.Delay(10);
                }

                Logger.Log(LogSeverity.Info, $"Enumeration complete for target, found {enumerator.Devices.Count} devices.");
                var i = 1;
                enumerator.Devices.ForEach(_dev =>
                {
                    ConnectedDevices.Add(new Device((int)_dev.Info.ProductId, _dev.FriendlyName, _dev.Target));
                    Logger.Log(LogSeverity.Info, $"{i} - {_dev.FriendlyName} | {_dev.Info.DeviceId} | {_dev.Target}.");
                    i++;
                });
            }
            catch (Exception e)
            {
                Logger.Log(LogSeverity.Error, e.Message);
                Step = FlashingStep.Error;
            }
        }
Exemple #4
0
        public IDevice Connect(IDeviceInfo deviceInfo)
        {
            MsHidDeviceInfo hidDeviceInfo = deviceInfo as MsHidDeviceInfo;

            if (hidDeviceInfo == null)
            {
                throw new ArgumentException("The specified DeviceInfo does not belong to this DeviceProvider.", "deviceInfo");
            }


            ReportWiimote wiimote;

            if (!TryConnect(hidDeviceInfo, out wiimote))
            {
                UseSetOutputReport = !UseSetOutputReport;
                if (!TryConnect(hidDeviceInfo, out wiimote))
                {
                    throw new DeviceConnectException("Both methods of connecting timed out.");
                }
            }

            wiimote.Disconnected += device_Disconnected;
            ConnectedDevices.Add(wiimote);
            MsHidDeviceProviderHelper.SetDevicePathConnected(hidDeviceInfo.DevicePath, true);

            OnDeviceConnected(new DeviceEventArgs(wiimote));
            return(wiimote);
        }
        public void AddFakeCamera()
        {
            FakeCameraDevice device = new FakeCameraDevice();

            ConnectedDevices.Add(device);
            NewCameraConnected(device);
        }
Exemple #6
0
 public void CloseAll()
 {
     foreach (ICameraDevice connectedDevice in ConnectedDevices.Where(connectedDevice => connectedDevice.IsConnected))
     {
         connectedDevice.Close();
     }
 }
 private async void DeviceFound(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs btAdv)
 {
     if (!ConnectedDevices.Contains(btAdv.Advertisement.LocalName) && _devices.Contains(btAdv.Advertisement.LocalName))
     {
         await Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
         {
             var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
             if (device.GattServices.Any())
             {
                 ConnectedDevices.Add(device.Name);
                 device.ConnectionStatusChanged += async(sender, args) =>
                 {
                     if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected)
                     {
                         await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                         {
                             ConnectedDevices
                             .Remove(
                                 sender
                                 .Name);
                         });
                     }
                 };
                 SetupWaxStream(device);
             }
             else if (device.DeviceInformation.Pairing.CanPair && !device.DeviceInformation.Pairing.IsPaired)
             {
                 await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);
             }
         });
     }
 }
Exemple #8
0
        private void AfterReceive(IAsyncResult ar)
        {
            byte[]     received;
            string     receivedStr;
            ThisDevice clObject = (ThisDevice)ar.AsyncState;

            try
            {
                received      = udpCli.EndReceive(ar, ref iPep);
                receivedStr   = Encoding.UTF8.GetString(received);
                clObject.ipEp = iPep;
                clObject.data = receivedStr;

                //Console.WriteLine(clObject.Data);
                if (receivedStr == "DISCOVER_XSTREAM_SERVER")
                {
                    Console.WriteLine("RECV_" + receivedStr);
                    data = Encoding.ASCII.GetBytes("DISCOVER_XSTREAM_CLIENT");
                    Console.WriteLine("SEND_DISCOVER_XSTREAM_CLIENT");
                    udpCli.Send(data, data.Length, iPep);
                }
                else if (receivedStr == "ADD_SUCCESS")
                {
                    Console.WriteLine("RECEIVE_ADD_SUCCESS");
                    ConnectedDevices.ManipClientObject(clObject);
                }
                else if (receivedStr == "REMOVE_THIS_DEVICE")
                {
                    Console.WriteLine("RECEIVE_REMOVE_THIS_CLIENT");
                    ConnectedDevices.ManipClientObject(clObject);
                }
                Console.WriteLine("True");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("False");
            }

            if (!bWorker.CancellationPending)
            {
                try
                {
                    Console.WriteLine(iPep.Address.ToString());
                    //AvailableDevices.ManipThisDevice(clObject);
                    bWorker.ReportProgress(0, clObject);

                    ThisDevice cliObj = new ThisDevice();
                    data        = new byte[1024];
                    iPep        = new IPEndPoint(IPAddress.Any, 8810);
                    cliObj.ipEp = iPep;
                    Console.WriteLine("Beginning receive");
                    udpCli.BeginReceive(new AsyncCallback(AfterReceive), cliObj);
                }
                catch (Exception expc)
                {
                    MessageBox.Show(expc.Message);
                }
            }
        }
Exemple #9
0
        private async void _server_ConnectionRequest(object sender, ResonanceListeningServerConnectionRequestEventArgs <BluetoothAdapter> e)
        {
            IResonanceTransporter transporter = ResonanceTransporter.Builder
                                                .Create()
                                                .WithAdapter(e.Accept())
                                                .WithJsonTranscoding()
                                                .Build();

            transporter.StateChanged += (x, ee) =>
            {
                if (ee.NewState != ResonanceComponentState.Connected)
                {
                    InvokeUI(() =>
                    {
                        ConnectedDevices.Remove(transporter);
                    });
                }
            };

            transporter.RegisterRequestHandler <ChatMessageRequest, ChatMessageResponse>(OnChatRequest);

            await transporter.ConnectAsync();

            InvokeUI(() =>
            {
                ConnectedDevices.Add(transporter);
                if (SelectedDevice == null)
                {
                    SelectedDevice = transporter;
                }
            });
        }
        public void Connect(EventHandler<SaleaeStringEventArgs> saleaeApiMonitor = null,
            EventHandler<LoggingEventArgs> loggingEventHandler = null)
        {
            saleae = new SocketAPI(host, port);

            if (saleaeApiMonitor != null)
            {
                saleae.SaleaeStringEvent += saleaeApiMonitor;
            }
            CallerLoggingEventHandler = loggingEventHandler;

            connDevs = saleae.GetConnectedDevices();
            dev = (from d in connDevs where d.type == "LOGIC_PRO_16_DEVICE" select d).FirstOrDefault();
            if( dev.index == 0 )
            {   // Can't find logic pro 16.  Just pick the first one.
                var dLst = (from d in connDevs where d.index > 0 select d);
                var minIdx = (from d in dLst select d.index).Min();
                dev = (from d in dLst where d.index == minIdx select d ).FirstOrDefault();
            }

            if (dev.index != 0)
            {
                saleae.SelectActiveDevice(dev.index);
            }
            else
            {   // Can't find any device.  Not sure what is wrong.
                saleae = null;
            }

            OnPropertyChanged("HasConnection");
        }
Exemple #11
0
        public async Task <T> EstablishDeviceConnectionByPort <T>(byte port) where T : IDevice
        {
            while (!ConnectedDevices.ContainsKey(port) || !ConnectedDevices[port].IsReady)
            {
                await Task.Delay(250);
            }

            return((T)ConnectedDevices[port]);
        }
        private async void ConnectDisconnectDevice(object sender, EventArgs e)
        {
            HttpResponseMessage result;

            if (isConnectedDeviceSelected)
            {
                result = await Services.WithingsService.DisconnectDeviceAsync(selectedDevice.Identifier.System, selectedDevice.Identifier.Value);
            }
            else
            {
                result = await Services.WithingsService.ConnectDeviceAsync(selectedDevice.Identifier.System, selectedDevice.Identifier.Value);
            }

            if (result.IsSuccessStatusCode)
            {
                List <object> connectedDevices    = new List <object>();
                List <object> disconnectedDevices = new List <object>();

                var res = await Services.WithingsService.GetDevices(connectedDevices, disconnectedDevices);

                if (res == System.Net.HttpStatusCode.OK)
                {
                    ConnectedDevices.Clear();
                    DisconnectedDevices.Clear();
                    ConnectedDevices    = new ObservableCollection <object>(connectedDevices);
                    DisconnectedDevices = new ObservableCollection <object>(disconnectedDevices);
                }
                else if (res == System.Net.HttpStatusCode.Conflict)
                {
                    await DisplayAlert("Conflict", "Previous user delete operation is in progress. Please try again later", "Ok");
                }
                else
                {
                    await DisplayAlert("Error", "Something went wrong. Please try again", "Ok");
                }
            }
            else
            {
                await DisplayAlert("Withing auth failed", "Something went wrong. Please try again", "Ok");
            }

            OnAppearing();

            if (result.IsSuccessStatusCode)
            {
                actionButton.IsEnabled      = false;
                actionButton.Text           = "Select Device";
                selectedDevice.IsSelected   = false;
                selectedDevice              = null;
                deviceContentView.IsVisible = false;
            }

            if (Device.Idiom == TargetIdiom.Tablet)
            {
                actionButton.IsVisible = false;
            }
        }
Exemple #13
0
 public Guid DeviceDescriptorToInstanceGuid(DeviceDescriptor deviceDescriptor)
 {
     if (ConnectedDevices.ContainsKey(deviceDescriptor.DeviceHandle) &&
         ConnectedDevices[deviceDescriptor.DeviceHandle].Count >= deviceDescriptor.DeviceInstance)
     {
         return(ConnectedDevices[deviceDescriptor.DeviceHandle][deviceDescriptor.DeviceInstance]);
     }
     throw new Exception($"Could not find device Handle {deviceDescriptor.DeviceHandle}, Instance {deviceDescriptor.DeviceInstance}");
     //return Guid.Empty;
 }
Exemple #14
0
        void device_Disconnected(object sender, EventArgs e)
        {
            ReportWiimote   wiimote    = (ReportWiimote)sender;
            MsHidDeviceInfo deviceInfo = (MsHidDeviceInfo)wiimote.DeviceInfo;

            wiimote.Disconnected -= device_Disconnected;
            ConnectedDevices.Remove(wiimote);
            MsHidDeviceProviderHelper.SetDevicePathConnected(deviceInfo.DevicePath, false);
            OnDeviceDisconnected(new DeviceEventArgs(wiimote));
        }
Exemple #15
0
        public void DisconnectAll()
        {
            List <Task> disconnectTasks = new List <Task>();

            foreach (var connectedDevice in ConnectedDevices.ToArray())
            {
                var t = Task.Run(() => connectedDevice.Disconnect());

                disconnectTasks.Add(t);
            }

            Task.WaitAll(disconnectTasks.ToArray());
        }
Exemple #16
0
 private void CheckListOfDevicesForNulls()
 {
     if (ConnectedDevices.Count == 0)
     {
         return;
     }
     for (int i = ConnectedDevices.Count - 1; i >= 0; i--)
     {
         if (ConnectedDevices[i] == null)
         {
             UnityEngine.Debug.Log($"{this.name} has a null value in {i}.");
             ConnectedDevices.RemoveAt(i);
         }
     }
 }
        public Device FindCompanionDevice(Log log, Device device)
        {
            var companion = ConnectedDevices.Where((v) => v.DeviceIdentifier == device.CompanionIdentifier);

            if (companion.Count() == 0)
            {
                throw new Exception($"Could not find the companion device for '{device.Name}'");
            }

            if (companion.Count() > 1)
            {
                log.WriteLine("Found {0} companion devices for {1}?!?", companion.Count(), device.Name);
            }

            return(companion.First());
        }
        protected BluetoothLEManager()
        {
            CentralManager = new CBCentralManager(DispatchQueue.CurrentQueue);
            CentralManager.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) =>
            {
                Console.WriteLine("DiscoveredPeripheral: " + e.Peripheral.Name);
                DiscoveredDevices.Add(e.Peripheral);
                DeviceDiscovered(this, e);
            };

            CentralManager.UpdatedState += (object sender, EventArgs e) =>
            {
                Console.WriteLine("UpdatedState: " + CentralManager.State);
            };


            CentralManager.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) =>
            {
                Console.WriteLine("ConnectedPeripheral: " + e.Peripheral.Name);

                // When a peripheral gets connected, add that peripheral to our running list of
                // connected peripherals
                if (!ConnectedDevices.Contains(e.Peripheral))
                {
                    ConnectedDevices.Add(e.Peripheral);
                }

                // raise our connected event
                DeviceConnected(sender, e);
            };

            CentralManager.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) =>
            {
                Console.WriteLine("DisconnectedPeripheral: " + e.Peripheral.Name);

                // When a peripheral disconnects, remove it from our running list.
                if (ConnectedDevices.Contains(e.Peripheral))
                {
                    ConnectedDevices.Remove(e.Peripheral);
                }

                // Raise our disconnected event
                DeviceDisconnected(sender, e);
            };
        }
        public async Task <IHardwareDevice> FindCompanionDevice(ILog log, IHardwareDevice device)
        {
            await LoadDevices(log, false, false);

            var companion = ConnectedDevices.Where((v) => v.DeviceIdentifier == device.CompanionIdentifier);

            if (companion.Count() == 0)
            {
                throw new Exception($"Could not find the companion device for '{device.Name}'");
            }

            if (companion.Count() > 1)
            {
                log.WriteLine("Found {0} companion devices for {1}?!?", companion.Count(), device.Name);
            }

            return(companion.First());
        }
Exemple #20
0
        /// <summary>
        /// Connect to a device.
        /// </summary>
        /// <param name="device">The device.</param>
        public async void ConnectToDevice(IDevice device)
        {
            var peripheral = device.NativeDevice as CBPeripheral;

            _central.ConnectPeripheral(peripheral);

            await Task.Delay(ConnectionTimeout);

            if (ConnectedDevices.All(x => x.Id != device.Id))
            {
                _central.CancelPeripheralConnection(peripheral);
                var args = new DeviceConnectionEventArgs(device)
                {
                    ErrorMessage = "The device connection timed out."
                };

                DeviceFailedToConnect(this, args);
            }
        }
Exemple #21
0
        protected BluetoothLeManager()
        {
            CentralBleManager = new CBCentralManager(DispatchQueue.CurrentQueue);
            DiscoveredDevices = new List <CBPeripheral>();
            CentralBleManager.DiscoveredPeripheral += (sender, e) =>
            {
                Mvx.Trace("DiscoveredPeripheral: {0}", e.Peripheral.Name);
                DiscoveredDevices.Add(e.Peripheral);
                DeviceDiscovered(this, e);
            };

            CentralBleManager.UpdatedState +=
                (sender, e) => { Mvx.Trace("UpdatedState: {0}", CentralBleManager.State); };

            CentralBleManager.ConnectedPeripheral += (sender, e) =>
            {
                Mvx.Trace("ConnectedPeripheral: " + e.Peripheral.Name);

                // when a peripheral gets connected, add that peripheral to our running list of connected peripherals
                if (!ConnectedDevices.Contains(e.Peripheral))
                {
                    ConnectedDevices.Add(e.Peripheral);
                }

                // raise our connected event
                DeviceConnected(sender, e);
            };

            CentralBleManager.DisconnectedPeripheral += (sender, e) =>
            {
                Mvx.Trace("DisconnectedPeripheral: " + e.Peripheral.Name);

                // when a peripheral disconnects, remove it from our running list.
                if (ConnectedDevices.Contains(e.Peripheral))
                {
                    ConnectedDevices.Remove(e.Peripheral);
                }

                // raise our disconnected event
                DeviceDisconnected(sender, e);
            };
        }
Exemple #22
0
        public mainForm()
        {
            int cnt = 0;

            Console.WriteLine(Dns.GetHostName());
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress addr in localIPs)
            {
                if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ConnectedDevices.GetCompiled(addr);
                    Console.WriteLine(addr);
                }
                cnt++;
            }
            InitializeComponent();
            //string str = SerializationFunctions.Serialize(new ThisDevice());
            //Console.WriteLine(str);
            cnt++;
        }
Exemple #23
0
        protected override async void OnAppearing()
        {
            await FetchDevices();

            if (ConnectedDevices.Count > 0)
            {
                await FetchObservations();
            }

            BindingContext = this;

            DataTemplate template = (DataTemplate)this.Resources["withingsDeviceDataTemplate"];

            connectedDevicesWrapLayout.Children.Clear();
            foreach (var connectedItem in ConnectedDevices)
            {
                Controls.ContentPresenter contentPresenter = BuildContentPresenter(template, connectedItem, false, true);
                connectedDevicesWrapLayout.Children.Add(contentPresenter);
            }

            template = (DataTemplate)this.Resources["withingsObservationDataTemplate"];
            observationListWrapLayout.Children.Clear();
            foreach (var observation in observationCategories)
            {
                Controls.ContentPresenter observationPresenter = BuildObservationPresenter(template, observation.Value);
                observationListWrapLayout.Children.Add(observationPresenter);
            }

            ManageDevicesButton  devicesButton        = new ManageDevicesButton();
            TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer();

            tapGestureRecognizer.Tapped += async(s, e) =>
            {
                await Navigation.PushAsync(new DeviceManagementPage(ConnectedDevices.ToList(), DisconnectedDevices.ToList()));
            };
            devicesButton.GestureRecognizers.Add(tapGestureRecognizer);
            connectedDevicesWrapLayout.Children.Add(devicesButton);

            base.OnAppearing();
        }
        public async Task <IHardwareDevice> FindDevice(RunMode runMode, ILog log, bool includeLocked, bool force)
        {
            DeviceClass [] deviceClasses = runMode switch
            {
                RunMode.iOS => new [] { DeviceClass.iPhone, DeviceClass.iPad, DeviceClass.iPod },
                RunMode.WatchOS => new [] { DeviceClass.Watch },
                RunMode.TvOS => new [] { DeviceClass.AppleTV },                // Untested
                _ => throw new ArgumentException(nameof(runMode)),
            };

            await LoadDevices(log, false, false);

            IEnumerable <IHardwareDevice> compatibleDevices = ConnectedDevices.Where(v => deviceClasses.Contains(v.DeviceClass) && v.IsUsableForDebugging != false);
            IHardwareDevice device;

            if (compatibleDevices.Count() == 0)
            {
                throw new NoDeviceFoundException($"Could not find any applicable devices with device class(es): {string.Join (", ", deviceClasses)}");
            }
            else if (compatibleDevices.Count() > 1)
            {
                device = compatibleDevices
                         .OrderBy(dev => Version.TryParse(dev.ProductVersion, out Version v) ? v : new Version())
                         .First();

                log.WriteLine("Found {0} devices for device class(es) '{1}': '{2}'. Selected: '{3}' (because it has the lowest version).",
                              compatibleDevices.Count(),
                              string.Join("', '", deviceClasses),
                              string.Join("', '", compatibleDevices.Select((v) => v.Name).ToArray()),
                              device.Name);
            }
            else
            {
                device = compatibleDevices.First();
            }

            return(device);
        }
Exemple #25
0
        // TODO: Combine this with code from DeviceManagementPage.cs
        private Controls.ContentPresenter BuildContentPresenter(DataTemplate template, object connectedItem, bool isConnected, bool showExtraInfo = false)
        {
            Models.Device device = JsonConvert.DeserializeObject <Models.Device>(connectedItem.ToString());

            device.IsConnected   = isConnected;
            device.ShowExtraInfo = showExtraInfo;

            Controls.ContentPresenter contentPresenter = new Controls.ContentPresenter()
            {
                BindingContext = device,
            };
            contentPresenter.ItemTemplate = template;
            TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer();

            // TODO: Change device tapped to go somewhere else?
            tapGestureRecognizer.Tapped += async(s, e) =>
            {
                await Navigation.PushAsync(new DeviceManagementPage(ConnectedDevices.ToList(), DisconnectedDevices.ToList()));
            };

            contentPresenter.GestureRecognizers.Add(tapGestureRecognizer);
            return(contentPresenter);
        }
Exemple #26
0
        public void RefreshConnectedDevices()
        {
            //ConnectedDevices = new ConcurrentDictionary<string, List<Guid>>();
            var diDeviceInstances = DiInstance.GetDevices();
            var connectedHandles  = ConnectedDevices.Keys.ToList();

            foreach (var device in diDeviceInstances)
            {
                if (!IsStickType(device))
                {
                    continue;
                }
                var joystick = new Joystick(DiInstance, device.InstanceGuid);
                var handle   = JoystickToHandle(joystick);
                if (connectedHandles.Contains(handle))
                {
                    connectedHandles.Remove(handle);
                }
                if (ConnectedDevices.ContainsKey(handle))
                {
                    if (ConnectedDevices[handle].Contains(device.InstanceGuid))
                    {
                        continue;
                    }
                }
                else
                {
                    ConnectedDevices[handle] = new List <Guid>();
                }
                ConnectedDevices[handle].Add(device.InstanceGuid);
            }

            foreach (var connectedHandle in connectedHandles)
            {
                ConnectedDevices.TryRemove(connectedHandle, out _);
            }
        }
Exemple #27
0
 private void ChannelWatcher_ClearDevices(object sender, System.EventArgs e)
 {
     AvailableChannels.Clear();
     ConnectedDevices.Clear();
 }
Exemple #28
0
        protected Adapter()
        {
            CentralManager = new CBCentralManager(DispatchQueue.CurrentQueue);

            CentralManager.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) =>
            {
                Console.WriteLine("DiscoveredPeripheral: " + e.Peripheral.Name);
                Device d = new Device(e.Peripheral);
                if (!ContainsDevice(DiscoveredDevices, e.Peripheral))
                {
                    DiscoveredDevices.Add(d);
                    DeviceDiscovered(this, new DeviceDiscoveredEventArgs()
                    {
                        Device = d
                    });
                }
            };

            CentralManager.UpdatedState += (object sender, EventArgs e) =>
            {
                Console.WriteLine("UpdatedState: " + CentralManager.State);
                _stateChanged.Set();
            };

            CentralManager.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) =>
            {
                Console.WriteLine("ConnectedPeripheral: " + e.Peripheral.Name);

                // When a peripheral gets connected, add that peripheral to our running list of
                // connected peripherals
                if (!ContainsDevice(ConnectedDevices, e.Peripheral))
                {
                    Device d = new Device(e.Peripheral);
                    ConnectedDevices.Add(new Device(e.Peripheral));
                    // raise our connected event
                    DeviceConnected(sender, new DeviceConnectionEventArgs()
                    {
                        Device = d
                    });
                }
            };

            CentralManager.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) =>
            {
                Console.WriteLine("DisconnectedPeripheral: " + e.Peripheral.Name);

                // when a peripheral disconnects, remove it from our running list.
                IDevice foundDevice = null;
                foreach (var d in ConnectedDevices)
                {
                    if (d.ID == Guid.ParseExact(e.Peripheral.Identifier.AsString(), "d"))
                    {
                        foundDevice = d;
                    }
                }

                if (foundDevice != null)
                {
                    ConnectedDevices.Remove(foundDevice);
                }

                // raise our disconnected event
                DeviceDisconnected(sender, new DeviceConnectionEventArgs()
                {
                    Device = new Device(e.Peripheral)
                });
            };

            CentralManager.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) =>
            {
                // raise the failed to connect event
                DeviceFailedToConnect(this, new DeviceConnectionEventArgs()
                {
                    Device       = new Device(e.Peripheral),
                    ErrorMessage = e.Error.Description
                });
            };
        }
        public IDevice Connect(IDeviceInfo deviceInfo)
        {
            int result;

            MsBluetoothDeviceInfo bluetoothDeviceInfo = deviceInfo as MsBluetoothDeviceInfo;

            if (bluetoothDeviceInfo == null)
            {
                throw new ArgumentException("The specified IDeviceInfo does not belong to this DeviceProvider.", "deviceInfo");
            }

            NativeMethods.BluetoothDeviceInfo bluetoothDevice = bluetoothDeviceInfo.Device;

            result = NativeMethods.BluetoothUpdateDeviceRecord(ref bluetoothDevice);
            NativeMethods.HandleError(result);

            if (bluetoothDevice.connected)
            {
                throw new NotImplementedException("The device is already connected.");
            }
            if (bluetoothDevice.remembered)
            {
                // Remove non-connected devices from MsBluetooth's device list.
                // This has to be done because:
                //     MsBluetooth can't connect to Hid devices without also pairing to them.
                // If you think that sounds crazy, you're on the right track.
                NativeMethods.RemoveDevice(bluetoothDevice.address);
            }

            Guid hidGuid = BluetoothServices.HumanInterfaceDeviceServiceClass_UUID;

            result = NativeMethods.BluetoothSetServiceState(IntPtr.Zero, ref bluetoothDevice, ref hidGuid, 0x0001);
            NativeMethods.HandleError(result);

            if (WaitTillConnected(bluetoothDevice.address, TimeSpan.FromSeconds(30)))
            {
                Thread.Sleep(2000);

                ReportDevice device = null;
                foreach (KeyValuePair <string, SafeFileHandle> pair in MsHidDeviceProviderHelper.GetWiiDeviceHandles())
                {
                    string         devicePath          = pair.Key;
                    SafeFileHandle fileHandle          = pair.Value;
                    Stream         communicationStream = new MsHidSetOutputReportStream(fileHandle);

                    // determine the device type
                    if (bluetoothDeviceInfo.Name == "Nintendo RVL-WBC-01")
                    {
                        device = new ReportBalanceBoard(deviceInfo, communicationStream);
                    }
                    else if (bluetoothDeviceInfo.Name == "Nintendo RVL-CNT-01")
                    {
                        device = new ReportWiimote(deviceInfo, communicationStream);
                    }
                    else
                    {
                        throw new ArgumentException("The specified deviceInfo with name '" + bluetoothDeviceInfo.Name + "' is not supported.", "deviceInfo");
                    }

                    if (MsHidDeviceProviderHelper.TryConnect(device, communicationStream, devicePath, fileHandle))
                    {
                        break;
                    }
                    device = null;
                }
                if (device != null)
                {
                    lookupFoundDevices.Remove(bluetoothDeviceInfo.Address);
                    foundDevices.Remove(bluetoothDeviceInfo);
                    OnDeviceLost(new DeviceInfoEventArgs(bluetoothDeviceInfo));

                    device.Disconnected += device_Disconnected;
                    ConnectedDevices.Add(device);
                    lookupConnectedDevices.Add(bluetoothDeviceInfo, device);
                    OnDeviceConnected(new DeviceEventArgs(device));
                    return(device);
                }
                else
                {
                    throw new DeviceConnectException("No working HID device found.");
                }
            }
            else
            {
                throw new TimeoutException("Timeout while trying to connect to the bluetooth device.");
            }
        }
Exemple #30
0
    internal void GetConnectedDevices()
    {
        connectedDevices.Clear();
        lines.Clear();
        Process proc = null;

        try
        {
            using (proc = new Process())
            {
                CurrActiveProcess = proc;
                System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(CommandProcessName + ".exe");
                procStartInfo.RedirectStandardInput  = true;
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.RedirectStandardError  = true;
                procStartInfo.UseShellExecute        = false;
                procStartInfo.CreateNoWindow         = true;
                proc.StartInfo          = procStartInfo;
                proc.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataHandlerForConnectedDevice);

                proc.Start();
                //print(proc.Id);
                proc.StandardInput.WriteLine("adb devices");
                proc.StandardInput.WriteLine("exit");

                for (int i = 0; !proc.StandardOutput.EndOfStream; i++)
                {
                    string line = proc.StandardOutput.ReadLine();
                    lines.Add(line);
                    //print (line);
                }

                proc.Close();

                if (lines.Count > 8)
                {
                    for (int i = 0; i < lines.Count - 8; i++)
                    {
                        DeviceState state = IsDeviceAuthorized(lines[i + 5]);
                        if (state == DeviceState.Online)
                        {
                            ConnectedDevices NewDevice = new ConnectedDevices();
                            NewDevice.DeviceID    = ExtractDeviceId(lines[i + 5]);
                            NewDevice.deviceState = state;


                            proc.Start();
                            proc.StandardInput.WriteLine("adb -s " + NewDevice.DeviceID + " shell getprop ro.product.model && exit");

                            string deviceName = "";
                            //proc.BeginErrorReadLine ();

                            string Line;
                            int    Counter = 0;
                            while ((Line = proc.StandardOutput.ReadLine()) != null)
                            {
                                if (Line.Length > 2 && !Line.Contains("exit") && !Line.Contains("Microsoft"))
                                {
                                    deviceName = Line;
                                }
                            }

                            NewDevice.DeviceName = deviceName;

                            connectedDevices.Add(NewDevice);

                            proc.WaitForExit();
                        }
                    }
                    proc.Close();
                }
                OnConnectedDevice();
            }
        }
        catch (System.Exception e)
        {
            UnityEngine.Debug.Log(e.ToString());
        }
        finally
        {
            OnFinallyCalledForAbort(Thread.CurrentThread);
            KillProcess(proc.Id);
        }
    }
Exemple #31
0
        public void ReceiveMessage(IMessage message)
        {
            if (message.MessageType == MessageType.Hub__Attached_IO)
            {
                var attachedIOMessage = new AttachedIOMessage(message.Bytes.ToArray());

                switch (attachedIOMessage.Event)
                {
                case IOEvent.Attached_IO:
                    switch (attachedIOMessage.DeviceType)
                    {
                    case IODeviceType.TechnicMotorL:
                        ConnectedDevices[attachedIOMessage.Port] = new TechnicMotorL(this, attachedIOMessage.Port);
                        break;

                    case IODeviceType.TechnicMotorXL:
                        ConnectedDevices[attachedIOMessage.Port] = new TechnicMotorXL(this, attachedIOMessage.Port);
                        break;
                    }
                    break;

                case IOEvent.Attached_Virtual_IO:
                    switch (attachedIOMessage.DeviceType)
                    {
                    case IODeviceType.LED_Light:
                        ConnectedDevices[attachedIOMessage.Port] = new LED(this, attachedIOMessage.Port);
                        break;
                    }
                    break;
                }
            }
            else if (message.MessageType == MessageType.Port_Information)
            {
                var portInformationMessage = new PortInformationMessage(message.Bytes.ToArray());

                if (ConnectedDevices.ContainsKey(portInformationMessage.Port))
                {
                    ConnectedDevices[portInformationMessage.Port].ReceiveMessage(portInformationMessage);
                }
            }
            else if (message.MessageType == MessageType.Port_Mode_Information)
            {
                var portModeInformationMessage = new PortModeInformationMessage(message.Bytes.ToArray());

                if (ConnectedDevices.ContainsKey(portModeInformationMessage.Port))
                {
                    ConnectedDevices[portModeInformationMessage.Port].ReceiveMessage(portModeInformationMessage);
                }
            }
            else if (message.MessageType == MessageType.Port_Input_Format__Single)
            {
                var portInputFormatMessage = new PortInputFormatSingleMessage(message.Bytes.ToArray());

                if (ConnectedDevices.ContainsKey(portInputFormatMessage.Port))
                {
                    ConnectedDevices[portInputFormatMessage.Port].ReceiveMessage(portInputFormatMessage);
                }
            }
            else if (message.MessageType == MessageType.Port_Input_Format__Combined_Mode)
            {
                var portInputFormatMessage = new PortInputFormatCombinedMessage(message.Bytes.ToArray());

                if (ConnectedDevices.ContainsKey(portInputFormatMessage.Port))
                {
                    ConnectedDevices[portInputFormatMessage.Port].ReceiveMessage(portInputFormatMessage);
                }
            }
            else if (message.MessageType == MessageType.Port_Value__Single)
            {
                var portValueMessage = new PortValueSingleMessage(message.Bytes.ToArray());

                if (ConnectedDevices.ContainsKey(portValueMessage.Port))
                {
                    ConnectedDevices[portValueMessage.Port].ReceiveMessage(portValueMessage);
                }
            }
            else if (message.MessageType == MessageType.Port_Value__Combined_Mode)
            {
                var portValueMessage = new PortValueCombinedMessage(message.Bytes.ToArray());

                if (ConnectedDevices.ContainsKey(portValueMessage.Port))
                {
                    ConnectedDevices[portValueMessage.Port].ReceiveMessage(portValueMessage);
                }
            }
            else
            {
                Messages.Enqueue(message);
            }
        }
Exemple #32
0
        /// <summary>
        /// Return the devices connected to the software
        /// </summary>
        /// <returns>Array of ConnectedDevices structs which contain device information</returns>
        public ConnectedDevices[] GetConnectedDevices()
        {
            String export_command = get_connected_devices_cmd;
            WriteString(export_command);

            String response = "";
            GetResponse(ref response);
            String[] response_strings = response.Split('\n');
            ConnectedDevices[] devices = new ConnectedDevices[response_strings.Length - 1];
            for (int i = 0; i < devices.Length; ++i)
            {
                String[] current_device = response_strings[i].Split(',');
                devices[i].type = current_device[2].Trim();
                devices[i].name = current_device[1].Trim();
                devices[i].index = int.Parse(current_device[0].Trim());
                devices[i].device_id = Convert.ToUInt64(current_device[3].Trim(), 16);
                if (current_device.Length > 4)
                    devices[i].is_active = true;
                else
                    devices[i].is_active = false;
            }
            return devices;
        }