public async Task <bool> WriteValueAsync(Guid serviceId, Guid featureId, byte[] data) { try { GattDeviceService service = _device.GetGattService(serviceId); if (service == null) { Debug.WriteLine($"Unable to find service {serviceId}"); return(false); } GattCharacteristic feature = service.GetCharacteristics(featureId).SingleOrDefault(); if (feature == null) { Debug.WriteLine($"Unable to find feature {featureId}"); return(false); } await feature.WriteValueAsync(data.AsBuffer()); return(true); } catch (Exception e) { Debug.WriteLine($"Exception : {e.Message} {e.StackTrace}"); } return(false); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { selectedBtleDevice = (BluetoothLEDevice)e.Parameter; mwGattService = selectedBtleDevice.GetGattService(GUID_METAWEAR_SERVICE); foreach (var characteristic in selectedBtleDevice.GetGattService(GUID_DEVICE_INFO_SERVICE).GetAllCharacteristics()) { var result = await characteristic.ReadValueAsync(); string value = result.Status == GattCommunicationStatus.Success ? System.Text.Encoding.UTF8.GetString(result.Value.ToArray(), 0, (int)result.Value.Length) : "N/A"; mwDeviceInfoChars.Add(characteristic.Uuid, value); outputListView.Items.Add(new ConsoleLine(ConsoleEntryType.INFO, DEVICE_INFO_NAMES[characteristic.Uuid] + ": " + value)); } mwNotifyChar = mwGattService.GetCharacteristics(METAWEAR_NOTIFY_CHARACTERISTIC).First(); await mwNotifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); mwNotifyChar.ValueChanged += new TypedEventHandler <Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic, GattValueChangedEventArgs>((Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic sender, GattValueChangedEventArgs obj) => { byte[] response = obj.CharacteristicValue.ToArray(); mbl_mw_connection_notify_char_changed(mwBoard, response, (byte)response.Length); }); }
public async Task <byte> GetBatteryStatus() { var batteryService = _nuimo.GetGattService(Constants.Services.Battery); var characteristic = batteryService.GetCharacteristics(Constants.Characteristics.Battery)[0]; var readResult = await characteristic.ReadValueAsync(); var value = readResult.Value.ToArray(); return(value[0]); }
/// <summary> /// Initialize the API /// </summary> /// <param name="initDelegate">C# Delegate wrapping the callback for <see cref="mbl_mw_metawearboard_initialize(IntPtr, FnVoid)"/></param> public async void Initialize(FnVoid initDelegate) { if (notifyChar == null) { notifyChar = btleDevice.GetGattService(GattCharGuid.METAWEAR_NOTIFY_CHAR.serviceGuid).GetCharacteristics(GattCharGuid.METAWEAR_NOTIFY_CHAR.guid).FirstOrDefault(); notifyChar.ValueChanged += notifyHandler; await notifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } this.initDelegate = initDelegate; mbl_mw_metawearboard_initialize(cppBoard, this.initDelegate); }
private async void handleAdvertisement(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { if (_handlingAdvertisement) { Debug.WriteLine("wtf"); } _handlingAdvertisement = true; StringBuilder sb = new StringBuilder(); sb.Append(eventArgs.RawSignalStrengthInDBm.ToString()); sb.Append(" "); sb.Append(eventArgs.AdvertisementType.ToString()); sb.Append("\n\t"); var sections = eventArgs.Advertisement.DataSections; for (int i = 0; i < sections.Count; ++i) { sb.Append(sections[i].DataType.ToString("X2")); sb.Append(": "); sb.Append(bufferToString(sections[i].Data).Replace("-", " ")); sb.Append(" "); } Debug.WriteLine(sb.ToString()); _handlingAdvertisement = false; if (_devicing) { return; } _devicing = true; var wantExceptions = true; wantExceptions = false;//comment to get exceptions! if (wantExceptions) { BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress); Debug.WriteLine("created device"); var service = device.GetGattService(new Guid("1800")); if (service == null) { _devicing = false; return; } var characteristics = service.GetCharacteristics(new Guid("2a00")); if (characteristics == null) { _devicing = false; return; } Debug.WriteLine("got characteristic"); foreach (var characteristic in characteristics) { var value = await characteristic.ReadValueAsync(); Debug.WriteLine("got device name:"); Debug.WriteLine(bufferToString(value.Value)); } } _devicing = false; }
private async void SetupScalesStream(BluetoothLEDevice device) { try { var service = device.GetGattService(_scalesServiceGuid); var weightCharac = service.GetAllCharacteristics().Single(c => c.Uuid == _weightGuid); await weightCharac.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); weightCharac.ValueChanged += (sender, args) => { Debug.WriteLine(args.CharacteristicValue); double weight = (BitConverter.ToInt32(args.CharacteristicValue.ToArray().Reverse().ToArray(), 0) / 10.0) - 500; _scalesStreamer.Send(new ScalesData { DeviceId = 1, Timestamp = DateTime.Now, Weight = (float)weight }); }; } catch (Exception e) { Debug.WriteLine($"Unable to connect to Scales: {e}"); } }
public async Task <bool> Connect(ulong deviceAddress) { this.Address = deviceAddress; device = await BluetoothLEDevice.FromBluetoothAddressAsync(this.Address); if (device is null) { return(false); } service = device.GetGattService(MuseGuid.PRIMARY_SERVICE); if (service is null) { return(false); } ch_control = service.GetCharacteristic(MuseGuid.CONTROL); ch_accelerometer = service.GetCharacteristic(MuseGuid.ACELEROMETER); ch_gyroscope = service.GetCharacteristic(MuseGuid.GYROSCOPE); ch_telemetry = service.GetCharacteristic(MuseGuid.TELEMETRY); ch_EEG_TP9 = service.GetCharacteristic(MuseGuid.EEG_TP9); ch_EEG_AF7 = service.GetCharacteristic(MuseGuid.EEG_AF7); ch_EEG_AF8 = service.GetCharacteristic(MuseGuid.EEG_AF8); ch_EEG_TP10 = service.GetCharacteristic(MuseGuid.EEG_TP10); ch_EEG_AUX = service.GetCharacteristic(MuseGuid.EEG_AUX); Connected = true; return(true); }
/// <summary> /// The entry point of a background task. /// </summary> /// <param name="taskInstance">The current background task instance.</param> public async void Run(IBackgroundTaskInstance taskInstance) { backgroundTaskInstance = taskInstance; // Get the details of the trigger var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails; if (details != null) { // If the background watcher stopped unexpectedly, an error will be available here. var error = details.Error; if (error == BluetoothError.Success) { // The Advertisements property is a list of all advertisement events received // since the last task triggered. The list of advertisements here might be valid even if // the Error status is not Success since advertisements are stored until this task is triggered IReadOnlyList <BluetoothLEAdvertisementReceivedEventArgs> advertisements = details.Advertisements; // The signal strength filter configuration of the trigger is returned such that further // processing can be performed here using these values if necessary. They are read-only here. var rssiFilter = details.SignalStrengthFilter; // Make sure we have advertisements to work with if (advertisements.Count == 0) { return; } // Grab the first advertisement var eventArg = advertisements[0]; if (eventArg.RawSignalStrengthInDBm > WriteCharacteristicMinRSSI) { // Get a deferral so we can use the await operator without the background task returning and closing the thread BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); // Get a connection to the device and get the service that we're looking for BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArg.BluetoothAddress); // Get the service and characteristic we're looking for var service = device.GetGattService(IoServiceUuid); var characteristic = service.GetCharacteristics(OutputCommandCharacteristicGuid)[0]; // Write to the motor characteristic telling it to spin GattCommunicationStatus status = await this.writeToCharacteristic(characteristic); // Wait a couple seconds before we disconnect so we can see the motor spin await Task.Delay(TimeSpan.FromSeconds(MotorSpinSeconds)); // Disconnect from the device so the motor stops device.Dispose(); // Let the system know that we've finished the background task deferral.Complete(); } } } }
public async void Connect() { ClearBluetoothLEDevice(); try { // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(BluetoothLEDeviceId); bluetoothLeDevice.ConnectionStatusChanged += BluetoothLeDevice_ConnectionStatusChanged; } catch (Exception ex) when((uint)ex.HResult == 0x800710df) { // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on. } if (bluetoothLeDevice != null) { Guid ancsUuid = new Guid("7905F431-B5CE-4E99-A40F-4B1E122D00D0"); try { GattService = bluetoothLeDevice.GetGattService(ancsUuid); } catch (Exception ex) { throw new Exception("Apple Notification Center Service not found."); } if (GattService == null) { throw new Exception("Apple Notification Center Service not found."); } else { Guid notificationSourceUuid = new Guid("9FBF120D-6301-42D9-8C58-25E699A21DBD"); Guid controlPointUuid = new Guid("69D1D8F3-45E1-49A8-9821-9BBDFDAAD9D9"); Guid dataSourceUuid = new Guid("22EAC6E9-24D6-4BB5-BE44-B36ACE7C7BFB"); try { ControlPoint = new ControlPoint(GattService.GetCharacteristics(controlPointUuid).First()); DataSource = new DataSource(GattService.GetCharacteristics(dataSourceUuid).First()); NotificationSource = new NotificationSource(GattService.GetCharacteristics(notificationSourceUuid).First()); } catch (Exception ex) { throw new Exception(ex.Message); } } } else { ClearBluetoothLEDevice(); throw new Exception("Failed to connect to device."); } }
private void AddCharacteristics(Guid serviceGuid, IEnumerable <Guid> characteristicGuids) { var service = _bluetoothLeDevice.GetGattService(serviceGuid); foreach (var characteristicGuid in characteristicGuids) { _gattCharacteristicsForGuid.Add(characteristicGuid, service.GetCharacteristics(characteristicGuid)[0]); } }
/// <summary> /// Called when connected. /// </summary> private async Task OnConnect() { deviceService = device.GetGattService(Guid.Parse(UuidService)); readCharacteristic = await GetCharacteristic(deviceService, Guid.Parse(UuidRead)); writeCharacteristic = await GetCharacteristic(deviceService, Guid.Parse(UuidWrite)); readCharacteristic.ValueChanged += ReadCharacteristic_ValueChanged; await readCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); }
//MOSTRA LE CARATTERISTICHE DEL SERVIZIO HR private async void servizi() { GattDeviceService HRservice = BluetoothDevice.GetGattService(HRserviceGuid); GattCharacteristicsResult HRcharacteristics = await HRservice.GetCharacteristicsAsync(); foreach (GattCharacteristic caratteristica in HRcharacteristics.Characteristics.Where(caratteristica => caratteristica.AttributeHandle == 36)) //13 { HRreader = caratteristica; OutputList.Items.Insert(0, "Servizio HR trovato in" + HRreader.CharacteristicProperties.ToString()); } }
private async static Task <GattDeviceService> waitConnection(AnkiBLE.anki_vehicle vehicle) { BluetoothLEDevice bluetoothLeDevice = null; GattDeviceService service = null; bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(vehicle.mac_address); while (bluetoothLeDevice.ConnectionStatus != BluetoothConnectionStatus.Connected) { throw new Exception("Not connected!"); } service = bluetoothLeDevice.GetGattService(Guid.Parse("be15beef-6186-407e-8381-0bd89c4d8df4")); return(service); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); selectedDevice = e.Parameter as BluetoothLEDevice; notifyChar = selectedDevice.GetGattService(GattCharGuid.METAWEAR_NOTIFY_CHAR.serviceGuid).GetCharacteristics(GattCharGuid.METAWEAR_NOTIFY_CHAR.guid).FirstOrDefault(); await notifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); notifyChar.ValueChanged += new TypedEventHandler <Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic, GattValueChangedEventArgs>( (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic sender, GattValueChangedEventArgs obj) => { byte[] response = obj.CharacteristicValue.ToArray(); mbl_mw_connection_notify_char_changed(board, response, (byte)response.Length); }); board = mbl_mw_metawearboard_create(ref btleConn); mbl_mw_metawearboard_initialize(board, initDelegate); }
/// <summary> /// Initialize the API /// </summary> /// <returns>Status value from calling <see cref="mbl_mw_metawearboard_initialize(IntPtr, Fn_IntPtr_Int)"/></returns> public async Task <int> Initialize() { if (notifyChar == null) { notifyChar = btleDevice.GetGattService(GattCharGuid.METAWEAR_NOTIFY_CHAR.serviceGuid).GetCharacteristics(GattCharGuid.METAWEAR_NOTIFY_CHAR.guid).FirstOrDefault(); notifyChar.ValueChanged += notifyHandler; await notifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } initTaskSource = new TaskCompletionSource <int>(); initDelegate = new Fn_IntPtr_Int((caller, status) => { initTaskSource.SetResult(status); }); mbl_mw_metawearboard_initialize(cppBoard, initDelegate); return(await initTaskSource.Task); }
public void ConnectGamepad(BluetoothLEDevice device) { if (pairedGamepad == null || pairedGamepad.ConnectionStatus == BluetoothConnectionStatus.Disconnected) { try { GattDeviceService service = device.GetGattService(new Guid("0000180f-0000-1000-8000-00805f9b34fb")); GattCharacteristic characteristic = service.GetCharacteristics(new Guid("00002a19-0000-1000-8000-00805f9b34fb")).First(); if (service != null && characteristic != null) { pairedGamepad = device; batteryCharacteristic = characteristic; } } catch { } } }
public NotificationConsumer(BluetoothLEDevice device) { try { DeviceService = device.GetGattService(new Guid("7905F431-B5CE-4E99-A40F-4B1E122D00D0")); } catch (Exception) { } if (DeviceService == null) { // TODO: Build a custom exception throw new Exception("Apple Notification Center Service not found on given device."); } LoadBaseCharacteristics(); }
async private void FindBleController() { int count = 0; foreach (var device in await DeviceInformation.FindAllAsync()) { try { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(device.Id); if (bleDevice != null && bleDevice.Appearance.SubCategory == BluetoothLEAppearanceSubcategories.Gamepad)//get the gamepads { GattDeviceService service = bleDevice.GetGattService(new Guid("0000180f-0000-1000-8000-00805f9b34fb")); GattCharacteristic characteristic = service.GetCharacteristics(new Guid("00002a19-0000-1000-8000-00805f9b34fb")).First(); if (service != null && characteristic != null)//get the gamepads with battery status { bleDevice.ConnectionStatusChanged += ConnectionStatusChanged; count++; if (bleDevice.ConnectionStatus == BluetoothConnectionStatus.Connected) { ConnectGamepad(bleDevice); } } } } catch { } } if (count == 0) { notifyIcon.Icon = Properties.Resources.iconE; notifyIcon.Text = "XBatteryStatus: No paired controller with battery service found"; } else { Update(); } }
private static async Task <bool> Connect() { int count = 0; foreach (var device in await DeviceInformation.FindAllAsync()) { try { bleDevice = await BluetoothLEDevice.FromIdAsync(device.Id); if (bleDevice != null && bleDevice.Appearance.Category == BluetoothLEAppearanceCategories.HeartRate) { GattDeviceService service = bleDevice.GetGattService(new Guid("0000180d-0000-1000-8000-00805f9b34fb")); characteristic = service.GetCharacteristics(new Guid("00002a37-0000-1000-8000-00805f9b34fb")).First(); if (service != null && characteristic != null) { Console.WriteLine("Found Paired Heart Rate Device"); GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { bleDevice.ConnectionStatusChanged += ConnectionStatusChanged; characteristic.ValueChanged += ValueChanged; count++; Console.WriteLine("Subscribed to Heart Rate"); break; } } } } catch (Exception e) { //Console.WriteLine(e.Message); } } return(count > 0); }
private void getCharacterstics(string id) { Guid g = new Guid(id); currentSvc = bluetoothLeDevice.GetGattService(g); IReadOnlyList <GattCharacteristic> chrs = currentSvc.GetAllCharacteristics(); listView3.Clear(); listView3.Columns.Add("Characterstic UUID", 150); listView3.Columns.Add("Description", 150); foreach (GattCharacteristic c in chrs) { string[] arr = new string[2]; ListViewItem itm; //add items to ListView arr[0] = c.Uuid.ToString(); arr[1] = c.CharacteristicProperties.ToString(); itm = new ListViewItem(arr); listView3.Items.Add(itm); } //do nothing }
async void ConnectDevice(ulong add) { // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(add); //System.Threading.Thread.Sleep(5000); isConnected = true; // BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(ble.DeviceId); //Console.WriteLine("Device Added"); //Console.ReadLine(); //GattDeviceServicesResult result = await bluetoothLeDevice; //var prslt = await bluetoothLeDevice.DeviceInformation.Pairing.PairAsync(); //System.Threading.Thread.Sleep(7000); //try 5 second lay. Guid serUuid = new Guid("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); Guid charUuid = new Guid("beb5483e-36e1-4688-b7f5-ea07361b26a8"); //IReadOnlyList<GattDeviceService> svc = bluetoothLeDevice.GattServices; GattDeviceService service = bluetoothLeDevice.GetGattService(serUuid); //Console.ReadLine(); //Console.WriteLine(String.Format(" Device Name: {0}", bluetoothLeDevice.DeviceInformation.Name)); //Console.WriteLine("Getting Characterstics"); //IReadOnlyList<GattCharacteristic> chars = service.GetAllCharacteristics(); GattCharacteristic selectedCharacteristic = service.GetCharacteristics(charUuid).FirstOrDefault(); //Console.WriteLine(chars.FirstOrDefault().Uuid); // Console.WriteLine(svc.FirstOrDefault().Uuid); // //IReadOnlyList<GattCharacteristic> chrs = svc.GetAllCharacteristics(); /* * if (result.Status == GattCommunicationStatus.Success) * { * var services = result.Services; * * // ... * }*/ //***** WRITE DATA ******* var writer = new DataWriter(); // WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle writer.WriteByte(0x78); GattCommunicationStatus result1 = await selectedCharacteristic.WriteValueAsync(writer.DetachBuffer()); if (result1 == GattCommunicationStatus.Success) { Console.WriteLine("Written Successfully"); } //***** READING DATA ******** GattReadResult result = await selectedCharacteristic.ReadValueAsync(); if (result.Status == GattCommunicationStatus.Success) { var reader = DataReader.FromBuffer(result.Value); byte[] input = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(input); Console.WriteLine(Encoding.UTF8.GetString(input)); // Utilize the data as needed } // ... }
public async void CheckArgs(BluetoothLEAdvertisementReceivedEventArgs args) { Console.WriteLine("★アドバタイズパケットスキャン"); bool find = false; { var bleServiceUUIDs = args.Advertisement.ServiceUuids; foreach (var uuidone in bleServiceUUIDs) { if (uuidone == Common.CreateFullUUID(SERVICE_UUID)) { // 発見 find = true; break; } } } if (find) { try { Console.WriteLine($"Service Find!"); // スキャンStop this.advWatcher.Stop(); BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); this.Service = dev.GetGattService(Common.CreateFullUUID(SERVICE_UUID)); // for log { Console.WriteLine($"Service.Uuid...{Service.Uuid}"); Console.WriteLine($"Servicev.DeviceId...{Service.DeviceId}"); Console.WriteLine($"Servicev.Device.Name...{Service.Device.Name}"); var characteristics = Service.GetAllCharacteristics(); foreach (var ch in characteristics) { Console.WriteLine($"CharacteristicUUID...{ch.Uuid}"); Console.WriteLine($"CharacteristicProperties...{ch.CharacteristicProperties}"); } } // Blood Pressure Measurement // Requirement = M , Mandatory Properties = Indicate { var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A35")); if (characteristics.Count > 0) { this.Characteristic_Blood_Pressure_Measurement = characteristics.First(); if (this.Characteristic_Blood_Pressure_Measurement == null) { Console.WriteLine("Characteristicに接続できない..."); } else { if (this.Characteristic_Blood_Pressure_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate)) { // イベントハンドラ追加 this.Characteristic_Blood_Pressure_Measurement.ValueChanged += characteristicChanged_Blood_Pressure_Measurement; // これで有効になる await this.Characteristic_Blood_Pressure_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate); } } } } // Blood Pressure Feature // Requirement = M , Mandatory Properties = Read { var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A49")); if (characteristics.Count > 0) { var chara = characteristics.First(); if (chara == null) { Console.WriteLine("Characteristicに接続できない..."); } else { if (chara.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read)) { GattReadResult result = await chara.ReadValueAsync(); if (result.Status == GattCommunicationStatus.Success) { var reader = Windows.Storage.Streams.DataReader.FromBuffer(result.Value); byte[] input = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(input); var tmp = BitConverter.ToString(input); Console.WriteLine($"Blood Pressure Feature...{tmp}"); } } } } } } catch (Exception ex) { Console.WriteLine($"Exception...{ex.Message})"); } } else { Console.WriteLine($"..."); } }
async static Task BLE() { GattReadResult result = null; BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(000000000002); // Get the service containing our characteristic Guid ServiceId = new Guid("6D617931-3733-3500-0000-000000000000"); GattDeviceService services = device.GetGattService(ServiceId); string preTimeData = ""; string curTimeData = ""; // This block assumes multiple characteristics and polls from each separate characteristic containing the needed data while (true) { foreach (var gc in services.GetAllCharacteristics()) { string output = ""; if (gc.Uuid != ServiceId) { result = await gc.ReadValueAsync(BluetoothCacheMode.Uncached); var dataReader = DataReader.FromBuffer(result.Value); output = dataReader.ReadString(result.Value.Length); //Console.WriteLine(output); } switch (gc.Uuid.ToString()) { // AccelX AccelY AccelZ case "01100000-0000-0000-0000-000000000000": string[] AccelValues = output.Split(' '); accel_x = AccelValues[0]; accel_y = AccelValues[1]; accel_z = AccelValues[2]; break; // GyroX GyroY GyroZ case "02100000-0000-0000-0000-000000000000": string[] GyroValues = output.Split(' '); gyro_x = GyroValues[0]; gyro_y = GyroValues[1]; gyro_z = GyroValues[2]; break; // MagX MagY MagZ case "03100000-0000-0000-0000-000000000000": string[] MagValues = output.Split(' '); mag_x = MagValues[0]; mag_y = MagValues[1]; mag_z = MagValues[2]; break; // JoystickX JoystickY JoystickZ Buttons case "04100000-0000-0000-0000-000000000000": string[] JoyButValues = output.Split(' '); joy_x = JoyButValues[0]; joy_y = JoyButValues[1]; buttons = JoyButValues[2]; break; // Time case "05100000-0000-0000-0000-000000000000": curTimeData = output; if (preTimeData.Equals(curTimeData)) { dataChanged = false; } else { dataChanged = true; } preTimeData = curTimeData; time = int.Parse(output, System.Globalization.NumberStyles.HexNumber).ToString(); break; default: break; } } } }
private async Task DisplayBluetooth(NameDevice knownDevice, DeviceInformationWrapper di, BluetoothLEDevice ble) { var jsonFormat = Newtonsoft.Json.Formatting.Indented; var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings() { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ContractResolver = IgnoreEmptyEnumerableResolver.Instance, }; var wireAllDevices = new NameAllBleDevices(); WireDevice = new NameDevice(); WireDevice.Name = di.di.Name; WireDevice.Details += $"Id:{di.di.Id}\nCanPair:{di.di.Pairing.CanPair} IsPaired:{di.di.Pairing.IsPaired}"; wireAllDevices.AllDevices.Add(WireDevice); WireDevice.ClassModifiers = knownDevice.ClassModifiers; WireDevice.ClassName = knownDevice.ClassName; WireDevice.Description = knownDevice.Description; uiRawData.Text = Newtonsoft.Json.JsonConvert.SerializeObject(WireDevice, jsonFormat); string raw = null; if (ble == null) { // Happens if another program is trying to use the device! raw = $"BLE: ERROR: Another app is using this device.\n"; } else { // TODO: remove this code which is only here while I investigate the WESCALE scale #if NEVER_EVER_DEFINED { // WESCALE: no gatt services var services = ble.GattServices; var count = services.Count; var devacc = ble.DeviceAccessInformation; var devaccstatus = devacc.CurrentStatus; foreach (var service in services) { var chars = service.GetAllCharacteristics(); } try { var guid = Guid.Parse("0000fff0-0000-1000-8000-00805f9b34fb"); var request = await ble.RequestAccessAsync(); var allservice = await ble.GetGattServicesForUuidAsync(guid); var servicefff0 = ble.GetGattService(guid); var charsfff0 = servicefff0.GetAllCharacteristics(); var countfff0 = charsfff0.Count; foreach (var ch in charsfff0) { ; } } catch (Exception ex) { ; } } #endif var result = await ble.GetGattServicesAsync(); if (result.Status != GattCommunicationStatus.Success) { raw += GetStatusString(result.Status, result.ProtocolError); } else { var header = new BleDeviceHeaderControl(); await header.InitAsync(ble); int serviceCount = 0; foreach (var service in result.Services) { await header.AddServiceAsync(ble, service); var shouldDisplay = ServiceShouldBeEdited(service); var defaultService = knownDevice.GetService(service.Uuid.ToString("D")); var wireService = new NameService(service, defaultService, serviceCount++); WireDevice.Services.Add(wireService); try { var cresult = await service.GetCharacteristicsAsync(); if (cresult.Status != GattCommunicationStatus.Success) { raw += GetStatusString(cresult.Status, cresult.ProtocolError); } else { var characteristicCount = 0; foreach (var characteristic in cresult.Characteristics) { //The descriptors don't seem to be actually interesting. it's how we read and write. var descriptorStatus = await characteristic.GetDescriptorsAsync(); if (descriptorStatus.Status == GattCommunicationStatus.Success) { foreach (var descriptor in descriptorStatus.Descriptors) { ; } } var defaultCharacteristic = defaultService?.GetChacteristic(characteristic.Uuid.ToString("D")); var wireCharacteristic = new NameCharacteristic(characteristic, defaultCharacteristic, characteristicCount++); wireService.Characteristics.Add(wireCharacteristic); if (wireCharacteristic.Suppress) { continue; // don't show a UI for a supressed characteristic. } // // Here are each of the editor children items // var edit = new BleCharacteristicControl(knownDevice, service, characteristic); uiEditor.Children.Add(edit); var dc = DeviceCharacteristic.Create(characteristic); //NOTE: does any device have a presentation format? foreach (var format in characteristic.PresentationFormats) { raw += $" Fmt: Description:{format.Description} Namespace:{format.Namespace} Type:{format.FormatType} Unit: {format.Unit} Exp:{format.Exponent}\n"; } try { if (wireCharacteristic.IsRead) { var vresult = await characteristic.ReadValueAsync(); if (vresult.Status != GattCommunicationStatus.Success) { raw += GetStatusString(vresult.Status, vresult.ProtocolError); } else { var dt = BluetoothLEStandardServices.GetDisplayInfo(service, characteristic); var hexResults = dt.AsString(vresult.Value); wireCharacteristic.ExampleData.Add(hexResults); // And add as a converted value var NC = BleNames.Get(knownDevice, service, characteristic); var decode = NC?.Type; if (decode != null && !decode.StartsWith("BYTES|HEX")) { var decoded = ValueParser.Parse(vresult.Value, decode); wireCharacteristic.ExampleData.Add(decoded.UserString); } } } } catch (Exception e) { raw += $" Exception reading value: {e.HResult} {e.Message}\n"; } // Update the UI with the latest discovery // Later: or not. The raw data isn't super useful. //uiRawData.Text = Newtonsoft.Json.JsonConvert.SerializeObject(WireDevice, jsonFormat); } } } catch (Exception e) { raw += $" Exception reading characteristic: {e.HResult} {e.Message}\n"; } } } } JsonAsList = Newtonsoft.Json.JsonConvert.SerializeObject(wireAllDevices, jsonFormat, jsonSettings); JsonAsSingle = Newtonsoft.Json.JsonConvert.SerializeObject(WireDevice, jsonFormat, jsonSettings); uiProgress.IsActive = false; uiRawData.Text += raw; return; }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { selectedBtleDevice = (BluetoothLEDevice) e.Parameter; mwGattService = selectedBtleDevice.GetGattService(Gatt.METAWEAR_SERVICE); foreach(var characteristic in selectedBtleDevice.GetGattService(DEVICE_INFO_SERVICE).GetAllCharacteristics()) { var result = await characteristic.ReadValueAsync(); string value = result.Status == GattCommunicationStatus.Success ? System.Text.Encoding.UTF8.GetString(result.Value.ToArray(), 0, (int)result.Value.Length) : "N/A"; mwDeviceInfoChars.Add(characteristic.Uuid, value); outputListView.Items.Add(new ConsoleLine(ConsoleEntryType.INFO, DEVICE_INFO_NAMES[characteristic.Uuid] + ": " + value)); } mwNotifyChar = mwGattService.GetCharacteristics(Gatt.METAWEAR_NOTIFY_CHARACTERISTIC).First(); await mwNotifyChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); mwNotifyChar.ValueChanged += new TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs>((GattCharacteristic sender, GattValueChangedEventArgs obj) => { byte[] response = obj.CharacteristicValue.ToArray(); MetaWearBoard.HandleResponse(mwBoard, response, (byte)response.Length); }); }
public async void CheckArgs(BluetoothLEAdvertisementReceivedEventArgs args) { Console.WriteLine("★アドバタイズパケットスキャン"); // Health Thermometerサービスを検索 bool find = false; { var bleServiceUUIDs = args.Advertisement.ServiceUuids; foreach (var uuidone in bleServiceUUIDs) { if (uuidone == Common.CreateFullUUID(SERVICE_UUID)) { // 発見 find = true; break; } } } if (find) { try { Console.WriteLine($"Service Find!"); // スキャンStop this.advWatcher.Stop(); BluetoothLEDevice dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); this.Service = dev.GetGattService(Common.CreateFullUUID(SERVICE_UUID)); // for log { Console.WriteLine($"Service.Uuid...{Service.Uuid}"); Console.WriteLine($"Servicev.DeviceId...{Service.DeviceId}"); Console.WriteLine($"Servicev.Device.Name...{Service.Device.Name}"); var characteristics = Service.GetAllCharacteristics(); foreach (var ch in characteristics) { Console.WriteLine($"Characteristic..."); Console.WriteLine($"...AttributeHandle=0x{ch.AttributeHandle.ToString("X2")}"); Console.WriteLine($"...Properties={ch.CharacteristicProperties}"); Console.WriteLine($"...ProtectionLevel={ch.ProtectionLevel}"); Console.WriteLine($"...UUID={ch.Uuid}"); } } // Temperature Measurement // Requirement = M , Mandatory Properties = Indicate { var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A1C")); if (characteristics.Count > 0) { this.Characteristic_Temperature_Measurement = characteristics.First(); if (this.Characteristic_Temperature_Measurement == null) { Console.WriteLine("Characteristicに接続できない..."); } else { if (this.Characteristic_Temperature_Measurement.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate)) { // イベントハンドラ追加 this.Characteristic_Temperature_Measurement.ValueChanged += characteristicChanged_Temperature_Measurement; // これで有効になる await this.Characteristic_Temperature_Measurement.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate); } } } } // Intermediate Temperature:Notify // Requirement = O , Mandatory Properties = Notify { var characteristics = Service.GetCharacteristics(Common.CreateFullUUID("2A1E")); if (characteristics.Count > 0) { this.Characteristic_Intermediate_Temperature = characteristics.First(); if (this.Characteristic_Intermediate_Temperature == null) { Console.WriteLine("Characteristicに接続できない..."); } else { if (this.Characteristic_Intermediate_Temperature.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { this.Characteristic_Intermediate_Temperature.ValueChanged += characteristicChanged_Intermediate_Temperature; await this.Characteristic_Intermediate_Temperature.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } } } } } catch (Exception ex) { Console.WriteLine($"Exception...{ex.Message})"); } } else { Console.WriteLine($"..."); } }