Exemplo n.º 1
0
        // TODO: Make this available to other generated interfaces too, not just IDevice1.
        // `dynamic obj` works, but it requires a Microsoft.* NuGet package and isn't type safe.
        public static async Task WaitForPropertyValueAsync <T>(this IDevice1 obj, string propertyName, T value,
                                                               TimeSpan timeout)
        {
            var(watchTask, watcher) = WaitForPropertyValueInternal <T>(obj, propertyName, value);
            var currentValue = await obj.GetAsync <T>(propertyName);

            // Console.WriteLine($"{propertyName}: {currentValue}");

            // https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c
            if (EqualityComparer <T> .Default.Equals(currentValue, value))
            {
                watcher.Dispose();
                return;
            }

            await Task.WhenAny(new Task[] { watchTask, Task.Delay(timeout) });

            if (!watchTask.IsCompleted)
            {
                throw new TimeoutException($"Timed out waiting for '{propertyName}' to change to '{value}'.");
            }

            // propogate any exceptions.
            await watchTask;
        }
Exemplo n.º 2
0
        private static async Task <string> GetDeviceDescriptionAsync(IDevice1 device,
                                                                     Device1Properties?deviceProperties = null)
        {
            if (deviceProperties == null)
            {
                deviceProperties = await device.GetAllAsync();
            }

            return($"{deviceProperties.Alias} (Address: {deviceProperties.Address}, RSSI: {deviceProperties.RSSI})");
        }
Exemplo n.º 3
0
        internal static async Task <Device> CreateAsync(IDevice1 proxy)
        {
            var device = new Device
            {
                m_proxy = proxy,
            };

            device.m_propertyWatcher = await proxy.WatchPropertiesAsync(device.OnPropertyChanges);

            return(device);
        }
Exemplo n.º 4
0
        private static async Task <bool> ShouldConnect(ScanFilter filter, IDevice1 device)
        {
            var deviceProperties = await device.GetAllAsync();

            if (!await filter.Check(device))
            {
                return(false);
            }
            Log.Debug($"Device found at {deviceProperties.Address}.");
            return(true);
        }
Exemplo n.º 5
0
        private static async Task <bool> CheckAndConnect(ScanFilter filter, IDevice1 device)
        {
            if (!await ShouldConnect(filter, device))
            {
                return(false);
            }
            await device.ConnectAsync();

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

            return(true);
        }
Exemplo n.º 6
0
        private async Task <string> GetDeviceDescriptionAsync(IDevice1 device)
        {
            var deviceProperties = await device.GetAllAsync();

            // используем Device UUID вместо GATTId в качестве идентификатора маячка, т.к. нет времени заморачиваться
            await _writer.SendInternal(new CTrack()
            {
                Timestamp = DateTimeOffset.Now, GATTid = deviceProperties.UUIDs[0], RSSI = deviceProperties.RSSI
            });

            return($"{deviceProperties.Alias} (Address: {deviceProperties.Address}, RSSI: {deviceProperties.RSSI}), DeviceUUID: {deviceProperties.UUIDs[0]}");
        }
Exemplo n.º 7
0
        public async Task <bool> Check(IDevice1 device)
        {
            var deviceProperties = await device.GetAllAsync();

            if (_address == null)
            {
                return(deviceProperties?.Alias?.Contains(_name ?? "") ?? false);
            }
            else
            {
                return(deviceProperties.Address == _address);
            }
        }
Exemplo n.º 8
0
        internal MoveHub(IDevice1 device) : base(device)
        {
            // This is a Boost MoveHub
            HubType = LPF2HubType.MOVE_HUB;

            PortIdMap[0]  = "A";
            PortIdMap[1]  = "B";
            PortIdMap[2]  = "C";
            PortIdMap[3]  = "D";
            PortIdMap[50] = "HUB_LED";
            PortIdMap[58] = "TILT_SENSOR";
            PortIdMap[59] = "CURRENT_SENSOR";
            PortIdMap[60] = "VOLTAGE_SENSOR";
        }
