public BleGattServiceViewModel(Guid service, IBleGattServerConnection gattServer, IUserDialogs dialogManager)
 {
     m_serviceGuid   = service;
     Characteristic  = new ObservableCollection <BleGattCharacteristicViewModel>();
     m_gattServer    = gattServer;
     m_dialogManager = dialogManager;
 }
Exemplo n.º 2
0
        private static void ToastDeviceDisconnected()
        {
            gattServer = null;
            var toastConfig = new ToastConfig("Connection lost. Please Reconnect.");

            toastConfig.SetDuration(3000);
            UserDialogs.Instance.Toast(toastConfig);
        }
Exemplo n.º 3
0
        private async Task <byte[]> SendCommand(IBleGattServerConnection connection, RileyLinkCommandType cmd, byte[] cmdData = null, int timeout = 2000)
        {
            ResetTimer();
            byte[] data;
            if (cmdData == null)
            {
                data = new byte[] { 1, (byte)cmd };
            }
            else
            {
                data    = new byte[cmdData.Length + 2];
                data[0] = (byte)(cmdData.Length + 1);
                data[1] = (byte)cmd;
                Buffer.BlockCopy(cmdData, 0, data, 2, cmdData.Length);
            }

            NotificationQueued.Reset();
            Console.WriteLine("writing data");
            await connection.WriteCharacteristicValue(RileyLinkServiceUUID, RileyLinkDataCharacteristicUUID, data);

            if (!NotificationQueued.Wait(timeout))
            {
                throw new Exception("timed out expecting a response from rileylink");
            }

            NotificationQueued.Reset();
            byte[] result = null;
            if (ResponseQueue.Count > 0)
            {
                result = ResponseQueue.Dequeue();
            }
            if (result == null || result.Length == 0)
            {
                throw new Exception("RL returned no result");
            }
            else if (result[0] == (byte)RileyLinkResponseType.OK)
            {
                if (result.Length > 1)
                {
                    var response = new byte[result.Length - 1];
                    Buffer.BlockCopy(result, 1, response, 0, response.Length);
                    return(response);
                }
                else
                {
                    return(null);
                }
            }
            else if (result[0] == (byte)RileyLinkResponseType.Interrupted)
            {
                return(await SendCommand(connection, cmd, cmdData, timeout));
            }
            else
            {
                throw new Exception($"RL returned error code {result[0]}");
            }
        }
Exemplo n.º 4
0
        public BleGattServiceViewModel(Guid service, IBleGattServerConnection gattServer, IUserDialogs dialogManager)
        {
            Debug.WriteLine("Services:" + service != null?service.ToString():"null" + " m_gattServer:" + (m_gattServer != null?m_gattServer.ToString():"null"));

            m_serviceGuid   = service;
            Characteristic  = new ObservableCollection <BleGattCharacteristicViewModel>();
            m_gattServer    = gattServer;
            m_dialogManager = dialogManager;
        }
 public void CloseConnection()
 {
     if (m_gattServer != null)
     {
         Log.Trace("Closing connection to GATT Server. state={0:g}", m_gattServer?.State);
         m_gattServer.Dispose();
         m_gattServer = null;
     }
     Services.Clear();
     IsBusy = false;
 }
        private async Task CloseConnection()
        {
            IsBusy = true;
            if (m_gattServer != null)
            {
                Log.Trace("Closing connection to GATT Server. state={0:g}", m_gattServer?.State);
                await m_gattServer.Disconnect();

                m_gattServer = null;
            }

            Services.Clear();
            IsBusy = false;
        }
        /// <summary>
        /// Listen for NOTIFY events on this characteristic.
        /// </summary>
        public static IDisposable NotifyCharacteristicValue([NotNull] this IBleGattServerConnection server, Guid service,
                                                            Guid characteristic, Action <Byte[]> onNotify,
                                                            Action <Exception> onError = null)
        {
            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            return(server.NotifyCharacteristicValue(
                       service,
                       characteristic,
                       Observer.Create((Tuple <Guid, Byte[]> tuple) => onNotify(tuple.Item2), null, onError)));
        }
