Example #1
0
        //---------------------------------------------------------------------
        // Initialization and task cancellation
        //---------------------------------------------------------------------

        /// <summary>
        /// Initializes local variables, like a constructor.
        /// </summary>
        private async Task Init()
        {
            //
            // Step 1
            // Acquire this device's IPv6 address from the local Bluetooth radio
            //
            generatedLocalIPv6AddressForNode = await StatelessAddressConfiguration.GenerateLinkLocalAddressFromBlThRadioIdAsync(2);

            if (generatedLocalIPv6AddressForNode == null)
            {
                Debug.WriteLine("Could not generate the local IPv6 address.");
                return;
            }

            //
            // Step 3
            // Enumerate nearby supported devices
            //
            await EnumerateNearbySupportedDevices();

            //
            // Step 4
            // Spin up the GATT server service to listen for later replies
            // over Bluetooth LE
            //
            gattServer = new GattServer();

            gattServerStarted = await StartGattServer();

            if (!gattServerStarted)
            {
                Debug.WriteLine("Aborting Init() because GATT server could " +
                                "not be started."
                                );
                return;
            }

            //
            // Step 5
            // Initialize the message cache for 10 messages
            //
            messageCache = new Queue <byte[]>(10);

            //
            // Step 6
            // Send 10 initial listening requests to the driver
            //
            //for (int i = 0; i < 10; i++)
            //{
            //    Debug.WriteLine($"Sending listening request {++count}");
            //    SendListenRequestToDriver();
            //    Thread.Sleep(100); // Wait 1/10 second to start another one
            //}
        }
