Exemple #1
0
        public async Task <bool> BLE_Connect(IBlePeripheral device)
        {
            // Get BLE device
            if ((null != g_BLEAdapterObj) && (null != device))
            {
                // Try connect to ble device
                BlePeripheralConnectionRequest connection = await g_BLEAdapterObj.ConnectToDevice(device, TimeSpan.FromSeconds(15));

                if (connection.IsSuccessful())
                {
                    // Invoke connection state callback
                    OnBLEConnection_StateChange(ConnectionState.Connected);

                    if (true == await SetupBLEConnection(connection))
                    {
                        return(true);
                    }
                    else
                    {
                        await connection.GattServer.Disconnect();
                    }
                }
            }

            return(false);
        }
        public async Task <bool> BLE_ScanAndConnect(string deviceName)
        {
            // Get BLE device
            if (null != deviceName)
            {
                // Try connect to ble device
                ScanFilter filter = new ScanFilter().SetAdvertisedDeviceName(deviceName);

                BlePeripheralConnectionRequest connection = await g_BLEAdapterObj.FindAndConnectToDevice(filter, TimeSpan.FromSeconds(15));

                if (connection.IsSuccessful())
                {
                    if (true == await SetupBLEConnection(connection))
                    {
                        return(true);
                    }
                    else
                    {
                        await connection.GattServer.Disconnect();
                    }
                }
            }

            return(false);
        }
Exemple #3
0
        public MyPage1( IBluetoothLowEnergyAdapter adapter, BlePeripheralConnectionRequest connection)
        {
            InitializeComponent();

            Adapter = adapter;

            Connection = connection;

           //valpower.Text = String.Format("{0:F1}", power.Value);


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

            try
            {


                Device.StartTimer(TimeSpan.FromSeconds(0.2), () =>
                {
                    //AggiornaStato();
                    return true; // True = Repeat again, False = Stop the timer
                });

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

        }
Exemple #4
0
        //public ICommand cmdConnect { get; }
        //public ICommand cmdDisconnect { get; }

        public MainPage(IBluetoothLowEnergyAdapter adapter, BlePeripheralConnectionRequest connection)
        {

            Adapter = adapter;

            Connection = connection;

            // 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();

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

            try
            {


                Device.StartTimer(TimeSpan.FromSeconds(0.2), () =>
                {
                    //AggiornaStato();
                    return true; // True = Repeat again, False = Stop the timer
                });

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



        }
Exemple #5
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());
            }
        }
Exemple #6
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());
            }
        }
Exemple #7
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);
        }