Exemplo n.º 8
0
        public BleGattCharacteristicViewModel(Guid serviceGuid, Guid characteristicGuid,
                                              IBleGattServerConnection gattServer, IUserDialogs dialogManager)
        {
            m_gattServer         = gattServer;
            m_dialogManager      = dialogManager;
            m_serviceGuid        = serviceGuid;
            m_characteristicGuid = characteristicGuid;

            RefreshValueCommand         = new Command(async() => { await ReadCharacteristicValue(); });
            EnableNotificationsCommand  = new Command(EnableNotifications);
            DisableNotificationsCommand = new Command(DisableNotifications);
            ToggleNotificationsCommand  = new Command(() => { NotifyEnabled = !NotifyEnabled; });
            WriteBytesCommand           = new Command(async() => { await WriteCurrentBytes(); });

            WriteCurrentBytesGUIDCommand = new Command(async() => { await WriteCurrentBytesGUID(); });


            ValueAsHex = String.Empty;

            ValueAsString   = String.Empty;
            ValueAsHexBytes = new Byte[] {};

            m_gattServer.ReadCharacteristicProperties(m_serviceGuid, m_characteristicGuid).ContinueWith(
                x =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    if (x.IsFaulted)
                    {
                        m_dialogManager.Toast(x.Exception.GetBaseException().Message);
                    }
                    else
                    {
                        Log.Trace("Reading properties for characteristic. id={0}", m_characteristicGuid);
                        m_props = x.Result;
                        RaisePropertyChanged(nameof(CanNotify));
                        RaisePropertyChanged(nameof(CanRead));
                        RaisePropertyChanged(nameof(CanWrite));
                        RaisePropertyChanged(nameof(CanIndicate));
                    }
                });
            });
        }
        public async Task OpenConnection()
        {
            // if we're busy or have a valid connection, then no-op
            if (IsBusy || m_gattServer != null && m_gattServer.State != ConnectionState.Disconnected)
            {
                //Log.Debug( "OnAppearing. state={0} isbusy={1}", m_gattServer?.State, IsBusy );
                return;
            }

            await CloseConnection();

            IsBusy = true;

            var connection = await m_bleAdapter.ConnectToDevice(
                device : m_peripheral.Model,
                timeout : TimeSpan.FromSeconds(CONNECTION_TIMEOUT_SECONDS),
                progress : progress => { Connection = progress.ToString(); });

            if (connection.IsSuccessful())
            {
                m_gattServer = connection.GattServer;
                Log.Debug("Connected to device. id={0} status={1}", m_peripheral.Id, m_gattServer.State);

                Settings.IsConnectedBLE = true;

                m_gattServer.Subscribe(
                    async c =>
                {
                    if (c == ConnectionState.Disconnected)
                    {
                        m_dialogManager.Toast("Device disconnected");
                        await CloseConnection();

                        //await OpenConnection();
                    }

                    Connection = c.ToString();
                });

                Connection = "Reading Services";
                try
                {
                    var services = (await m_gattServer.ListAllServices()).ToList();
                    foreach (var serviceId in services)
                    {
                        if (Services.Any(viewModel => viewModel.Guid.Equals(serviceId)))
                        {
                            continue;
                        }

                        Services.Add(new BleGattServiceViewModel(serviceId, m_gattServer, m_dialogManager));
                    }

                    if (Services.Count == 0)
                    {
                        m_dialogManager.Toast("No services found");
                    }

                    Connection = m_gattServer.State.ToString();
                }
                catch (GattException ex)
                {
                    Log.Warn(ex);
                    m_dialogManager.Toast(ex.Message, TimeSpan.FromSeconds(3));
                }
            }
            else
            {
                String errorMsg;
                if (connection.ConnectionResult == ConnectionResult.ConnectionAttemptCancelled)
                {
                    errorMsg = "Connection attempt cancelled after {0} seconds (see {1})".F(
                        CONNECTION_TIMEOUT_SECONDS,
                        GetType().Name + ".cs");
                }
                else
                {
                    errorMsg = "Error connecting to device: {0}".F(connection.ConnectionResult);
                }

                Settings.IsConnectedBLE = false;

                Log.Info(errorMsg);
                m_dialogManager.Toast(errorMsg, TimeSpan.FromSeconds(5));
            }

            IsBusy = false;
        }
Exemplo n.º 10
0
 /// <summary>
 /// </summary>
 public BlePeripheralConnectionRequest(ConnectionResult connectionResult, IBleGattServerConnection gattServer)
 {
     ConnectionResult = connectionResult;
     GattServer       = gattServer;
 }
