Exemplo n.º 1
0
        public void FindDeviceAround()
        {
            try
            {
                Message       MsgSent      = new Message();
                List <Device> devicesFound = new List <Device>();
                while (true)
                {
                    devicesFound.Clear();
                    MsgSent.Pin        = Utils.GeneratePin();
                    MsgSent.DeviceName = Utils.GetDeviceName();
                    UdpMulticastSend(MsgSent);

                    CallWithTimeout(() =>
                    {
                        while (true)
                        {
                            WaitMessage(
                                (msg) => msg.Type == MsgType.Info && msg.Pin == MsgSent.Pin,
                                (remote, msg) => devicesFound.Add(new Device {
                                Addr = remote.Address.ToString(), Name = msg.DeviceName
                            }));
                        }
                    }, 3000);
                    OnDeviceFound?.Invoke(devicesFound);
                }
            }
            catch (OperationCanceledException)
            {
            }
        }
Exemplo n.º 2
0
        public void StartScanning()
        {
            if (CrossBleAdapter.Current.Status != AdapterStatus.PoweredOn)
            {
                // TODO: throw an exception
            }

            _isScanning = true;

            CrossBleAdapter.Current.Scan().Subscribe(scanResult => {
                if (!_isScanning || scanResult.AdvertisementData.LocalName != COSINUSS_DEVICE_NAME)
                {
                    return; // if the device name does not match the expected name return immediatly
                }

                _isScanning = false;
                CrossBleAdapter.Current.StopScan();

                OnDeviceFound?.Invoke(this, new CosinussDevice(scanResult.Device));
            });
        }
Exemplo n.º 3
0
        /// <summary>
        /// Scan all BLE devices in range. You can check if the returned device has the name that you're looking
        /// for. The address will be used to start a connection with the device.
        /// </summary>
        public static void StartScan(OnDeviceFound onDeviceFound)
        {
            CheckIfInitialized();

            if (CurrentState != State.ReadyToScan)
            {
                throw new Exception("You can only start a scan when you are Ready to Scan");
            }

            SetState(State.Scanning);
            Observable
            .Timer(TimeSpan.FromSeconds(0.1f))
            .Subscribe(_ =>
            {
                BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null,
                                                                            (address, name) => onDeviceFound(new Device
                {
                    Name = name, Address = address
                }), null, false, false);
            });
        }
Exemplo n.º 4
0
        public async void FindDeviceAroundAsync()
        {
            try
            {
                List <Device> devicesFound = new List <Device>();
                while (true)
                {
                    devicesFound.Clear();

                    TaskCompletionSource <bool> gotMsg = new TaskCompletionSource <bool>();
                    UdpReceived ev = (remote, arg) =>
                    {
                        if (arg.Handled)
                        {
                            return;
                        }
                        var msg = arg.Mess;
                        if (msg.Type == MsgType.Info && msg.Pin == 100000)
                        {
                            devicesFound.Add(new Device {
                                Addr = remote.Address.ToString(), Name = msg.DeviceName, Time = DateTime.Now
                            });
                            gotMsg.SetResult(true);
                        }
                    };
                    OnUdpReceived += ev;

                    await gotMsg.Task;
                    OnUdpReceived -= ev;

                    OnDeviceFound?.Invoke(devicesFound);
                }
            }
            catch (OperationCanceledException)
            {
            }
        }
Exemplo n.º 5
0
 // Overridden from ScanDelegate
 public void Start(OnDeviceFound onDeviceFound)
 {
     Log.D(this, "Starting scan");
     this.onDeviceFound = onDeviceFound;
     scanner.StartScan(this);
 }
Exemplo n.º 6
0
 // Overridden from ScanDelegate
 public void Stop()
 {
     Log.D(this, "Stopping scan");
     onDeviceFound = null;
     adapter.StopLeScan(this);
 }
Exemplo n.º 7
0
        /// <summary>
        /// Create Discovery tasks for a specific Network Interface
        /// </summary>
        /// <param name="netInterface"></param>
        /// <returns></returns>
        private static List <Task <List <Device> > > CreateDiscoverTasks(NetworkInterface netInterface)
        {
            var devices = new ConcurrentDictionary <string, Device>();
            List <Task <List <Device> > > tasks = new List <Task <List <Device> > >();

            try
            {
                GatewayIPAddressInformation addr = netInterface.GetIPProperties().GatewayAddresses.FirstOrDefault();

                if (addr != null && !addr.Address.ToString().Equals("0.0.0.0"))
                {
                    if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                    {
                        foreach (UnicastIPAddressInformation ip in netInterface.GetIPProperties().UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                for (int cpt = 0; cpt < 3; cpt++)
                                {
                                    Task <List <Device> > t = Task.Factory.StartNew <List <Device> >(() =>
                                    {
                                        Socket ssdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
                                        {
                                            Blocking            = false,
                                            Ttl                 = 1,
                                            UseOnlyOverlappedIO = true,
                                            MulticastLoopback   = false,
                                        };
                                        ssdpSocket.Bind(new IPEndPoint(ip.Address, 0));
                                        ssdpSocket.SetSocketOption(
                                            SocketOptionLevel.IP,
                                            SocketOptionName.AddMembership,
                                            new MulticastOption(_multicastEndPoint.Address));

                                        ssdpSocket.SendTo(_ssdpDiagram, SocketFlags.None, _multicastEndPoint);

                                        DateTime start = DateTime.Now;
                                        while (DateTime.Now - start < TimeSpan.FromSeconds(1))
                                        {
                                            int available = ssdpSocket.Available;

                                            if (available > 0)
                                            {
                                                byte[] buffer = new byte[available];
                                                int i         = ssdpSocket.Receive(buffer, SocketFlags.None);

                                                if (i > 0)
                                                {
                                                    string response = Encoding.UTF8.GetString(buffer.Take(i).ToArray());
                                                    Device device   = GetDeviceInformationsFromSsdpMessage(response);

                                                    //add only if no device already matching
                                                    if (devices.TryAdd(device.Hostname, device))
                                                    {
                                                        OnDeviceFound?.Invoke(null, new DeviceFoundEventArgs(device));
                                                    }
                                                }
                                            }
                                            Thread.Sleep(10);
                                        }

                                        return(devices.Values.ToList());
                                    });
                                    tasks.Add(t);
                                }
                            }
                        }
                    }
                }
            }
            catch { }

            return(tasks);
        }
Exemplo n.º 8
0
 extern public static int BS2_SetDeviceEventListener(IntPtr context, OnDeviceFound cbOnDeviceFound, OnDeviceAccepted cbOnDeviceAccepted, OnDeviceConnected cbOnDeviceConnected, OnDeviceDisconnected cbOnDeviceDisconnected);