private string getAdvertisementInfo(BLEAdvertisementInfo bleAdvArg) { return(string.Format("\n[{0}] [{1}]: Rssi={2}dBm, localName={3}, address=[0x{4}], manufacturerData=[{5}]", bleAdvArg.Timestamp.ToString("hh\\:mm\\:ss\\.fff"), bleAdvArg.AdvertisementType.ToString(), bleAdvArg.RawSignalStrengthInDBm.ToString(), bleAdvArg.Advertisement.LocalName, bleAdvArg.BluetoothAddress.ToString("X"), bleAdvArg.Advertisement.ManufacturerData[0])); }
private async void OnBleAdvertisementUpdated(BleAdvertisementWatcher sender, DeviceWatchEvent eventCode, BLEAdvertisementInfo bleAdvertisementInfo) { DeviceInformation btDeviceInformation = await BluetoothDevices.CreateDeviceInformation(bleAdvertisementInfo.ToBtAddressString(), AddressType.Bluetooth); DeviceInformation bleDeviceInformation = await BluetoothDevices.CreateDeviceInformation(bleAdvertisementInfo.ToBtAddressString(), AddressType.BLE); if (!App.sUserManager.IsSingnIn()) { // FIXME: SERVICE CODE to configuration if (bleAdvertisementInfo.Advertisement.ManufacturerData[0].Data.Length > 5) { // ignore, because it has user Key. Log.D(string.Format($"Other User's Device Found: {bleAdvertisementInfo.Advertisement.ManufacturerData[0].Data}")); return; } } if (eventCode == DeviceWatchEvent.Added) { Log.D(string.Format($"New BLE Advertisement Found: {bleAdvertisementInfo.ToBtAddressString()}")); AddNearByEarbuds(bleDeviceInformation.Id); AddNearByBtDevice(bleDeviceInformation.Id, btDeviceInformation.Name); } else if (eventCode == DeviceWatchEvent.Removed) { Log.D(string.Format($"BLE Advertisement Removed: {bleAdvertisementInfo.ToBtAddressString()}")); Earbuds removeEarBuds = RemoveNearByEarbuds(bleDeviceInformation.Id); if (removeEarBuds != null) { RemoveNearByBtDevice(bleDeviceInformation.Id, btDeviceInformation.Name); } } }
/// <summary> /// The entry point of a background task. /// </summary> /// <param name="taskInstance">The current background task instance.</param> public void Run(IBackgroundTaskInstance taskInstance) { backgroundTaskInstance = taskInstance; 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; // 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 List <BLEAdvertisementInfo> jsonInput = new List <BLEAdvertisementInfo>(); 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; // In this example, the background task simply constructs a message communicated // to the App. For more interesting applications, a notification can be sent from here instead. string eventMessage = ""; eventMessage += string.Format("ErrorStatus: {0}, EventCount: {1}, HighDBm: {2}, LowDBm: {3}, Timeout: {4}, Sampling: {5}", error.ToString(), advertisements.Count.ToString(), rssiFilter.InRangeThresholdInDBm.ToString(), rssiFilter.OutOfRangeThresholdInDBm.ToString(), rssiFilter.OutOfRangeTimeout.GetValueOrDefault().TotalMilliseconds.ToString(), rssiFilter.SamplingInterval.GetValueOrDefault().TotalMilliseconds.ToString()); // Advertisements can contain multiple events that were aggregated, each represented by // a BluetoothLEAdvertisementReceivedEventArgs object. foreach (var eventArgs in advertisements) { // Check if there are any manufacturer-specific sections. // If there is, print the raw data of the first manufacturer section (if there are multiple). string manufacturerDataString = ""; var manufacturerSections = eventArgs.Advertisement.ManufacturerData; if (manufacturerSections.Count > 0) { var manufacturerData = manufacturerSections[0]; var data = new byte[manufacturerData.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerData.Data)) { reader.ReadBytes(data); } // Print the company ID + the raw data in hex format. manufacturerDataString = string.Format("0x{0}: {1}", manufacturerData.CompanyId.ToString("X"), BitConverter.ToString(data)); } eventMessage += string.Format("\n[{0}] [{1}]: Rssi={2}dBm, localName={3}, address=[0x{4}], manufacturerData=[{5}]", eventArgs.Timestamp.ToString("hh\\:mm\\:ss\\.fff"), eventArgs.AdvertisementType.ToString(), eventArgs.RawSignalStrengthInDBm.ToString(), eventArgs.Advertisement.LocalName, eventArgs.BluetoothAddress.ToString("X"), manufacturerDataString); BLEAdvertisementInfo arg = new BLEAdvertisementInfo(eventArgs); jsonInput.Add(arg); } // Store the message in a local settings indexed by this task's name so that the foreground App // can display this message. ApplicationData.Current.LocalSettings.Values[taskInstance.Task.Name] = /*eventMessage + "\n" +*/ JsonConvert.SerializeObject(jsonInput, Formatting.Indented); } }
// BLE Advertisement Handler private void OnBleAdvertisementUpdated(BleAdvertisementWatcher sender, DeviceWatchEvent eventCode, BLEAdvertisementInfo bleAdvertisementInfo) { if (userKey == null || userKey.Length == 0) { // FIXME: SERVICE CODE to configuration if (bleAdvertisementInfo.Advertisement.ManufacturerData[0].Data.Length > 5) { // ignore, because it has user Key. return; } } if (eventCode == DeviceWatchEvent.Added) { Log.D($"New BLE Advertisement Found: {bleAdvertisementInfo.ToBtAddressString()}"); ValueSet newBleDeviceMessage = new ValueSet { { "opcode", "ble_device" }, { "status", "added" }, { "name", bleAdvertisementInfo.Advertisement.LocalName }, { "id", $"Bluetooth#Bluetooth{localBtAddress}-{bleAdvertisementInfo.ToBtAddressString()}" } }; systrayApplicationServiceConnection.SendMessageAsync(newBleDeviceMessage); } else if (eventCode == DeviceWatchEvent.Removed) { Log.D($"BLE Advertisement Removed: {bleAdvertisementInfo.ToBtAddressString()}"); ValueSet removeBleDeviceMessage = new ValueSet { { "opcode", "ble_device" }, { "status", "removed" }, { "name", bleAdvertisementInfo.Advertisement.LocalName }, { "id", $"Bluetooth#Bluetooth{localBtAddress}-{bleAdvertisementInfo.ToBtAddressString()}" } }; systrayApplicationServiceConnection.SendMessageAsync(removeBleDeviceMessage); } // Propergate Event to Earbuds Menu string deviceId = $"Bluetooth#Bluetooth{localBtAddress}-{bleAdvertisementInfo.ToBtAddressString()}"; foreach (EarbudsMenuItem earbudsMenuItem in PairedDeviceMenuItems) { if (BluetoothDevices.EqualDevice(deviceId, earbudsMenuItem.BtID)) { earbudsMenuItem.HandleBleAdvertisement(eventCode); break; } } }