Exemplo n.º 11
0
        async Task Connect(bool connect)
        {
            if (connect)
            {
                // Forza la connessione
                if (Adapter.AdapterCanBeEnabled && Adapter.CurrentState.IsDisabledOrDisabling())
                {
                    Debug.WriteLine("Attivo adattatore.");
                    await Adapter.EnableAdapter();
                }

                Debug.WriteLine("Tento la connessione.");
                var connection = await Adapter.FindAndConnectToDevice(
                    new ScanFilter()
                    .SetAdvertisedDeviceName("ADJUST")
                    //.SetAdvertisedManufacturerCompanyId(0xffff)
                    //.AddAdvertisedService(guid)
                    ,
                    TimeSpan.FromSeconds(30)
                    );

                if (connection.IsSuccessful())
                {
                    Debug.WriteLine($"Connesso a { connection.GattServer.DeviceId} { connection.GattServer.Advertisement.DeviceName}");
                    GattServer = connection.GattServer;

                    try
                    {
                        notifyHandler = GattServer.NotifyCharacteristicValue(
                            serviceGuid,
                            buttonGuid,
                            bytes =>
                        {
                            /*// Attento. Qui puòrrivarti un solo byte o due o quattro a seconda del tipo
                             *                             // di dato che hai devinito lato ESP32...
                             *                             // Ora lato ESP32 ho usato un uint16_t
                             *                             var val = BitConverter.ToUInt16(bytes, 0);
                             *                             Debug.WriteLine($"{bytes.Count()} byte ({val}) da {buttonGuid}");
                             *                             if (val == 1)
                             *                                 lblTitolo.BackgroundColor = Color.Red;
                             *                             else
                             *                                 lblTitolo.BackgroundColor = oldColor;
                             *
                             */
                        }
                            );
                    }
                    catch (GattException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }

                    #region old

                    #endregion
                }
                else
                {
                    Debug.WriteLine("Error connecting to device. result={0:g}", connection.ConnectionResult);
                }
            }
            else
            {
                // Forza la disconnessione
                if (GattServer != null)
                {
                    if (GattServer.State == ConnectionState.Connected ||
                        GattServer.State == ConnectionState.Connecting)
                    {
                        await GattServer.Disconnect();

                        // una volta disconnesso, meglio spegnere anche i notificatori...
                        notifyHandler.Dispose();
                    }
                }
            }

            Debug.WriteLine($"Stato della connessione: { GattServer.State}");
        }
Exemplo n.º 12
0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using nexus.protocols.ble;
using nexus.protocols.ble.scan;
using Xamarin.Forms;
using nexus.protocols.ble.gatt.adopted;
using nexus.protocols.ble.gatt;

