Ejemplo n.º 1
0
        internal BleDevice(BGLib bgLib, BleModuleConnection bleModuleConnection, ILogger logger, byte connectionHandle, byte[] address, BleAddressType addressType, List <BleService> services)
        {
            _bgLib = bgLib;
            _bleModuleConnection = bleModuleConnection;
            _logger           = logger;
            _connectionHandle = connectionHandle;

            Address     = address;
            AddressType = addressType;
            Services    = services;

            services.ForEach(service =>
            {
                service.Characteristics.ForEach(characteristic =>
                {
                    CharacteristicsByUuid.Add(characteristic.Uuid, characteristic);
                });
            });

            services.ForEach(service =>
            {
                service.Characteristics.ForEach(characteristic =>
                {
                    CharacteristicsByHandle.Add(characteristic.Handle, characteristic);
                });
            });

            _bgLib.BLEEventATTClientAttributeValue += OnClientAttributeValue;
            _bgLib.BLEEventConnectionDisconnected  += OnDisconnected;

            IsConnected = true;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Connect to a device
        /// </summary>
        /// <param name="address">Device address</param>
        /// <param name="addressType">Device address type</param>
        /// <returns></returns>
        public async Task <BleDevice> ConnectAsync(byte[] address, BleAddressType addressType)
        {
            var connectCommand   = new BleConnectCommand(_bgLib, _bleModuleConnection, _logger);
            var connectionStatus = await connectCommand.ExecuteAsync(address, addressType);

            var findServicesCommand        = new BleFindServicesCommand(_bgLib, _bleModuleConnection, _logger);
            var findCharacteristicsCommand = new BleFindCharacteristicsCommand(_bgLib, _bleModuleConnection, _logger);
            var services = await findServicesCommand.ExecuteAsync(connectionStatus.connection);

            foreach (var service in services)
            {
                _logger?.LogDebug($"Service found Uuid={service.Uuid}");

                var(characteristics, attributes) = await findCharacteristicsCommand.ExecuteAsync(connectionStatus.connection, service.StartHandle, service.EndHandle);

                service.Characteristics.AddRange(characteristics);
                service.Attributes.AddRange(attributes);

                foreach (var characteristic in service.Characteristics)
                {
                    _logger?.LogDebug($"Characteristic found, Uuid={characteristic.Uuid}, Handle={characteristic.Handle}, HasCcc={characteristic.HasCcc}");
                }
            }

            var bleDevice = new BleDevice(_bgLib, _bleModuleConnection, _logger, connectionStatus.connection, address, addressType, services);

            return(bleDevice);
        }
Ejemplo n.º 3
0
 public BleScanResponseReceivedEventArgs(sbyte rssi, byte packetType, byte[] address, BleAddressType addressType, byte bond, byte[] data)
 {
     Rssi        = rssi;
     PacketType  = packetType;
     Address     = address;
     AddressType = addressType;
     Bond        = bond;
     Data        = data;
     ParsedData  = BleAdvertisingDataParser.Parse(data);
 }
Ejemplo n.º 4
0
        private async Task RunAsync()
        {
            _bleModuleConnection.Start("COM3");

            byte[]         deviceAddress     = null;
            BleAddressType deviceAddressType = BleAddressType.Public;

            _bleDeviceDiscovery.ScanResponse += (sender, args) =>
            {
                // Filter advertisement data by the complete local name
                if (args.ParsedData.Any(x => x.Type == BleAdvertisingDataType.CompleteLocalName && x.ToAsciiString() == "DEVICE-NAME"))
                {
                    _logger.LogInformation("Device found");

                    deviceAddress     = args.Address;
                    deviceAddressType = args.AddressType;

                    _bleDeviceDiscovery.StopDeviceDiscovery();

                    _discoveryTimeout.Set();
                }
            };

            _bleDeviceDiscovery.StartDeviceDiscovery();

            try
            {
                _discoveryTimeout.WaitOne(10000);

                // Connecting to a device will log the discovered services and characteristics
                var device = await _bleDeviceManager.ConnectAsync(deviceAddress, deviceAddressType);
            }
            catch
            {
                _bleDeviceDiscovery.StopDeviceDiscovery();

                _logger.LogError("Device coulnd not be found");
            }

            _bleModuleConnection.Stop();
        }
Ejemplo n.º 5
0
        public async Task <StatusEventArgs> ExecuteAsync(byte[] address, BleAddressType addressType, CancellationToken cancellationToken, int timeout = DefaultTimeout)
        {
            Logger?.LogDebug($"Connect to device, Address={address.ToHexString()}, AddressType={addressType}");

            var taskCompletionSource = new TaskCompletionSource <StatusEventArgs>();

            using (var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                cancellationTokenSource.CancelAfter(timeout);

                void OnConnectionStatus(object sender, StatusEventArgs e)
                {
                    if ((e.flags & 0x05) == 0x05)
                    {
                        taskCompletionSource.SetResult(e);
                    }
                    else
                    {
                        taskCompletionSource.SetException(new Exception("Couldn't connect to device"));
                    }
                }

                try
                {
                    BgLib.BLEEventConnectionStatus += OnConnectionStatus;

                    using (cancellationTokenSource.Token.Register(() => taskCompletionSource.SetCanceled(), false))
                    {
                        BgLib.SendCommand(BleModuleConnection.SerialPort, BgLib.BLECommandGAPConnectDirect((byte[])address, (byte)addressType, 0x20, 0x30, 0x100, 0));

                        return(await taskCompletionSource.Task.ConfigureAwait(false));
                    }
                }
                finally
                {
                    BgLib.BLEEventConnectionStatus -= OnConnectionStatus;
                }
            }
        }
Ejemplo n.º 6
0
 public async Task <StatusEventArgs> ExecuteAsync(byte[] address, BleAddressType addressType, int timeout = DefaultTimeout)
 {
     return(await ExecuteAsync(address, addressType, CancellationToken.None, timeout));
 }