Exemplo n.º 9
0
        public static async Task <IGattService1> GetServiceAsync(this IDevice1 device, string serviceUUID)
        {
            var services = await GetProxiesAsync <IGattService1>(device, BluezConstants.GattServiceInterface);

            foreach (var service in services)
            {
                if (String.Equals(await service.GetUUIDAsync(), serviceUUID, StringComparison.OrdinalIgnoreCase))
                {
                    return(service);
                }
            }

            return(null);
        }
Exemplo n.º 10
0
        private static async Task PrintDeviceInformation(IDevice1 device)
        {
            var service = await device.GetServiceAsync(GattConstants.DeviceInformationServiceUUID);

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

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

            Console.WriteLine("Reading Device Info characteristic values...");
            var modelNameBytes = await modelNameCharacteristic.ReadValueAsync(timeout);

            var manufacturerBytes = await manufacturerCharacteristic.ReadValueAsync(timeout);

            Console.WriteLine($"Model name: {Encoding.UTF8.GetString(modelNameBytes)}");
            Console.WriteLine($"Manufacturer: {Encoding.UTF8.GetString(manufacturerBytes)}");
        }
Exemplo n.º 11
0
        private static async Task <LPF2Hub?> CreateHubInstance(IDevice1 dev)
        {
            var data = await dev.GetManufacturerDataAsync();

            if (!data.ContainsKey(0x0397))
            {
                // Not a LEGO product
                return(null);
            }

            var     typeId = ((byte[])data[0x0397])[1];
            LPF2Hub?ret    = null;

            switch (typeId)
            {
            case 32:     // Duplo Train Base
                // TODO:
                break;

            case 64:     // LEGO Boost MoveHub
                ret = new MoveHub(dev);
                break;

            case 65:     // Powered Up Hub
                // TODO:
                break;

            case 66:     // Remote Controller
                // TODO:
                break;

            case 128:     // Technic Medium Hub
                ret = new TechnicMediumHub(dev);
                break;
            }

            if (ret == null)
            {
                // Unknown LEGO Hub
                return(null);
            }

            await ret.Initialize();

            return(ret);
        }
Exemplo n.º 12
0
        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);
        }
Exemplo n.º 13
0
 internal BluetoothDevice(IDevice1 device, Device1Properties properties)
 {
     _device1         = device;
     Address          = properties.Address;
     Name             = properties.Name;
     Alias            = properties.Alias;
     Paired           = properties.Paired;
     Trusted          = properties.Trusted;
     Blocked          = properties.Blocked;
     LegacyPairing    = properties.LegacyPairing;
     RSSI             = properties.RSSI;
     Connected        = properties.Connected;
     UUIDs            = properties.UUIDs;
     ManufacturerData = properties.ManufacturerData;
     ServiceData      = properties.ServiceData;
     TxPower          = properties.TxPower;
     ServicesResolved = properties.ServicesResolved;
 }
Exemplo n.º 14
0
        internal TechnicMediumHub(IDevice1 device) : base(device)
        {
            // This is a Technic Medium Hub
            HubType = LPF2HubType.TECHNIC_MEDIUM_HUB;

            PortIdMap[0]  = "A";
            PortIdMap[1]  = "B";
            PortIdMap[2]  = "C";
            PortIdMap[3]  = "D";
            PortIdMap[50] = "HUB_LED";
            PortIdMap[59] = "CURRENT_SENSOR";
            PortIdMap[60] = "VOLTAGE_SENSOR";
            // What are these?
            // PortIdMap[61] = "TEMPERATURE_SENSOR";
            // PortIdMap[96] = "TEMPERATURE_SENSOR";
            PortIdMap[97] = "ACCELEROMETER";
            PortIdMap[98] = "GYRO_SENSOR";
            PortIdMap[99] = "TILT_SENSOR";
        }
Exemplo n.º 15
0
#pragma warning disable CS8618
        protected BleDevice(IDevice1 device)
        {
            _device = device;
        }