namespace Adjust
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(true)]
    public partial class Page3 : ContentPage
    {
        IBluetoothLowEnergyAdapter Adapter { get; set; }
        IBleGattServerConnection GattServer { get; set; }
        Guid serviceGuid = new Guid("0000ffe0-0000-1000-8000-00805f9b34fb");
        Guid sliderGuid = new Guid("0000ffe1-0000-1000-8000-00805f9b34fb");
        Guid buttonGuid = new Guid("ABCD1236-0aaa-467a-9538-01f0652c74e8");

        IDisposable notifyHandler;

       

        //public ICommand cmdConnect { get; }
        //public ICommand cmdDisconnect { get; }

        public Page3(IBluetoothLowEnergyAdapter adapter)
        {
            Adapter = adapter;

            // i command cosìon si bindano... Devono essere messi all'interno di una INotifyPropertyChanged...
            //cmdConnect = new Command(async () => await Connect(true));
            //cmdDisconnect = new Command(async () => await Connect(false));

            InitializeComponent();


        }


        async void btnConnect_Clicked(object sender, System.EventArgs e)
        {
            try
            {
                btnConnect.IsEnabled = false;
                // Forza la connessione
                if (Adapter.AdapterCanBeEnabled && Adapter.CurrentState.IsDisabledOrDisabling())
                {
                    Debug.WriteLine("Attivo adattatore.");
                    await Adapter.EnableAdapter();
                }

                Debug.WriteLine("Tento la connessione.");
                var connection = await Adapter.FindAndConnectToDevice(
                    new ScanFilter()
                        .SetAdvertisedDeviceName("ADJUST")
                        //.SetAdvertisedManufacturerCompanyId(0xffff)
                        //.AddAdvertisedService(guid)
                        ,
                    TimeSpan.FromSeconds(10)
                );


                if (connection.IsSuccessful())
                {
                    await Navigation.PushModalAsync(new MainPage(Adapter, connection));
                }
                else
                {
                    btnConnect.IsEnabled = true;
                    DisplayAlert("Errore", "Device non trovato...", "OK");
                }
            }
            catch (Exception errore)
            {
                DisplayAlert("Errore", errore.Message, "OK");
            }
        }

        void Handle_Appearing(object sender, System.EventArgs e)
        {
            btnConnect.IsEnabled = true;
        }

        async Task Connect(bool connect)
        {
            if (connect)
            {
                // Forza la connessione
                if (Adapter.AdapterCanBeEnabled && Adapter.CurrentState.IsDisabledOrDisabling())
                {
                    Debug.WriteLine("Attivo adattatore.");
                    await Adapter.EnableAdapter();
                }

                Debug.WriteLine("Tento la connessione.");
                var connection = await Adapter.FindAndConnectToDevice(
                    new ScanFilter()
                        .SetAdvertisedDeviceName("ADJUST")
                        //.SetAdvertisedManufacturerCompanyId(0xffff)
                        //.AddAdvertisedService(guid)
                        ,
                    TimeSpan.FromSeconds(30)
                );

                if (connection.IsSuccessful())
                {
                    Debug.WriteLine($"Connesso a { connection.GattServer.DeviceId} { connection.GattServer.Advertisement.DeviceName}");
                    GattServer = connection.GattServer;

                    try
                    {
                        notifyHandler = GattServer.NotifyCharacteristicValue(
                           serviceGuid,
                           buttonGuid,
                           bytes =>
                           {

                               /*// Attento. Qui puòrrivarti un solo byte o due o quattro a seconda del tipo
                                                              // di dato che hai devinito lato ESP32...
                                                              // Ora lato ESP32 ho usato un uint16_t
                                                              var val = BitConverter.ToUInt16(bytes, 0);
                                                              Debug.WriteLine($"{bytes.Count()} byte ({val}) da {buttonGuid}");
                                                              if (val == 1)
                                                                  lblTitolo.BackgroundColor = Color.Red;
                                                              else
                                                                  lblTitolo.BackgroundColor = oldColor;

                                                         */
                           }
                        );
                    }
                    catch (GattException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }

                    #region old

                    #endregion

                }
                else
                    Debug.WriteLine("Error connecting to device. result={0:g}", connection.ConnectionResult);
            }
            else
            {
                // Forza la disconnessione
                if (GattServer != null)
                {
                    if (GattServer.State == ConnectionState.Connected ||
                        GattServer.State == ConnectionState.Connecting)
                    {
                        await GattServer.Disconnect();

                        // una volta disconnesso, meglio spegnere anche i notificatori...
                        notifyHandler.Dispose();
                    }
                }
            }

            Debug.WriteLine($"Stato della connessione: { GattServer.State}");
        }
    }
}



