Exemplo n.º 1
0
        public async Task <bool> init()
        {
            if (!string.IsNullOrEmpty(adapterId))
            {
                Instance = await BlueZManager.GetAdapterAsync(adapterId);

                return(true);
            }
            else
            {
                var adapters = await BlueZManager.GetAdaptersAsync();

                if (adapters.Count == 0)
                {
                    throw new Exception("No Bluetooth adapters found.");
                }

                Instance = adapters.First();
            }

            var adapterPath = Instance.ObjectPath.ToString();
            var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

            Console.WriteLine($"Using Bluetooth adapter {adapterName}");
            return(true);
        }
Exemplo n.º 2
0
        private static async Task Main(string[] args)
        {
            if (args.Length < 1 || args.Length == 3)
            {
                Console.WriteLine("Usage: subscribeToCharacteristic <deviceAddress>|<deviceNameSubstring> [adapterName] [serviceUUID characteristicUUID]");
                Console.WriteLine(@"Examples:
  subscribeToCharacteristic phone
  subscribeToCharacteristic 8C:8E:F2:AB:73:76 hci0 CAFE CFFE (see https://github.com/hashtagchris/early-iOS-BluetoothLowEnergy-tests/tree/master/myFirstPeripheral)");
                Console.WriteLine();
                Console.WriteLine($"Default service:        {DefaultServiceUUID}");
                Console.WriteLine($"Default characteristic: {DefaultCharacteristicUUID}");
                return;
            }

            s_deviceFilter = args[0];

            Adapter adapter;

            if (args.Length > 1)
            {
                adapter = await BlueZManager.GetAdapterAsync(args[1]);
            }
            else
            {
                var adapters = await BlueZManager.GetAdaptersAsync();

                if (adapters.Count == 0)
                {
                    throw new Exception("No Bluetooth adapters found.");
                }

                adapter = adapters.First();
            }

            s_serviceUUID = BlueZManager.NormalizeUUID(args.Length > 3
        ? args[2]
        : DefaultServiceUUID);

            s_characteristicUUID = BlueZManager.NormalizeUUID(args.Length > 3
        ? args[3]
        : DefaultCharacteristicUUID);

            var adapterPath = adapter.ObjectPath.ToString();
            var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

            Console.WriteLine($"Using Bluetooth adapter {adapterName}");

            adapter.PoweredOn   += adapter_PoweredOnAsync;
            adapter.DeviceFound += adapter_DeviceFoundAsync;

            Console.WriteLine("Waiting for events. Use Control-C to quit.");
            Console.WriteLine();
            await Task.Delay(-1);
        }
Exemplo n.º 3
0
 public async void LoadFirstAdapter()
 {
     try
     {
         adapter = (await BlueZManager.GetAdaptersAsync()).FirstOrDefault();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
Exemplo n.º 4
0
        static async Task Main(string[] args)
        {
            IAdapter1 adapter;
            var       adapters = await BlueZManager.GetAdaptersAsync();

            if (adapters.Count == 0)
            {
                Console.WriteLine("No Bluetooth adapters found");
                return;
            }

            adapter = adapters.First();
            var adapterPath = adapter.ObjectPath.ToString();
            var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

            Console.WriteLine($"Using Bluetooth adapter {adapterName}");

            // Print out the devices we already know about.
            var devices = await adapter.GetDevicesAsync();

            foreach (var device in devices)
            {
                string deviceDescription = await GetDeviceDescriptionAsync(device);

                Console.WriteLine(deviceDescription);
            }

            Console.WriteLine($"{devices.Count} device(s) found ahead of scan.");
            Console.WriteLine();

            // Scan for more devices.
            Console.WriteLine($"Scanning for {SecondsToScan} seconds...");

            int newDevices = 0;

            using (await adapter.WatchDevicesAddedAsync(async device => {
                newDevices++;
                // Write a message when we detect new devices during the scan.
                string deviceDescription = await GetDeviceDescriptionAsync(device);
                Console.WriteLine($"[NEW] {deviceDescription}");

//                await PrintDeviceInformation(device);
            }))
            {
                await adapter.StartDiscoveryAsync();

                await Task.Delay(TimeSpan.FromSeconds(SecondsToScan));

                await adapter.StopDiscoveryAsync();
            }

            Console.WriteLine($"Scan complete. {newDevices} new device(s) found");
        }
Exemplo n.º 5
0
        public async Task StartScan(CancellationToken ct)
        {
            // запускаемся и слушаем окружающие девайсы
            // при обнаружении устройств с нужными GATT характеристиками шлём на сервер пакет о том, что "видим" маячок
            IAdapter1 adapter;

            var adapters = await BlueZManager.GetAdaptersAsync();

            if (adapters.Count == 0)
            {
                throw new Exception("No Bluetooth adapters found.");
            }

            adapter = adapters.First();

            var adapterPath = adapter.ObjectPath.ToString();
            var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

            Console.WriteLine($"Using Bluetooth adapter {adapterName}");

            // Print out the devices we already know about.
            var devices = await adapter.GetDevicesAsync();

            foreach (var device in devices)
            {
                string deviceDescription = await GetDeviceDescriptionAsync(device);

                Console.WriteLine(deviceDescription);
            }
            Console.WriteLine($"{devices.Count} device(s) found ahead of scan.");

            int newDevices = 0;

            using (await adapter.WatchDevicesAddedAsync(async device =>
            {
                newDevices++;
                // Write a message when we detect new devices during the scan.
                string deviceDescription = await GetDeviceDescriptionAsync(device);
                Console.WriteLine($"[NEW] {deviceDescription}");
            }))
            {
                // запускаем дискаверинг устройств вокруг
                await adapter.StartDiscoveryAsync();

                // ждём до скончания времён или остановки приложения
                await Task.Delay(-1, ct).ContinueWith(t => { });

                await adapter.StopDiscoveryAsync();
            }
        }
Exemplo n.º 6
0
        public async Task <IBluetoothAdapter> GetAdapterAsync(string name)
        {
            IBluetoothAdapter adapter = null;

            if (name != null)
            {
                var dnbAdapter = await BlueZManager.GetAdapterAsync(name);

                adapter = new DotNetBlueZAdapter(dnbAdapter);
            }
            else
            {
                var adapters = await BlueZManager.GetAdaptersAsync();

                if (adapters.Count > 0)
                {
                    adapter = new DotNetBlueZAdapter(adapters.First());
                }
            }
            return(adapter);
        }
Exemplo n.º 7
0
        static async Task <int> Main(string[] args)
        {
            var adapter = (await BlueZManager.GetAdaptersAsync()).FirstOrDefault();

            if (adapter is null)
            {
                Console.Error.WriteLine("Could not find any bluetooth adapters.");
                return(-1);
            }

            var adapterPath = adapter.ObjectPath.ToString();
            var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

            Console.WriteLine($"Using Bluetooth adapter {adapterName}");

            adapter.DeviceFound += OnDeviceFoundAsync;
            await adapter.StartDiscoveryAsync();

            await Task.Delay(Timeout.Infinite);

            return(0);
        }
Exemplo n.º 8
0
        protected static async Task <IDevice1?> ScanAndConnectInternal(ScanFilter filter,
                                                                       TimeSpan?timeout = null,
                                                                       string?adapter   = null)
        {
            // Default value
            if (timeout == null)
            {
                timeout = TimeSpan.FromSeconds(10);
            }
            try
            {
                IAdapter1?a;
                if (adapter == null)
                {
                    var adapters = await BlueZManager.GetAdaptersAsync();

                    if (adapters.Count == 0)
                    {
                        Log.Error("No Bluetooth adapters found.");
                        throw new BleDeviceError("No Bluetooth adapters found.");
                    }

                    a = adapters.First();
                }
                else
                {
                    a = await BlueZManager.GetAdapterAsync(adapter);
                }

                var adapterPath = a.ObjectPath.ToString();
                var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/", StringComparison.Ordinal) + 1);
                Log.Debug($"Using Bluetooth Adapter {adapterName}.");

                var devices = await a.GetDevicesAsync();

                foreach (var device in devices)
                {
                    var properties = await device.GetAllAsync();

                    var deviceDescription = await GetDeviceDescriptionAsync(device, properties);

                    Log.Debug(deviceDescription);
                    if (await CheckAndConnect(filter, device))
                    {
                        return(device);
                    }
                }

                Log.Debug($"{devices.Count} device(s) found ahead of scan.");

                // Scan for more devices.
                Log.Debug($"Scanning for {timeout.Value.Seconds} seconds...");

                IDevice1?device1     = null;
                var      tokenSource = new CancellationTokenSource();
                using (await a.WatchDevicesAddedAsync(async device =>
                {
                    var deviceProperties = await device.GetAllAsync();
                    var deviceDescription = await GetDeviceDescriptionAsync(device, deviceProperties);
                    Log.Debug($"[NEW] {deviceDescription}");
                    if (!await CheckAndConnect(filter, device))
                    {
                        return;
                    }
                    device1 = device;
                    Log.Debug("Stopping scan...");
                    tokenSource.Cancel();
                }))
                {
                    Log.Debug("Starting scanning...");
                    await a.StartDiscoveryAsync();

                    await Task.Delay(TimeSpan.FromSeconds(timeout.Value.Seconds), tokenSource.Token);

                    await a.StopDiscoveryAsync();

                    Log.Debug("Scan complete.");
                }

                if (device1 != null)
                {
                    return(device1);
                }

                Log.Warning("Device not found.");
            }
            catch (Tmds.DBus.DBusException e)
            {
                Log.Warning($"Error: {e.ErrorMessage}.");
            }

            return(null);
        }
Exemplo n.º 9
0
    static async Task Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: PrintDeviceInfo <deviceAddress> [adapterName]");
            Console.WriteLine("Example: PrintDeviceInfo AA:BB:CC:11:22:33 hci1");
            return;
        }

        var deviceAddress = args[0];

        IAdapter1 adapter;

        if (args.Length > 1)
        {
            adapter = await BlueZManager.GetAdapterAsync(args[1]);
        }
        else
        {
            var adapters = await BlueZManager.GetAdaptersAsync();

            if (adapters.Count == 0)
            {
                throw new Exception("No Bluetooth adapters found.");
            }

            adapter = adapters.First();
        }

        var adapterPath = adapter.ObjectPath.ToString();
        var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

        Console.WriteLine($"Using Bluetooth adapter {adapterName}");

        // Find the Bluetooth peripheral.
        var device = await adapter.GetDeviceAsync(deviceAddress);

        if (device == null)
        {
            Console.WriteLine($"Bluetooth peripheral with address '{deviceAddress}' not found. Use `bluetoothctl` or Bluetooth Manager to scan and possibly pair first.");
            return;
        }

        Console.WriteLine("Connecting...");
        await device.ConnectAsync();

        await device.WaitForPropertyValueAsync("Connected", value : true, timeout);

        Console.WriteLine("Connected.");

        Console.WriteLine("Waiting for services to resolve...");
        await device.WaitForPropertyValueAsync("ServicesResolved", value : true, timeout);

        var servicesUUID = await device.GetUUIDsAsync();

        Console.WriteLine($"Device offers {servicesUUID.Length} service(s).");

        var deviceInfoServiceFound = servicesUUID.Any(uuid => String.Equals(uuid, GattConstants.DeviceInformationServiceUUID, StringComparison.OrdinalIgnoreCase));

        if (!deviceInfoServiceFound)
        {
            Console.WriteLine("Device doesn't have the Device Information Service. Try pairing first?");
            return;
        }

        // Console.WriteLine("Retrieving Device Information service...");
        var service = await device.GetServiceAsync(GattConstants.DeviceInformationServiceUUID);

        var modelNameCharacteristic = await service.GetCharacteristicAsync(GattConstants.ModelNameCharacteristicUUID);

        var manufacturerCharacteristic = await service.GetCharacteristicAsync(GattConstants.ManufacturerNameCharacteristicUUID);

        int characteristicsFound = 0;

        if (modelNameCharacteristic != null)
        {
            characteristicsFound++;
            Console.WriteLine("Reading model name characteristic...");
            var modelNameBytes = await modelNameCharacteristic.ReadValueAsync(timeout);

            Console.WriteLine($"Model name: {Encoding.UTF8.GetString(modelNameBytes)}");
        }

        if (manufacturerCharacteristic != null)
        {
            characteristicsFound++;
            Console.WriteLine("Reading manufacturer characteristic...");
            var manufacturerBytes = await manufacturerCharacteristic.ReadValueAsync(timeout);

            Console.WriteLine($"Manufacturer: {Encoding.UTF8.GetString(manufacturerBytes)}");
        }

        if (characteristicsFound == 0)
        {
            Console.WriteLine("Model name and manufacturer characteristics not found.");
        }

        await device.DisconnectAsync();

        Console.WriteLine("Disconnected.");
    }
Exemplo n.º 10
0
 private async void GetAdapters()
 {
     this.Adapters.AddRange(await BlueZManager.GetAdaptersAsync());
     this.SetMainAdapter();
 }
Exemplo n.º 11
0
        static async Task Main(string[] args)
        {
            if (args.Length < 1 || args.Length > 2 || args[0].ToLowerInvariant() == "-h" || !int.TryParse(args[0], out int scanSeconds))
            {
                Console.WriteLine("Usage: scan <SecondsToScan> [adapterName]");
                Console.WriteLine("Example: scan 15 hci0");
                return;
            }

            IAdapter1 adapter;

            if (args.Length > 1)
            {
                adapter = await BlueZManager.GetAdapterAsync(args[1]);
            }
            else
            {
                var adapters = await BlueZManager.GetAdaptersAsync();

                if (adapters.Count == 0)
                {
                    throw new Exception("No Bluetooth adapters found.");
                }

                adapter = adapters.First();
            }

            var adapterPath = adapter.ObjectPath.ToString();
            var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);

            Console.WriteLine($"Using Bluetooth adapter {adapterName}");

            // Print out the devices we already know about.
            var devices = await adapter.GetDevicesAsync();

            foreach (var device in devices)
            {
                string deviceDescription = await GetDeviceDescriptionAsync(device);

                Console.WriteLine(deviceDescription);
            }
            Console.WriteLine($"{devices.Count} device(s) found ahead of scan.");

            Console.WriteLine();

            // Scan for more devices.
            Console.WriteLine($"Scanning for {scanSeconds} seconds...");

            int newDevices = 0;

            using (await adapter.WatchDevicesAddedAsync(async device => {
                newDevices++;
                // Write a message when we detect new devices during the scan.
                string deviceDescription = await GetDeviceDescriptionAsync(device);
                Console.WriteLine($"[NEW] {deviceDescription}");
            }))
            {
                await adapter.StartDiscoveryAsync();

                await Task.Delay(TimeSpan.FromSeconds(scanSeconds));

                await adapter.StopDiscoveryAsync();
            }
            Console.WriteLine($"Scan complete. {newDevices} new device(s) found.");
        }
Exemplo n.º 12
0
        private async Task <GattCharacteristic> GetPowerStateCharacteristic()
        {
            if (powerStateCharacteristic == null)
            {
                IAdapter1 adapter;
                var       adapters = await BlueZManager.GetAdaptersAsync();

                if (adapters.Count == 0)
                {
                    throw new Exception("No Bluetooth adapters found.");
                }

                adapter = adapters.First();

                var adapterPath = adapter.ObjectPath.ToString();
                var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/") + 1);
                Console.WriteLine($"Using Bluetooth adapter {adapterName}");

                var devices = await adapter.GetDevicesAsync();

                string deviceAddress = "";
                foreach (var d in devices)
                {
                    var name = await d.GetNameAsync();

                    if (name.ToLower().Contains("hue") || name.ToLower().Contains("plug"))
                    {
                        deviceAddress = await d.GetAddressAsync();

                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                if (deviceAddress == "")
                {
                    Console.WriteLine("No matching devices found.");
                    return(null);
                }

                var device = await adapter.GetDeviceAsync(deviceAddress);

                if (device == null)
                {
                    Console.WriteLine($"Bluetooth peripheral with address '{deviceAddress}' not found. Use `bluetoothctl` or Bluetooth Manager to scan and possibly pair first.");
                    return(null);
                }

                Console.WriteLine("Connecting...");
                await device.ConnectAsync();

                await device.WaitForPropertyValueAsync("Connected", value : true, timeout);

                Console.WriteLine("Connected.");

                device.Disconnected += OnDisconnected;

                Console.WriteLine("Waiting for services to resolve...");
                await device.WaitForPropertyValueAsync("ServicesResolved", value : true, timeout);

                var servicesUUID = await device.GetUUIDsAsync();

                Console.WriteLine($"Device offers {servicesUUID.Length} service(s).");

                var deviceInfoServiceFound = servicesUUID.Any(uuid => String.Equals(uuid, GattConstants.DeviceInformationServiceUUID, StringComparison.OrdinalIgnoreCase));
                if (!deviceInfoServiceFound)
                {
                    Console.WriteLine("Device doesn't have the Device Information Service. Try pairing first?");
                    return(null);
                }

                var service = await device.GetServiceAsync("932c32bd-0000-47a2-835a-a8d455b859dd");

                powerStateCharacteristic = await service.GetCharacteristicAsync("932C32BD-0002-47A2-835A-A8D455B859DD");

                return(powerStateCharacteristic);
            }
            else
            {
                return(powerStateCharacteristic);
            }
        }