public async Task <bool> CheckServiceAndCharateristics() { if (this.BLEDevice == null || this.BLEDevice.State != Plugin.BLE.Abstractions.DeviceState.Connected) { return(false); } this.MTU = await BLEDevice.RequestMtuAsync(517); var service = await BLEDevice.GetServiceAsync(uuid_service); if (service == null) { return(false); } Charateristic = await service.GetCharacteristicAsync(uuid_characteristic); if (Charateristic == null) { return(false); } return(true); }
public async Task WriteToBLE() { var services = await BLEDevice.GetServicesAsync(); if (services == null) { return; } var characteristics = await services[0].GetCharacteristicsAsync(); var characteristic = characteristics[0]; if (characteristic != null) { if (characteristic.CanWrite) { byte[] buf = { 0x01, 0x00 }; if (ledStatus) { buf[1] = 0x01; await characteristic.WriteAsync(buf); } else { buf[1] = 0x00; await characteristic.WriteAsync(buf); } ledStatus = !ledStatus; } } }
public async void LED1() { var service = await BLEDevice.GetServiceAsync(Guid.Parse("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")); var WriteCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")); var ReadCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")); //byte[] data = new byte[] { 0x31 }; if (WriteCharacteristic != null) { if (WriteCharacteristic.CanWrite) { byte[] data = new byte[] { 0x31 }; await WriteCharacteristic.WriteAsync(data); //byte[] readdata = new byte; if (ReadCharacteristic.CanRead) { byte[] readdata = await ReadCharacteristic.ReadAsync(); if (readdata == new byte[] { 0x31 }) { byte[] confirm = new byte[] { 0x33 }; await WriteCharacteristic.WriteAsync(confirm); await Task.Delay(1000); await WriteCharacteristic.WriteAsync(new byte[] { 0x36 }); } } } } }
public async Task SetupNotifications(string bleDeviceId, Dictionary <string, string> telemetryMap) { BLEDevice = await BLEService.Connect(bleDeviceId); TelemetryMap = telemetryMap; foreach (var gatt in telemetryMap) { var telemetryField = gatt.Value; var pair = new GattPair(gatt.Key); var service = await BLEDevice.GetServiceAsync(pair.ServiceId); if (service != null) // service could be null if mapping has old values related to other devices { var characteristic = await service.GetCharacteristicAsync(pair.CharacteristicId); if (characteristic != null) // like above but for characteristic { if (telemetryField != null) { await BLEService.EnableNotification(characteristic); } else { await BLEService.DisableNotification(characteristic); } } } } MessagingCenter.Send(new ResultMessage <IDevice>(BLEDevice), Constants.BLE_DEVICE_READY); }
public async Task <bool> ConnectDeviceAsync(BLEDevice device) { try { CancellationTokenSource tokenSource = new CancellationTokenSource(); System.Diagnostics.Debug.WriteLine("Connecting to " + device.Name); await _adapterInstance.ConnectToDeviceAsync(device.Device, new ConnectParameters(autoConnect : true, forceBleTransport : false), tokenSource.Token); System.Diagnostics.Debug.WriteLine("Connected to " + device.Name); _findMeConnected = device; // Send message MessagingCenter.Send <BLEService>(this, "deviceConnected"); return(true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Connection error " + ex.Message); return(false); } }
public DeviceViewModel(BLEDevice device) { _device = device; _device.ConnectionLost += OnConnectionLost; _handlers = BuildHandlers(); _values = new ConcurrentQueue <byte[]>(); _codeSlim = new SemaphoreSlim(1, 1); _writeSlim = new SemaphoreSlim(1, 1); }
public void DisconnectDevice() { if (BLEDevice != null) { AdapterBLE.DisconnectDeviceAsync(BLEDevice); BLEDevice.Dispose(); BLEDevice = null; } }
//--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- #endregion #region --Misc Methods (Private)-- private void LoadInfos(BLEDevice device) { UpdateViewState(State_Loading.Name); if (!(device is null)) { VIEW_MODEL.LoadInfos(device); UpdateViewState(State_Success.Name); } }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public void LoadInfos(BLEDevice device) { MODEL.Device = device; MODEL.DeviceName = device.CACHE.GetString(BTUtils.CHARACTERISTIC_DEVICE_NAME) ?? ""; MODEL.DeviceHardwareRevision = device.CACHE.GetString(BTUtils.CHARACTERISTIC_HARDWARE_REVISION) ?? ""; MODEL.DeviceLanguage = device.CACHE.GetString(BTUtils.CHARACTERISTIC_LANGUAGE) ?? ""; MODEL.DeviceManufacturer = device.CACHE.GetString(BTUtils.CHARACTERISTIC_MANUFACTURER_NAME) ?? ""; MODEL.DeviceSerialNumber = device.CACHE.GetString(BTUtils.CHARACTERISTIC_SERIAL_NUMBER) ?? ""; }
private void OnDeviceDisconnected(object sender, DeviceEventArgs args) { System.Diagnostics.Debug.WriteLine("Disconnected " + args.Device.Name); // Reset device _findMeConnected = null; // Send message MessagingCenter.Send <BLEService>(this, "deviceDisconnected"); }
private void OnDeviceConnectionLost(object sender, DeviceErrorEventArgs args) { System.Diagnostics.Debug.WriteLine("Connection lost with " + args.Device.Name); // Resert device connected _findMeConnected = null; // Send message MessagingCenter.Send <BLEService>(this, "deviceConnectionLost"); }
private void BtnDisconnect_Clicked(object sender, EventArgs e) { BLEDevice device = Windesheart.PairedDevice; device.Disconnect(true); Device.BeginInvokeOnMainThread(delegate { StatusText.Text = "Desconectado."; BtnScan.IsEnabled = true; }); }
private void Scan() { // Scan for any Bluetooth device // For Android: if we scan using the given config-object we can command the scanner to only scan for Bean-devices // This doesn't work in iOS (error in the NuGet-package) var config = new ScanConfig(); if (Device.OS == TargetPlatform.Android) { config.ServiceUuid = Constants.BeanServiceAdvertisingUuid; } _scanner = CrossBleAdapter.Current.Scan(config).Subscribe(scanResult => { // Only add the Bluetooth devices that have the right advertisement UUID // You should be using "new ScanConfig ..." as a parameter in "Scan()" but that's not doing anything (as of today)... if (Device.OS == TargetPlatform.iOS) { // Since we are unable to use the config-object in iOS, we look at the advertisement-service once we've discovered a device // If this ID isn't equal to our Constant, don't add the device if (scanResult.AdvertisementData == null || scanResult.AdvertisementData.ServiceUuids == null || scanResult.AdvertisementData.ServiceUuids.Count() == 0 || scanResult.AdvertisementData.ServiceUuids[0] != Constants.BeanServiceAdvertisingUuid) { return; } } // First check if the found device is already added to the collection // The easiest way to do this, is by Id (UUID) if (IsDeviceAlreadyAdded(scanResult.Device)) { // If the device is already added to the collection, no need to re-add it return; } // Device is not added yet, so add it // First create a new instance of "BLEDevice" var device = new BLEDevice { Id = scanResult.Device.Uuid, Name = scanResult.Device.Name, NativeDevice = scanResult.Device }; // Next add this to the collection // Since "Devices" is an ObservableCollection the UI will automatically be notified // If added to prevent emty devices if (!string.IsNullOrWhiteSpace(device.Name)) { Devices.Add(device); } }); }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public void LoadInfos(BLEDevice device) { MODEL.Device = device; MODEL.DeviceName = device.CACHE.GetString(BTUtils.CHARACTERISTIC_DEVICE_NAME) ?? ""; MODEL.DeviceHardwareRevision = device.CACHE.GetString(BTUtils.CHARACTERISTIC_HARDWARE_REVISION) ?? ""; MODEL.DeviceLanguage = device.CACHE.GetString(BTUtils.CHARACTERISTIC_LANGUAGE) ?? ""; MODEL.DeviceManufacturer = device.CACHE.GetString(BTUtils.CHARACTERISTIC_MANUFACTURER_NAME) ?? ""; MODEL.DeviceSerialNumber = device.CACHE.GetString(BTUtils.CHARACTERISTIC_SERIAL_NUMBER) ?? ""; MODEL.WifiSsid = GetCurrentWiFiSsid(); MODEL.Jid = "*****@*****.**"; MODEL.JidPassword = "******"; }
protected async Task <Peripheral> ConnectAsync(string id) { // Ble connect Debug.Log($"GrayBlue try connect. id={id}"); var ble = new BLEDevice(id); var success = await grayBlueCentral.ConnectAsync(id, ble); if (!success) { Debug.Log($"GrayBlue connect failed. id={id}"); return(null); } Debug.Log($"GrayBlue connect done. id={id}"); return(new Peripheral(ble)); }
void FindBLEDeviceEvent(object sender, System.EventArgs e) { root.transform.FindChild("BLEListCanvas").gameObject.SetActive(true); root.transform.FindChild("Canvas").gameObject.SetActive(true); root.transform.FindChild("TTT").gameObject.SetActive(false); devicelist.Clear(); string json = sender as string; JsonData ListJson = JsonMapper.ToObject(json); for (int i = 0; i < ListJson.Count; i++) { BLEDevice deviceModel = new BLEDevice(); JsonData item = ListJson [i]; IDictionary deviceDic = item as IDictionary; if (deviceDic.Contains("mac")) { string macString = item ["mac"].ToString(); deviceModel.mac = macString; } if (deviceDic.Contains("name")) { string name = item ["name"].ToString(); deviceModel.name = name; } devicelist.Add(deviceModel); } for (int i = 0; i < 10; i++) { string sIndex = "Button (" + (i + 1).ToString() + ")"; string directory = "BLEListCanvas/Panel/" + sIndex; GameObject button = root.transform.Find(directory).gameObject; if (i < devicelist.Count) { button.SetActive(true); } else { button.SetActive(false); } } }
private async void DisconnectDevice(BLEDevice device) { try { if (!device.IsConnected) { return; } System.Diagnostics.Debug.WriteLine("Disconnecting " + device.Name + "..."); await _adapterInstance.DisconnectDeviceAsync(device.Device); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Disconnect error " + ex.Message); } }
public async Task ReadHeartrate() { BLEDevice device = Windesheart.PairedDevice; try { if (device.IsConnected()) { device.EnableRealTimeHeartrate(OnHeartrateUpdate); await Task.Delay(60000); device.DisableRealTimeHeartrate(); } } catch (Exception e1) { Console.WriteLine("ERRO - - - - " + e1); } }
public async void LED4() { var service = await BLEDevice.GetServiceAsync(Guid.Parse("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")); var characteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")); //var RXcharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")); //byte[] data = new byte[] { 0x31 }; if (characteristic != null) { if (characteristic.CanWrite) { byte[] data = new byte[] { 0x35 }; await characteristic.WriteAsync(data); } } }
private async void OnIntervalClicked(object sender, EventArgs e) { var intervalButton = sender as Button; BLEDevice device = Windesheart.PairedDevice; if (device.IsConnected()) { if (intervalButton == null) { return; } var interval = Convert.ToInt32(intervalButton.Text); device.SetHeartrateMeasurementInterval(interval); } else { await DisplayAlert("Aviso", "Nenhum dispositivo conectado.", "OK"); } }
private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (this) { log(String.Format("Added {0}{1}", deviceInfo.Id, deviceInfo.Name)); // Protect against race condition if the task runs after the app stopped the deviceWatcher. if (sender == deviceWatcher) { BLEDevice ble = new BLEDevice(deviceInfo); // Make sure device isn't already present in the list. if (!KnownDevices.Contains(ble)) { KnownDevices.Add(ble); } } } }); }
/* * public async void WriteToBLE() * { * var services = await BLEDevice.GetServicesAsync(); * Debug.WriteLine("Test"); * if (services == null) * return; * * var characteristics = await services[0].GetCharacteristicsAsync(); * var characteristic = characteristics[0]; * * if (characteristic != null) * { * if (characteristic.CanWrite) * { * byte[] buf = new byte[] { 0x31 }; * if (ledStatus) * { * //buf[1] = 0x31; * await characteristic.WriteAsync(buf); * } * else * { * //buf[1] = 0x31; * await characteristic.WriteAsync(buf); * } * ledStatus = !ledStatus; * } * } * * }*/ public async void LEDSON(int lednumber) { var service = await BLEDevice.GetServiceAsync(Guid.Parse("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")); var WriteCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")); var ReadCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")); //byte[] data = new byte[] { 0x31 }; byte[] ledbyte = BitConverter.GetBytes(lednumber); Array.Reverse(ledbyte); byte[] data = ledbyte; if (WriteCharacteristic != null) { if (WriteCharacteristic.CanWrite) { //byte[] data = new byte[] { 0x31 }; await WriteCharacteristic.WriteAsync(data); //byte[] readdata = new byte; if (ReadCharacteristic.CanRead) { byte[] readdata = await ReadCharacteristic.ReadAsync(); if (readdata == new byte[] { 0x31 }) { byte[] confirm = new byte[] { 0x33 }; await WriteCharacteristic.WriteAsync(confirm); await Task.Delay(1000); await WriteCharacteristic.WriteAsync(new byte[] { 0x36 }); } } } } }
public async void ReadTest() { var service = await BLEDevice.GetServiceAsync(Guid.Parse("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")); //var WriteCharacteristic = await service.Get(); //var ReadCharacteristic = await service.GetCharacteristicsAsync(); var WriteCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")); var ReadCharacteristic = await service.GetCharacteristicAsync(Guid.Parse("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")); System.Diagnostics.Debug.WriteLine(ReadCharacteristic); Debug.WriteLine("Write Characteristic = " + WriteCharacteristic); System.Diagnostics.Debug.WriteLine("Read Characteristic CanRead = " + ReadCharacteristic.CanRead); await WriteCharacteristic.WriteAsync(new byte[] { 0x31 }); ReadCharacteristic.ValueUpdated += (s, e) => { Debug.WriteLine("New value : ", e.Characteristic.Value); }; await ReadCharacteristic.StartUpdatesAsync(); if (ReadCharacteristic.CanRead) { var readdata = await ReadCharacteristic.ReadAsync(); System.Diagnostics.Debug.WriteLine(readdata); if (readdata == new byte[] { 0x31 }) { byte[] confirm = new byte[] { 0x33 }; await WriteCharacteristic.WriteAsync(confirm); await Task.Delay(1000); await WriteCharacteristic.WriteAsync(new byte[] { 0x36 }); } } }
public async void WhenDeviceFound(BLEScanResult result) { Device.BeginInvokeOnMainThread(delegate { StatusText.Text = "Dispositivo Encontrado."; }); Console.WriteLine("Device found!"); BLEDevice device = result.Device; int Rssi = result.Rssi; IAdvertisementData data = result.AdvertisementData; await Task.Delay(1500); Windesheart.StopScanning(); try { device.Connect(OnConnectionFinished); } catch (Exception e1) { Console.WriteLine("ERRO - - - -" + e1); } }
private void VIEW_MODEL_ScannerDeviceFound(BluetoothScannerControlContext ctx, BLEDeviceEventArgs args) { UpdateViewState(State_Success.Name); Device = args.DEVICE; }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- public BLEDeviceEventArgs(BLEDevice device) { DEVICE = device; }
public BLEScanResult(BLEDevice device, int rssi, IAdvertisementData advertisementData) { Device = device; Rssi = rssi; AdvertisementData = advertisementData; }
private async void ScanDevice(BLEDevice b) { StatusUpdate.Text = "Using device " + b.Name; log("Using device " + b.Name + ", " + b.id); log("Enumerating Services and Characteristics..."); var dev = await BluetoothLEDevice.FromIdAsync(b.id); if (dev == null) { log("... Couldn't get Device from ID"); return; } var services = await dev.GetGattServicesAsync(); if (services == null || services.Services == null) { log("... Couldn't get services from device"); return; } bool found = false; foreach (GattDeviceService gds in services.Services) { log(b.Name + ": s" + gds.Uuid); if (gds.Uuid.ToString().Equals("6e400001-b5a3-f393-e0a9-e50e24dcca9e")) // nordic serial { found = true; } var characts = await gds.GetCharacteristicsAsync(); if (characts == null || characts.Characteristics == null) { log(b.Name + ": s" + gds.Uuid + ", couldn't enumerate characteristics"); continue; } foreach (GattCharacteristic gc in characts.Characteristics) { log(b.Name + ": s" + gds.Uuid + ", c" + gc.Uuid); if (found && gc.Uuid.ToString().Equals("6e400003-b5a3-f393-e0a9-e50e24dcca9e")) // rx { read = gc; var res = await read.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (res == GattCommunicationStatus.Success) { log("Registered for notifications"); read.ValueChanged += RX; } } if (found && gc.Uuid.ToString().Equals("6e400002-b5a3-f393-e0a9-e50e24dcca9e")) // tx { write = gc; } } } if (!found) { log("Compatable service not found"); Open.IsEnabled = false; Upload.IsEnabled = false; } else { Open.IsEnabled = true; } }
public void BtnStopHeartrate_Clicked(object sender, EventArgs e) { BLEDevice device = Windesheart.PairedDevice; device.DisableRealTimeHeartrate(); }
public MiBand3ConfigurationService(MiBand3 device) { _miBand3 = device; }