Exemplo n.º 16
0
 public static Task <short> GetTxPowerAsync(this IDevice1 o) => o.GetAsync <short>(nameof(Device1Properties.TxPower));
Exemplo n.º 17
0
 public static Task <bool> GetServicesResolvedAsync(this IDevice1 o) => o.GetAsync <bool>(nameof(Device1Properties.ServicesResolved));
Exemplo n.º 18
0
 public static Task SetAliasAsync(this IDevice1 o, string val) => o.SetAsync(nameof(Device1Properties.Alias), val);
Exemplo n.º 19
0
 public static Task SetBlockedAsync(this IDevice1 o, bool val) => o.SetAsync(nameof(Device1Properties.Blocked), val);
Exemplo n.º 20
0
 private Microbit(IDevice1 device) : base(device)
 {
 }
Exemplo n.º 21
0
 internal DotNetBlueZDevice(IDevice1 device)
 {
     _device = device;
 }
Exemplo n.º 22
0
 public static Task <IReadOnlyList <IGattService1> > GetServicesAsync(this IDevice1 device)
 {
     return(BlueZManager.GetProxiesAsync <IGattService1>(BluezConstants.GattServiceInterface, device));
 }
 public static IDevice1 CreateRef(this IDevice1 objectRef) =>
 ((IDevice1)objectRef.CreateRef(typeof(IDevice1)));
Exemplo n.º 24
0
 public static Task <IAdapter1> GetAdapterAsync(this IDevice1 o) => o.GetAsync <IAdapter1>(nameof(Device1Properties.Adapter));
Exemplo n.º 25
0
 protected LPF2Hub(IDevice1 device) : base(device)
 {
 }
Exemplo n.º 26
0
 public static Task <IDictionary <string, object> > GetServiceDataAsync(this IDevice1 o) =>
 o.GetAsync <IDictionary <string, object> >(nameof(Device1Properties.ServiceData));
Exemplo n.º 27
0
 public static Task <IDictionary <ushort, object> > GetManufacturerDataAsync(this IDevice1 o) =>
 o.GetAsync <IDictionary <ushort, object> >(nameof(Device1Properties.ManufacturerData));
Exemplo n.º 28
0
        static async Task OnDeviceFoundAsync(IDevice1 device)
        {
            string deviceDescription = await GetDeviceDescriptionAsync(device);

            while (true)
            {
                Console.WriteLine($"Connect to {deviceDescription}? yes/[no]?");
                string response = Console.ReadLine();
                if (response.Length == 0 || response.ToLowerInvariant().StartsWith("n"))
                {
                    return;
                }

                if (response.ToLowerInvariant().StartsWith("y"))
                {
                    break;
                }
            }

            try
            {
                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 servicesUUIDs = await device.GetUUIDsAsync();

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

                var deviceInfoServiceFound = servicesUUIDs.Any(uuid => uuid == GattConstants.DeviceInformationServiceUUID);
                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);

                Console.WriteLine("Reading Device Info characteristic values...");
                var modelNameBytes = await modelNameCharacteristic.ReadValueAsync(timeout);

                var manufacturerBytes = await manufacturerCharacteristic.ReadValueAsync(timeout);

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

                // Test walking back up to the adapter...
                var adapterName = await(await(await(await modelNameCharacteristic.GetServiceAsync()).GetDeviceAsync()).GetAdapterAsync()).GetAliasAsync();

                Console.WriteLine($"Adapter name: {adapterName}");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
            finally
            {
                Console.WriteLine();
            }
        }
Exemplo n.º 29
0
        private static async Task <string> GetDeviceDescriptionAsync(IDevice1 device)
        {
            var deviceProperties = await device.GetAllAsync();

            return($"{deviceProperties.Address} (Alias: {deviceProperties.Alias}, RSSI: {deviceProperties.RSSI})");
        }
Exemplo n.º 30
0
 Device(ObjectPath path)
 {
     proxy      = Connection.System.CreateProxy <IDevice1>("org.bluez", path);
     properties = new Dictionary <string, object>();
 }