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); }
public static async Task <Device> GetDeviceAsync(this IAdapter1 adapter, string deviceAddress) { var devices = await BlueZManager.GetProxiesAsync <IDevice1>(BluezConstants.DeviceInterface, adapter); var matches = new List <IDevice1>(); foreach (var device in devices) { if (String.Equals(await device.GetAddressAsync(), deviceAddress, StringComparison.OrdinalIgnoreCase)) { matches.Add(device); } } // BlueZ can get in a weird state, probably due to random public BLE addresses. if (matches.Count > 1) { throw new Exception($"{matches.Count} devices found with the address {deviceAddress}!"); } var dev = matches.FirstOrDefault(); if (dev != null) { return(await Device.CreateAsync(dev)); } return(null); }
public async void LoadFirstAdapter() { try { adapter = (await BlueZManager.GetAdaptersAsync()).FirstOrDefault(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
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); }
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"); }
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(); } }
public static async Task <IGattService1> GetServiceAsync(this IDevice1 device, string serviceUUID) { var services = await BlueZManager.GetProxiesAsync <IGattService1>(BluezConstants.GattServiceInterface, device); foreach (var service in services) { var uuid = await service.GetUUIDAsync(); // Console.WriteLine($"Checking {uuid}"); if (String.Equals(uuid, serviceUUID, StringComparison.OrdinalIgnoreCase)) { return(service); } } return(null); }
public static Task <IDisposable> WatchDevicesAddedAsync(this IAdapter1 adapter, Action <Device> handler) { async void OnDeviceAdded((ObjectPath objectPath, IDictionary <string, IDictionary <string, object> > interfaces) args) { if (BlueZManager.IsMatch(BluezConstants.DeviceInterface, args.objectPath, args.interfaces, adapter)) { var device = Connection.System.CreateProxy <IDevice1>(BluezConstants.DbusService, args.objectPath); var dev = await Device.CreateAsync(device); handler(dev); } } var objectManager = Connection.System.CreateProxy <IObjectManager>(BluezConstants.DbusService, "/"); return(objectManager.WatchInterfacesAddedAsync(OnDeviceAdded)); }
public static async Task <List <string> > GetAllCharacteristicAsync(this IGattService1 service) { var result = new List <string>(); var characteristics = await BlueZManager.GetProxiesAsync <IGattCharacteristic1>(BluezConstants.GattCharacteristicInterface, service); Debug.WriteLine($"{characteristics.Count} characteristics found"); foreach (var characteristic in characteristics) { var uuid = await characteristic.GetUUIDAsync(); //var ch = await GattCharacteristic.CreateAsync(characteristic); result.Add(uuid); } return(result); }
public static async Task <GattCharacteristic> GetCharacteristicAsync(this IGattService1 service, string characteristicUUID) { var characteristics = await BlueZManager.GetProxiesAsync <IGattCharacteristic1>(BluezConstants.GattCharacteristicInterface, service); foreach (var characteristic in characteristics) { var uuid = await characteristic.GetUUIDAsync(); // Console.WriteLine($"Checking {uuid}"); if (String.Equals(uuid, characteristicUUID, StringComparison.OrdinalIgnoreCase)) { var ch = await GattCharacteristic.CreateAsync(characteristic); return(ch); } } return(null); }
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); }
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); }
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: DotNetBlueZTest1 <SecondsToScan> [adapterName]"); Console.WriteLine("Example: DotNetBlueZTest1 15 hci0"); return; } var adapterName = args.Length > 1 ? args[1] : DefaultAdapterName; var adapter = await BlueZManager.GetAdapterAsync(adapterName); // Scan briefly for devices. Console.WriteLine($"Scanning for {scanSeconds} seconds..."); using (await adapter.WatchDevicesAddedAsync(async device => { // 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(); } var devices = await adapter.GetDevicesAsync(); Console.WriteLine($"{devices.Count} device(s) found."); foreach (var device in devices) { await OnDeviceFoundAsync(device); } }
public static async Task <IReadOnlyList <Device> > GetDevicesAsync(this IAdapter1 adapter) { var devices = await BlueZManager.GetProxiesAsync <IDevice1>(BluezConstants.DeviceInterface, adapter); return(await Task.WhenAll(devices.Select(Device.CreateAsync))); }
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); }
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."); }
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."); }
private async void GetAdapters() { this.Adapters.AddRange(await BlueZManager.GetAdaptersAsync()); this.SetMainAdapter(); }
public static Task <IReadOnlyList <IGattCharacteristic1> > GetCharacteristicsAsync(this IGattService1 service) { return(BlueZManager.GetProxiesAsync <IGattCharacteristic1>(BluezConstants.GattCharacteristicInterface, service)); }
public static Task <IReadOnlyList <IGattService1> > GetServicesAsync(this IDevice1 device) { return(BlueZManager.GetProxiesAsync <IGattService1>(BluezConstants.GattServiceInterface, device)); }
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); } }