Esempio n. 1
0
        private async Task <byte[]> WriteAndRead(byte[] dataToWrite, int timeout = 5000)
        {
            try
            {
                var tc = new TaskCompletionSource <CharacteristicGattResult>();
                ResponseCharacteristic.WhenNotificationReceived().Subscribe(result =>
                {
                    tc.TrySetResult(result);
                });

                try
                {
                    await DataCharacteristic.Write(dataToWrite);

                    await tc.Task;
                    var readResult = await DataCharacteristic.Read().Timeout(TimeSpan.FromMilliseconds(timeout));

                    return(readResult.Data);
                }
                catch (TimeoutException)
                {
                    throw new OmniCoreTimeoutException();
                }
            }
            catch (OmniCoreException) { throw; }
            catch (Exception e)
            {
                throw new PacketRadioException("Error while writing to and reading from RL", e);
            }
        }
Esempio n. 2
0
        private async Task <byte[]> WriteAndRead(byte[] dataToWrite, bool noWait = false, int timeout = 5000)
        {
            try
            {
                if (noWait)
                {
                    await DataCharacteristic.WriteWithoutResponse(dataToWrite);
                }
                else
                {
                    var tc = new TaskCompletionSource <CharacteristicGattResult>();
                    ResponseCharacteristic.WhenNotificationReceived().Subscribe(result =>
                    {
                        tc.TrySetResult(result);
                    });
                    await DataCharacteristic.Write(dataToWrite);

                    await tc.Task;
                    var readResult = await DataCharacteristic.Read();

                    return(readResult.Data);
                }
                return(null);
            }
            catch (OmnipyException) { throw; }
            catch (Exception e)
            {
                throw new PacketRadioException("Error while writing to and reading from RL", e);
            }
        }
Esempio n. 3
0
 public static IObservable <CharacteristicResult> ReadInterval(this IGattCharacteristic character, TimeSpan timeSpan)
 => Observable.Create <CharacteristicResult>(ob =>
                                             Observable
                                             .Interval(timeSpan)
                                             .Subscribe(async _ =>
 {
     // BAD
     var read = await character.Read();
     ob.OnNext(read);
 }));
Esempio n. 4
0
 public static IObservable <CharacteristicResult> ReadUntil(this IGattCharacteristic characteristic, byte[] endBytes)
 => Observable.Create <CharacteristicResult>(async ob =>
 {
     var cancelSrc = new CancellationTokenSource();
     try
     {
         var result = await characteristic.Read().RunAsync(cancelSrc.Token);
         while (!result.Data.SequenceEqual(endBytes) && !cancelSrc.IsCancellationRequested)
         {
             ob.OnNext(result);
             result = await characteristic.Read().RunAsync(cancelSrc.Token);
         }
         ob.OnCompleted();
     }
     catch (OperationCanceledException)
     {
         // swallow
     }
     return(() => cancelSrc.Cancel());
 });
        private async Task ReadCharacteristicAsync(IGattCharacteristic ch)
        {
            var charResult = await ch.Read();

            var theData = charResult.Data;

            Device.BeginInvokeOnMainThread(() =>
            {
                characteristicValue.Text = theData[0].ToString();
            });
        }
Esempio n. 6
0
 public static IObservable <byte[]> ReadInterval(this IGattCharacteristic character, TimeSpan timeSpan)
 {
     return(Observable.Create <byte[]>(ob =>
                                       Observable
                                       .Interval(timeSpan)
                                       .Subscribe(async _ =>
     {
         var read = await character.Read();
         ob.OnNext(read);
     })
                                       ));
 }