Exemplo n.º 13
0
        async Task Connect(bool connect)
        {
            if (connect)
            {
                // Forza la connessione
                if (Adapter.AdapterCanBeEnabled && Adapter.CurrentState.IsDisabledOrDisabling())
                {
                    Debug.WriteLine("Attivo adattatore.");
                    await Adapter.EnableAdapter();
                }

                Debug.WriteLine("Tento la connessione.");
                var connection = await Adapter.FindAndConnectToDevice(
                    new ScanFilter()
                    .SetAdvertisedDeviceName("Sensore Techno Back Brace")
                    //.SetAdvertisedManufacturerCompanyId(0xffff)
                    //.AddAdvertisedService(guid)
                    ,
                    TimeSpan.FromSeconds(30)
                    );

                if (connection.IsSuccessful())
                {
                    Debug.WriteLine($"Connesso a {connection.GattServer.DeviceId} {connection.GattServer.Advertisement.DeviceName}");
                    GattServer = connection.GattServer;

                    try
                    {
                        notifyHandler = GattServer.NotifyCharacteristicValue(
                            serviceGuid,
                            buttonGuid,
                            bytes =>
                        {
                            // Attento. Qui può arrivarti un solo byte o due o quattro a seconda del tipo
                            // di dato che hai devinito lato ESP32...
                            // Ora lato ESP32 ho usato un uint16_t
                            var val = BitConverter.ToUInt16(bytes, 0);
                            Debug.WriteLine($"{bytes.Count()} byte ({val}) da {buttonGuid}");
                            if (val == 1)
                            {
                                lblTitolo.BackgroundColor = Color.Red;
                            }
                            else
                            {
                                lblTitolo.BackgroundColor = oldColor;
                            }
                        }
                            );
                    }
                    catch (GattException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }

                    #region old

                    /*
                     * foreach(var sGuid in await GattServer.ListAllServices())
                     * {
                     *  Debug.WriteLine($"service: {known.GetDescriptionOrGuid(sGuid)}");
                     *
                     *  foreach (var cGuid in await GattServer.ListServiceCharacteristics(sGuid))
                     *  {
                     *      Debug.WriteLine($"characteristic: {known.GetDescriptionOrGuid(cGuid)}");
                     *
                     *      // Memorizza i Guid
                     *      serviceGuid = sGuid;
                     *      charGuid = cGuid;
                     *
                     *      try
                     *      {
                     *          var valueArray = await GattServer.ReadCharacteristicValue(sGuid, cGuid);
                     *          var intValue = BitConverter.ToInt32(valueArray, 0);
                     *          Debug.WriteLine(intValue);
                     *
                     *          try
                     *          {
                     *              // Will also stop listening when gattServer
                     *              // is disconnected, so if that is acceptable,
                     *              // you don't need to store this disposable.
                     *              notifyHandler = GattServer.NotifyCharacteristicValue(
                     *                 sGuid,
                     *                 cGuid,
                     *                 // IObserver<Tuple<Guid, Byte[]>> or IObserver<Byte[]> or
                     *                 // Action<Tuple<Guid, Byte[]>> or Action<Byte[]>
                     *                 bytes => {
                     *                     var intValue2 = BitConverter.ToInt32(bytes, 0);
                     *                     Debug.WriteLine(intValue2);
                     *                     Pulsante = intValue2 == 1 ? true : false;
                     *
                     *                     if (Pulsante)
                     *                         lblTitolo.BackgroundColor = Color.Red;
                     *                     else
                     *                         lblTitolo.BackgroundColor = oldColor;
                     *
                     *                 });
                     *          }
                     *          catch (GattException ex)
                     *          {
                     *              Debug.WriteLine(ex.ToString());
                     *          }
                     *
                     *      }
                     *      catch (GattException ex)
                     *      {
                     *          Debug.WriteLine(ex.ToString());
                     *      }
                     *  }
                     * }
                     */

                    #endregion
                }
                else
                {
                    Debug.WriteLine("Error connecting to device. result={0:g}", connection.ConnectionResult);
                }
            }
            else
            {
                // Forza la disconnessione
                if (GattServer != null)
                {
                    if (GattServer.State == ConnectionState.Connected ||
                        GattServer.State == ConnectionState.Connecting)
                    {
                        await GattServer.Disconnect();

                        // una volta disconnesso, meglio spegnere anche i notificatori...
                        notifyHandler.Dispose();
                    }
                }
            }

            Debug.WriteLine($"Stato della connessione: {GattServer.State}");
        }
        public BleGattServicePage(BleGattServiceViewModel model, IBleGattServerConnection gattServer, IUserDialogs dialogs)
        {
            InitializeComponent();
            BindingContext = model;

            model_saved = model;

            cargarMTU();


            NavigationPage.SetHasNavigationBar(this, false); //Turn off the Navigation bar

            back_button.Tapped += returntomain;



            Task.Run(async() =>
            {
                await Task.Delay(2000); Device.BeginInvokeOnMainThread(() =>
                {
                    model_saved.Characteristic.RemoveAt(0);



                    Guid ServicioIndicate      = new Guid("2cf42000-7992-4d24-b05d-1effd0381208");
                    Guid CaracterisicoIndicate = new Guid("00000003-0000-1000-8000-00805f9b34fb");

                    BleGattCharacteristicViewModel gattCharacteristicViewModelIndicate = new BleGattCharacteristicViewModel(ServicioIndicate, CaracterisicoIndicate, gattServer, dialogs);

                    var viewModelIndicate = (BleGattCharacteristicViewModel)gattCharacteristicViewModelIndicate;

                    if (viewModelIndicate.EnableNotificationsCommand.CanExecute(null))
                    {
                        viewModelIndicate.EnableNotificationsCommand.Execute(null);
                    }



                    model_saved.Characteristic.Add(gattCharacteristicViewModelIndicate);

                    BindingContext = model_saved;

                    lista.BeginRefresh();

                    lista.EndRefresh();



                    Task.Run(async() =>
                    {
                        await Task.Delay(1000); Device.BeginInvokeOnMainThread(() =>
                        {
                            model_saved.Characteristic.RemoveAt(0);

                            Guid ServicioWrite      = new Guid("2cf42000-7992-4d24-b05d-1effd0381208");
                            Guid CaracterisicoWrite = new Guid("00000002-0000-1000-8000-00805f9b34fb");
                            // String valorDato = "000005258000015a";

                            BleGattCharacteristicViewModel gattCharacteristicViewModelWrite = new BleGattCharacteristicViewModel(ServicioWrite, CaracterisicoWrite, gattServer, dialogs);

                            var viewModelWrite = (BleGattCharacteristicViewModel)gattCharacteristicViewModelWrite;
                            if (viewModelWrite.WriteCurrentBytesGUIDCommand.CanExecute(null))
                            {
                                viewModelWrite.WriteCurrentBytesGUIDCommand.Execute(null);
                            }



                            model_saved.Characteristic.Add(gattCharacteristicViewModelWrite);

                            BindingContext = model_saved;

                            lista.BeginRefresh();

                            lista.EndRefresh();


                            Task.Run(async() =>
                            {
                                await Task.Delay(1000); Device.BeginInvokeOnMainThread(() =>
                                {
                                    BleGattCharacteristicViewModel[] array = new BleGattCharacteristicViewModel[10];
                                    model_saved.Characteristic.CopyTo(array, 0);



                                    Byte[] value1 = array[0].ValueAsHexBytes;

                                    int longitud = value1.Length;

                                    int contador = 0;


                                    byte[] listTotal    = new byte[1024];
                                    int listTotalLength = 0;
                                    int cuantoDato      = 0;

                                    while (contador < longitud)
                                    {
                                        byte[] array2 = new byte[20];

                                        Array.Copy(value1, contador, array2, 0, 20);

                                        cuantoDato = array2[2];
                                        if (cuantoDato > 0)
                                        {
                                            Array.Copy(array2, 3, listTotal, listTotalLength, cuantoDato);
                                            listTotalLength += cuantoDato;
                                        }

                                        contador = contador + 20;
                                    }


                                    //Identificador
                                    byte[] identificador = new byte[4];
                                    Array.Copy(listTotal, 6 + 5, identificador, 0, 4);

                                    long identificador_valor = (long)(identificador[3] * Math.Pow(2, 24)
                                                                      + identificador[2] * Math.Pow(2, 16)
                                                                      + identificador[1] * Math.Pow(2, 8)
                                                                      + identificador[0] * Math.Pow(2, 0));


                                    //oneWayTx
                                    byte[] oneWayTx = new byte[4];
                                    Array.Copy(listTotal, 10 + 5, oneWayTx, 0, 4);


                                    long oneWayTx_valor = (long)(oneWayTx[3] * Math.Pow(2, 24)
                                                                 + oneWayTx[2] * Math.Pow(2, 16)
                                                                 + oneWayTx[1] * Math.Pow(2, 8)
                                                                 + oneWayTx[0] * Math.Pow(2, 0));


                                    //TwoWayTx
                                    byte[] TwoWayTx = new byte[4];
                                    Array.Copy(listTotal, 14 + 5, TwoWayTx, 0, 4);


                                    long TwoWayTx_valor = (long)(TwoWayTx[3] * Math.Pow(2, 24)
                                                                 + TwoWayTx[2] * Math.Pow(2, 16)
                                                                 + TwoWayTx[1] * Math.Pow(2, 8)
                                                                 + TwoWayTx[0] * Math.Pow(2, 0));

                                    //TwoWayRx
                                    byte[] TwoWayRx = new byte[4];
                                    Array.Copy(listTotal, 18 + 5, TwoWayRx, 0, 4);


                                    long TwoWayRx_valor = (long)(TwoWayRx[3] * Math.Pow(2, 24)
                                                                 + TwoWayRx[2] * Math.Pow(2, 16)
                                                                 + TwoWayRx[1] * Math.Pow(2, 8)
                                                                 + TwoWayRx[0] * Math.Pow(2, 0));

                                    String listatotla = listTotal.EncodeToBase16String();
                                    valorHEX.Text     = listatotla.Substring(0, listTotalLength * 2);

                                    cargarValoresMTU(identificador_valor.ToString(), oneWayTx_valor.ToString(), TwoWayTx_valor.ToString(), TwoWayRx_valor.ToString());
                                });
                            });
                        });
                    });
                });
            });
        }