Example #2
0
        //public ICommand cmdConnect { get; }
        //public ICommand cmdDisconnect { get; }

        public BLEPage(IBluetoothLowEnergyAdapter adapter, BlePeripheralConnectionRequest connection)
        {
            Adapter    = adapter;
            Connection = connection;

            // i command così non 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();
            oldColor = lblTitolo.BackgroundColor;


            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}");

                    swESP32.IsToggled = val == 1;
                }
                    );

                Device.StartTimer(TimeSpan.FromSeconds(0.2), () =>
                {
                    AggiornaStato();
                    return(true); // True = Repeat again, False = Stop the timer
                });
            }
            catch (GattException ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Example #3
0
        async void btnDisconnect_Clicked(object sender, System.EventArgs e)
        {
            // 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...
            if (buttonNotifyHandler != null)
            {
                buttonNotifyHandler.Dispose();
            }

            await Navigation.PopModalAsync();
        }
Example #4
0
        async void AggiornaStato()
        {
            bool connesso = false;

            if (GattServer != null)
            {
                connesso = GattServer.State == ConnectionState.Connected;

                // Aggiorna visualizzazione stato connessione;
                GestioneStatoConnessione(connesso);

                if (connesso)
                {
                    try
                    {
                        int sliderValore = Convert.ToInt32(slValore.Value);

                        if (sliderValore != oldSliderValue)
                        {
                            oldSliderValue = sliderValore;

                            // Spedisce il valore dello slider
                            byte[] bufferDaSpedire = BitConverter.GetBytes(sliderValore);

                            var result = await GattServer.WriteCharacteristicValue(
                                serviceGuid, sliderGuid,
                                bufferDaSpedire
                                );
                        }
                    }
                    catch (Exception errore)
                    {
                        Debug.WriteLine(errore.ToString());
                    }
                }
            }
        }
Example #5
0
        public BLEPage(IBluetoothLowEnergyAdapter adapter, BlePeripheralConnectionRequest connection)
        {
            Adapter    = adapter;
            Connection = connection;

            // i command così non 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();
            oldColor = lblTitolo.BackgroundColor;

            Valori = new Models.AdcValues();

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

            try
            {
                // Mi registro per ricevere le notifiche del bottone lato ESP32
                buttonNotifyHandler = GattServer.NotifyCharacteristicValue(
                    serviceGuid,
                    buttonGuid,
                    bytes =>
                {
                    // Attento. Qui può arrivarti un solo byte o due o quattro a seconda del tipo
                    // di dato che hai definito lato ESP32...
                    // Ora lato ESP32 ho usato un uint16_t
                    var valuleFromESP32 = BitConverter.ToUInt16(bytes, 0);
                    Debug.WriteLine($"{bytes.Count()} byte ({valuleFromESP32}) da {buttonGuid}");

                    swESP32.IsToggled = valuleFromESP32 == 1;
                }
                    );

                // Mi registro per ricevere le notifiche dell ADC lato ESP32
                adcNotifyHandler = GattServer.NotifyCharacteristicValue(
                    serviceGuid,
                    adcGuid,
                    bytes =>
                {
                    // Attento. Qui può arrivarti un solo byte o due o quattro a seconda del tipo
                    // di dato che hai definito lato ESP32...
                    // Ora lato ESP32 ho usato un int (signed)
                    var valuleFromESP32 = BitConverter.ToInt32(bytes, 0);
                    Debug.WriteLine($"{bytes.Count()} byte ({valuleFromESP32}) da {adcGuid}");

                    lblADCVal.Text = valuleFromESP32.ToString();
                    Valori.Add(new Models.AdcValue {
                        Time = DateTime.Now, Value = valuleFromESP32
                    });
                    if (Valori.Count > 100)
                    {
                        Valori.RemoveAt(0);
                    }

                    chart.ItemsSource = null;
                    chart.ItemsSource = Valori;
                }
                    );

                Device.StartTimer(TimeSpan.FromSeconds(0.2), () =>
                {
                    AggiornaStato();
                    return(true); // True = Repeat again, False = Stop the timer
                });
            }
            catch (GattException ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Example #6
0
 async void OnSuClicked(object sender, System.EventArgs e)
        {

            potenza = potenza + 1;

            try
            {
                int sliderValore = Convert.ToInt32(77777777);



                // Spedisce il valore dello slider
                byte[] bufferDaSpedire = BitConverter.GetBytes(sliderValore);

                var result = await GattServer.WriteCharacteristicValue(
                    serviceGuid, sliderGuid,
                    bufferDaSpedire
                );

            }
            catch (Exception errore)
            {
                Debug.WriteLine(errore.ToString());
            }
        }

        async void OnGiuClicked(object sender, System.EventArgs e)
        {

            potenza = potenza - 1;

            try
            {
                int sliderValore = Convert.ToInt32(44444444);



                // Spedisce il valore dello slider
                byte[] bufferDaSpedire = BitConverter.GetBytes(sliderValore);

                var result = await GattServer.WriteCharacteristicValue(
                    serviceGuid, sliderGuid,
                    bufferDaSpedire
                );

            }
            catch (Exception errore)
            {
                Debug.WriteLine(errore.ToString());
            }
        }

Example #7
0
        public static GattServer.GattServerService.GattServerCharacteristic.GattServerDescriptor ToDescriptor(this Android.Bluetooth.BluetoothGattDescriptor self, GattServer server)
        {
            var service        = server.GattServices.GetFromUuid(self.Characteristic.Service.Uuid.ToGuid());
            var characteristic = service.GattCharacteristics.GetFromUuid(self.Characteristic.Uuid.ToGuid());
            var descriptor     = characteristic.Descriptors.GetFromUuid(self.Uuid.ToGuid());

            return(descriptor);
            //var descriptor = characteristic.Descriptors.GetFromUuid(self.Uuid);
        }
        private async void startButton_Click(object sender, RoutedEventArgs e)
        {
            overallStatusBox.Text = "Starting...";

            //
            // Step 1
            // Acquire this device's IPv6 address from the local Bluetooth radio
            //
            generatedLocalIPv6AddressForNode = await StatelessAddressConfiguration.GenerateLinkLocalAddressFromBlThRadioIdAsync(2);

            if (generatedLocalIPv6AddressForNode == null)
            {
                overallStatusBox.Text = "Could not generate the local IPv6 address.";
                throw new Exception();
            }

            //localIPv6AddressesForDesktop = GetLocalIPv6AddressesOnDesktop();
            //if (localIPv6AddressesForDesktop == null)
            //{
            //    overallStatusBox.Text = "Could not acquire the local IPv6 address(es).";
            //    throw new Exception();
            //}

            //
            // Step 3
            // Enumerate nearby supported devices
            //
            await EnumerateNearbySupportedDevices();

            //
            // Step 4
            // Spin up the GATT server service to listen for later replies
            // over Bluetooth LE
            //
            gattServer = new GattServer();

            gattServerStarted = await StartGattServer();

            if (!gattServerStarted)
            {
                Debug.WriteLine("Aborting Init() because GATT server could " +
                                "not be started."
                                );
                return;
            }

            //
            // Step 5
            // Initialize the message cache for 10 messages
            //
            messageCache = new Queue <byte[]>(10);

            //
            // Step 6
            // Send 10 initial listening requests to the driver
            //
            //Debug.WriteLine($"Sending listening request {++count}");
            //SendListenRequestToDriver();

            overallStatusBox.Text = "Finished starting.";
        }
Example #9
0
     async  void OnBluetoothClicked(object sender, System.EventArgs e)
        {
            // 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...
            if (notifyHandler != null)
                notifyHandler.Dispose();

            await Navigation.PushModalAsync(new Bluetooth(Adapter));
        }