Esempio n. 7
0
        private async Task CharacteristicsDiscovered(IGattCharacteristic result)
        {
            await result.Read();

            await result.EnableNotifications();

            result.WhenNotificationReceived().Subscribe();

            //Zmiany w interfejsie
            this.RunOnUiThread(() =>
            {
                FindViewById <AppCompatImageButton>(Resource.Id.buttonClear).Click     += buttonClearClicked;
                FindViewById <AppCompatImageButton>(Resource.Id.buttonClear).Visibility = ViewStates.Visible;

                FindViewById <AppCompatImageButton>(Resource.Id.buttonColor).Click     += buttonColorClicked;
                FindViewById <AppCompatImageButton>(Resource.Id.buttonColor).Visibility = ViewStates.Visible;

                FindViewById <AppCompatImageButton>(Resource.Id.buttonText).Click     += buttonAddText;
                FindViewById <AppCompatImageButton>(Resource.Id.buttonText).Visibility = ViewStates.Visible;

                FindViewById <Android.Widget.LinearLayout>(Resource.Id.linearLayout1).AddView(drawView);

                FindViewById <TextInputEditText>(Resource.Id.textInputEditText1).Visibility = ViewStates.Visible;

                FindViewById <FloatingActionButton>(Resource.Id.fab).Click     += FabOnClick;
                FindViewById <FloatingActionButton>(Resource.Id.fab).Visibility = ViewStates.Visible;
            });


            gattCharacteristic = result;
            drawExist          = true;


            Snackbar.Make(FindViewById <Android.Widget.LinearLayout>(Resource.Id.linearLayout), "Połączono", Snackbar.LengthShort)
            .SetAction("Action", (View.IOnClickListener)null).Show();
            this.RGB = drawView.GetColor();
            sendColorToArduino();
        }
Esempio n. 8
0
 public static Task <GattCharacteristicResult> ReadAsync(this IGattCharacteristic characteristic, CancellationToken?cancelToken = null)
 => characteristic.Read().ToTask(cancelToken ?? CancellationToken.None);
Esempio n. 9
0
        public async Task Connect()
        {
            try
            {
                if (this.Device == null)
                {
                    this.VersionVerified  = false;
                    this.RadioInitialized = false;

                    Debug.WriteLine("Searching RL");
                    var result = await CrossBleAdapter.Current.Scan(
                        new ScanConfig()
                    {
                        ScanType = BleScanType.Balanced, ServiceUuids = new List <Guid>()
                        {
                            RileyLinkServiceUUID
                        }
                    })
                                 .FirstOrDefaultAsync();

                    if (CrossBleAdapter.Current.IsScanning)
                    {
                        CrossBleAdapter.Current.StopScan();
                    }

                    this.Device = result?.Device;

                    if (this.Device == null)
                    {
                        throw new PacketRadioException("Couldn't find RileyLink!");
                    }
                    else
                    {
                        Debug.WriteLine("Found RL");
                    }
                }

                if (!this.Device.IsConnected())
                {
                    Debug.WriteLine("Connecting to RL");
                    this.Device.Connect(new ConnectionConfig()
                    {
                        AndroidConnectionPriority = ConnectionPriority.Normal,
                        AutoConnect = false
                    });
                    await this.Device.ConnectWait();

                    if (!this.Device.IsConnected())
                    {
                        throw new PacketRadioException("Failed to connect to RL.");
                    }
                    else
                    {
                        Debug.WriteLine("Connected to RL.");

                        var dataService     = this.Device.GetKnownService(RileyLinkServiceUUID);
                        var characteristics = this.Device.GetKnownCharacteristics(RileyLinkServiceUUID,
                                                                                  new Guid[] { RileyLinkDataCharacteristicUUID, RileyLinkResponseCharacteristicUUID });

                        this.DataCharacteristic = await characteristics.FirstOrDefaultAsync(x => x.Uuid == RileyLinkDataCharacteristicUUID);

                        this.ResponseCharacteristic = await characteristics.FirstOrDefaultAsync(x => x.Uuid == RileyLinkResponseCharacteristicUUID);

                        await DataCharacteristic.Write(new byte[] { 0 });

                        await this.ResponseCharacteristic.EnableNotifications();

                        while (true)
                        {
                            try
                            {
                                await ResponseCharacteristic.WhenNotificationReceived().Timeout(TimeSpan.FromMilliseconds(200));

                                await DataCharacteristic.Read().Timeout(TimeSpan.FromMilliseconds(200));

                                await ResponseCharacteristic.Read().Timeout(TimeSpan.FromMilliseconds(200));
                            }
                            catch (TimeoutException)
                            {
                                break;
                            }
                        }
                        await Task.Delay(500);
                    }
                }

                if (!this.VersionVerified)
                {
                    await this.VerifyVersion();
                }

                if (!this.RadioInitialized)
                {
                    await this.InitializeRadio();
                }
            }
            catch (OmniCoreException) { throw; }
            catch (Exception e)
            {
                throw new PacketRadioException("Error while connecting to BLE device", e);
            }
        }