Exemplo n.º 15
0
        private async Task <IBleGattServerConnection> GetRLConnection()
        {
            var peripheral = await this.GetRileyLink();

            if (peripheral == null)
            {
                throw new Exception("Failed to find RL");
            }

            if (_connection == null || _connection.State != ConnectionState.Connected)
            {
                Console.WriteLine($"Starting new connection");
                var connectionRequest = await this.Ble.ConnectToDevice(_peripheral, TimeSpan.FromSeconds(10));

                if (connectionRequest.IsSuccessful())
                {
                    Console.WriteLine($"Connected");
                    _connection = connectionRequest.GattServer;
                    if (_disconnectTimer != null)
                    {
                        _disconnectTimer.Dispose();
                    }
                    _disconnectTimer = new Timer(
                        async(state) =>
                    {
                        var conn = (IBleGattServerConnection)state;
                        if (conn != null && conn.State == ConnectionState.Connected)
                        {
                            await conn.Disconnect();
                        }
                    },
                        _connection, Timeout.Infinite, Timeout.Infinite);

                    ResponseQueue = new Queue <byte[]>();

                    _connection.NotifyCharacteristicValue(RileyLinkServiceUUID, RileyLinkResponseCharacteristicUUID,
                                                          async(byte[] data) =>
                    {
                        Console.WriteLine($"Notify counter: {data[0]}");
                        var response = await _connection.ReadCharacteristicValue(RileyLinkServiceUUID, RileyLinkDataCharacteristicUUID);
                        ResponseQueue.Enqueue(response);
                        NotificationQueued.Set();
                        ResetTimer();
                    });

                    Console.WriteLine($"Emptying queue");
                    await _connection.WriteCharacteristicValue(RileyLinkServiceUUID, RileyLinkDataCharacteristicUUID, new byte[] { 0x01, 0x00 });

                    while (true)
                    {
                        NotificationQueued.Wait(200);
                        if (ResponseQueue.Count > 0)
                        {
                            ResponseQueue.Dequeue();
                        }
                        else
                        {
                            break;
                        }
                        NotificationQueued.Reset();
                    }
                    Console.WriteLine($"Queue emptied");
                }
            }
            ResetTimer();
            return(_connection);
        }