Esempio n. 10
0
 public static IObservable <CharacteristicGattResult> ReadInterval(this IGattCharacteristic character, TimeSpan timeSpan)
 => Observable
 .Interval(timeSpan)
 .Select(_ => character.Read())
 .Switch();
 public async Task <byte[]> Read(CancellationToken cancellationToken)
 {
     return((await Characteristic.Read().ToTask(cancellationToken)).Data);
 }
Esempio n. 12
0
        private void RegisterCharacteristicObservers(IGattCharacteristic characteristic)
        {
            /*
             * Read Once Characteristics
             */
            if (characteristic.Uuid == GattConstants.SYSTEM_ID_UUID)
            {
                characteristic.Read().Subscribe(result => { Id = _hexStringConversion.Convert(result.Data); });
            }
            else if (characteristic.Uuid == GattConstants.MANUFACTURER_NAME_UUID)
            {
                characteristic.Read().Subscribe(result => { ManufacturerName = _stringConversion.Convert(result.Data); });
            }
            else if (characteristic.Uuid == GattConstants.MODEL_NUMBER_UUID)
            {
                characteristic.Read().Subscribe(result => { ModelNumber = _stringConversion.Convert(result.Data); });
            }
            else if (characteristic.Uuid == GattConstants.HARDWARE_REVISION_UUID)
            {
                characteristic.Read().Subscribe(result => { HardwareRevision = _stringConversion.Convert(result.Data); });
            }
            else if (characteristic.Uuid == GattConstants.FIRMWARE_REVISION_UUID)
            {
                characteristic.Read().Subscribe(result => { FirmwareRevision = _stringConversion.Convert(result.Data).Replace('-', '.'); });
            }
            else if (characteristic.Uuid == GattConstants.SOFTWARE_REVISION_UUID)
            {
                characteristic.Read().Subscribe(result => { SoftwareRevision = _stringConversion.Convert(result.Data).Replace('-', '.'); });
            }
            else if (characteristic.Uuid == GattConstants.BATTERY_LEVEL_UUID)
            {
                characteristic.Read().Subscribe(result => BatteryLevel = _byteConversion.Convert(result.Data));
            }

            /*
             * Notify Characteristics
             */
            if (characteristic.Uuid == GattConstants.BATTERY_LEVEL_UUID)
            {
                characteristic.RegisterAndNotify().Subscribe(result => BatteryLevel = _byteConversion.Convert(result.Data));
            }
            else if (characteristic.Uuid == GattConstants.HEART_RATE_UUID)
            {
                characteristic.RegisterAndNotify().Subscribe(result => HeartRate = _heartRateConversion.Convert(result.Data));
            }
            else if (characteristic.Uuid == GattConstants.SPO2_UUID)
            {
                characteristic.RegisterAndNotify().Subscribe(result => { });
            }
            else if (characteristic.Uuid == GattConstants.TEMPERATURE_MEASUREMENT_UUID)
            {
                characteristic.RegisterAndNotify(true).Subscribe(result => BodyTemperature = _temperatureConversion.Convert(result.Data));
            }
            else if (characteristic.Uuid == GattConstants.SENSOR_QUALITY_INDEX_UUID)
            {
                characteristic.RegisterAndNotify().Subscribe(result => SensorQualityIndex = _byteConversion.Convert(result.Data));
            }

            /*
             * Write Raw Data Characteristic and Start Notify
             */
            if (characteristic.Uuid == GattConstants.RAW_DATA_UUID)
            {
                var rawDataCharacteristic = characteristic;
                characteristic.Write(RAW_DATA_KEY).Subscribe(result =>
                {
                    rawDataCharacteristic.RegisterAndNotify().Subscribe(notifyResult =>
                    {
                        var convertedRawData = _rawConversion.Convert(notifyResult.Data);

                        if (convertedRawData.StepFrequency != null)
                        {
                            this.StepFrequency = convertedRawData.StepFrequency ?? this.StepFrequency;
                        }
                        if (convertedRawData.Accelerometer != null)
                        {
                            this.Accelerometer = convertedRawData.Accelerometer;
                        }
                    });
                });
            }
        }
Esempio n. 13
0
        private void ConnectToServer()
        {
            server.Connect();
            Server_Name.Text = "Currently connected to " + server.Name;

            server.WhenAnyCharacteristicDiscovered().Subscribe(characteristic =>
            {
                //Debug.WriteLine("Char" + characteristic.Uuid);
            });

            //set up identity management
            server.GetKnownCharacteristics(StaticGuids.buzzerServiceGuid, StaticGuids.identityCharGuid).Subscribe(identityChar =>
            {
                Debug.WriteLine("Found Identity char");
                this.identityChar = identityChar;

                //writing nickname allows server to create association b/w uuid and nickname
                identityChar.Write(Encoding.UTF8.GetBytes(nickname)).Subscribe(write =>
                {
                    Debug.WriteLine("Successful identity write");
                }, error =>
                {
                    Debug.WriteLine(error.GetBaseException());
                });

                identityChar.Read().Subscribe(read =>
                {
                    addOne(LoadLabel);
                    clientGuid = Guid.Parse(Encoding.UTF8.GetString(read.Data));
                    Debug.WriteLine("Found own GUID: " + clientGuid.ToString());
                }, error =>
                {
                    Debug.WriteLine(error.ToString());
                });
            });

            //set up lock status
            server.GetKnownCharacteristics(StaticGuids.buzzerServiceGuid, StaticGuids.lockStatusGuid).Subscribe(lockStatusChar =>
            {
                Debug.WriteLine("Found Lock char");
                lockStatusChar.EnableNotifications();
                lockStatusChar.WhenNotificationReceived().Subscribe(result =>
                {
                    Debug.WriteLine("Notification recieved" + Encoding.UTF8.GetString(result.Data));
                    string reply       = Encoding.UTF8.GetString(result.Data);
                    char tempLockState = reply[0];
                    Debug.WriteLine(reply.Substring(1, 36));
                    Guid buzzDevice = Guid.Parse(reply.Substring(1, 36));

                    //TODO fix risk that client guid is not yet found
                    if (buzzDevice == clientGuid)
                    {
                        tempLockState = 'U';
                    }

                    lockStatus = tempLockState;
                    addOne(LoadLabel);
                });
            });

            //set up buzz char
            server.GetKnownCharacteristics(StaticGuids.buzzerServiceGuid, StaticGuids.buzzCharGuid).Subscribe(buzzerChar =>
            {
                Debug.WriteLine("Found buzzer char");
                this.buzzerChar = buzzerChar;
                addOne(LoadLabel);
            });

            //set up team info
            server.GetKnownCharacteristics(StaticGuids.buzzerServiceGuid, StaticGuids.teamCharGuid).Subscribe(teamChar =>
            {
                Debug.WriteLine("Team char found");
                teamChar.EnableNotifications();
                teamChar.WhenNotificationReceived().Subscribe(result =>
                {
                    Debug.WriteLine("Team info recieved");
                    string teamInfoString = Encoding.UTF8.GetString(result.Data);
                    string[] teamInfo     = teamInfoString.Split(teamSplitter, 2, StringSplitOptions.None);
                    foreach (string teamString in teamInfo)
                    {
                        string[] names = teamString.Split(nameSplitter, 50, StringSplitOptions.None);

                        if (!teams.ContainsKey(names[0]))
                        {
                            teams[names[0]] = new List <Guid>();
                        }
                        List <Guid> teamMembers = teams[names[0]];
                        for (int i = 1; i < names.Length; i++)
                        {
                            teamMembers.Add(Guid.Parse(names[i]));
                        }
                    }
                    addOne(LoadLabel);
                });
            });
        }
Esempio n. 14
0
 public static Task <GattCharacteristicResult> ReadAsync(this IGattCharacteristic characteristic, CancellationToken cancelToken = default)
 => characteristic.Read().ToTask(cancelToken);
 public override IObservable <CharacteristicGattResult> Read()
 {
     return(chs.Read());
 }