Exemplo n.º 16
0
        /* Internal */
        private async Task <bool> SetupBLEConnection(BlePeripheralConnectionRequest connection)
        {
            bool targetFound = false;
            bool setupDone   = false;

            /* Look for Service UUID and Characteristic UUID on device Target */
            try
            {
                IEnumerable <Guid> services = await connection.GattServer.ListAllServices();

                foreach (Guid service in services)
                {
                    string serviceString = service.ToString();

                    if (true == string.Equals(serviceString, Library.BLE_DEVICE_SERVICE_UUID_TARGET, StringComparison.OrdinalIgnoreCase))
                    {
                        g_BLETargetService = service;
                        IEnumerable <Guid> characteristics = await connection.GattServer.ListServiceCharacteristics(service);

                        foreach (Guid characteristic in characteristics)
                        {
                            g_BLETargetCharacteristic = characteristic;
                            string characteristicString = characteristic.ToString();

                            if (true == string.Equals(characteristicString, Library.BLE_DEVICE_CHARACTERISTIC_UUID_TARGET, StringComparison.OrdinalIgnoreCase))
                            {
                                targetFound = true;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            if (true == targetFound)
            {
                // Subcribe to notifications of Target characteristic
                try
                {
                    g_BLEAdapterObj_notificationServiceObserver = OnBLEConnection_ServiceNotification;
                    connection.GattServer.NotifyCharacteristicValue(g_BLETargetService, g_BLETargetCharacteristic, g_BLEAdapterObj_notificationServiceObserver);
                    setupDone = true;
                }
                catch (GattException)
                {
                }

                if (true == setupDone)
                {
                    // Suscribe to receive BLE Connection state changes
                    g_BLEAdapterObj_connectionStateObserver = OnBLEConnection_StateChange;
                    connection.GattServer.Subscribe(Observer.Create <ConnectionState>(g_BLEAdapterObj_connectionStateObserver, null, null));

                    // Get Gatt Server handler
                    g_BLEAdapterObj_connectionGattServer = connection.GattServer;
                }
            }

            return(setupDone);
        }