Decompiled source of RumbleHeartRateDisplay v1.0.2

Mods/RumbleHeartRateDisplay.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Il2CppTMPro;
using MelonLoader;
using Microsoft.CodeAnalysis;
using RumbleHeartRateDisplay;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "RumbleHeartRateDisplay", "1.0.0", "Roaby", null)]
[assembly: MelonGame("Buckethead Entertainment", "RUMBLE")]
[assembly: MelonColor(50, 168, 164, 255)]
[assembly: MelonAuthorColor(50, 168, 164, 255)]
[assembly: VerifyLoaderVersion(0, 6, 6, true)]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("RumbleHeartRateDisplay")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+fe0f1af65a872ca01532d9f2effae243ef41e0be")]
[assembly: AssemblyProduct("RumbleHeartRateDisplay")]
[assembly: AssemblyTitle("RumbleHeartRateDisplay")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace RumbleHeartRateDisplay
{
	internal class BuildInfo
	{
		public const string ModName = "RumbleHeartRateDisplay";

		public const string Author = "Roaby";

		public const string ModVersion = "1.0.0";
	}
	public class Core : MelonMod
	{
		private HeartRateReceiver _heartRateReceiver;

		private string settingsFilePath = "UserData\\RumbleHeartHud.xml";

		public static Instance Logger { get; private set; }

		public override void OnInitializeMelon()
		{
			Logger = ((MelonBase)this).LoggerInstance;
			((MelonBase)this).LoggerInstance.Msg("RumbleHeartRateDisplay: Initialized.");
			try
			{
				Settings.FromXmlFile(settingsFilePath);
				((MelonBase)this).LoggerInstance.Msg("Loaded settings from file.");
			}
			catch
			{
				Settings.Initialize();
				((MelonBase)this).LoggerInstance.Msg("Unable to load settings. Using defaults.");
			}
			_heartRateReceiver = new HeartRateReceiver();
			Task.Run(() => _heartRateReceiver.StartStreamingHeartRate());
		}

		public override void OnUpdate()
		{
			if (!ModResources.Initialized)
			{
				ModResources.LoadResources();
			}
			if (!HeartHud.Initialized)
			{
				HeartHud.Initialize();
			}
			if (Input.GetKeyDown((KeyCode)104))
			{
				Task.Run(delegate
				{
					HeartRateReceiver.RestartBluetoothHandler(_heartRateReceiver);
				});
			}
		}

		public override void OnApplicationQuit()
		{
			MelonLogger.Msg("Game is exiting...");
			HeartRateReceiver.StopBluetoothHandler();
		}
	}
	internal class HeartHud
	{
		private static GameObject uiContainer = null;

		private static Canvas canvas = null;

		private static string heartSpeedParamName = "BeatSpeedMultiplier";

		private static bool initialized = false;

		private static readonly int playerControllerLayerMask = LayerMask.NameToLayer("PlayerController");

		private const int playerControllerLayer = 8388608;

		private static HeartUiElements uiElements = new HeartUiElements();

		public static bool Initialized => initialized;

		public static void Initialize()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			if (!initialized)
			{
				uiContainer = new GameObject();
				((Object)uiContainer).name = "HeartRateHud_Canvas";
				uiContainer.AddComponent<Canvas>();
				canvas = uiContainer.GetComponent<Canvas>();
				canvas.renderMode = (RenderMode)0;
				CanvasScaler obj = uiContainer.AddComponent<CanvasScaler>();
				obj.uiScaleMode = (ScaleMode)1;
				obj.referenceResolution = new Vector2(1920f, 1008f);
				uiContainer.AddComponent<GraphicRaycaster>();
				CreateHeartUi();
				Object.DontDestroyOnLoad((Object)(object)uiContainer);
				Object.DontDestroyOnLoad((Object)(object)canvas);
				initialized = true;
			}
		}

		public static void ToggleVisible()
		{
			if (!((Object)(object)uiContainer == (Object)null))
			{
				uiContainer.active = !uiContainer.active;
			}
		}

		public static void CreateHeartUi()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			GameObject heartImageObject = ModResources.HeartImageObject;
			heartImageObject.transform.parent = uiContainer.transform;
			RectTransform component = heartImageObject.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(0f, 1f);
			component.pivot = new Vector2(0.5f, 0.5f);
			((Transform)component).position = new Vector3(120f, 850f, 0f);
			heartImageObject.GetComponent<Animator>().SetFloat(heartSpeedParamName, 0f);
			GameObject val = new GameObject();
			val.transform.parent = heartImageObject.transform;
			((Object)val).name = "RumbleHeartHud_heartRate";
			TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val2).font = ModResources.TmpFont;
			((TMP_Text)val2).text = "-- BPM";
			RectTransform component2 = ((Component)val2).GetComponent<RectTransform>();
			((Transform)component2).position = new Vector3(0f, 7f);
			component2.sizeDelta = new Vector2(100f, 80f);
			((TMP_Text)val2).enableAutoSizing = true;
			((TMP_Text)val2).fontSizeMax = 55f;
			((TMP_Text)val2).fontSizeMin = 45f;
			component2.anchorMin = new Vector2(0.5f, 0.5f);
			component2.anchorMax = new Vector2(0.5f, 0.5f);
			component2.pivot = new Vector2(0.5f, 0.5f);
			component2.anchoredPosition = Vector2.op_Implicit(new Vector3(0f, 0f));
			((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
			int num = 1;
			heartImageObject.transform.localScale = new Vector3((float)num, (float)num, (float)num);
			uiElements = new HeartUiElements
			{
				Container = heartImageObject,
				HeartRate = val2,
				Position = 1
			};
		}

		public static void UpdateHeartUi(int heartRate)
		{
			if (uiElements != null)
			{
				MelonCoroutines.Start(UpdateHeartUiCoroutine(heartRate));
			}
		}

		private static IEnumerator UpdateHeartUiCoroutine(int heartRate)
		{
			yield return null;
			PerformHeartUiUpdate(heartRate);
		}

		public static void PerformHeartUiUpdate(int heartRate)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			((TMP_Text)uiElements.HeartRate).text = ((heartRate >= 10) ? $"{heartRate}   BPM" : "-- BPM");
			Color heartDefaultColor = ModResources.HeartDefaultColor;
			heartDefaultColor = ((heartRate > 140) ? ModResources.HeartHighColor : ((heartRate >= 90) ? ModResources.HeartMediumColor : ((heartRate < 10) ? ModResources.HeartDefaultColor : ModResources.HeartLowColor)));
			if (heartRate > 0)
			{
				uiElements.Container.GetComponent<Animator>().SetFloat(heartSpeedParamName, (float)heartRate * 0.0166f);
			}
			else
			{
				uiElements.Container.GetComponent<Animator>().SetFloat(heartSpeedParamName, 0f);
			}
			((Graphic)uiElements.HeartRate).color = heartDefaultColor;
		}
	}
	internal class HeartRateReceiver
	{
		private static Process bluetoothProcess;

		public async Task StartStreamingHeartRate()
		{
			try
			{
				Core.Logger.Msg("Starting application for heart rate data...");
				StartBluetoothHandler();
				using NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "HeartRatePipe", PipeDirection.In);
				Core.Logger.Msg("Connecting to HeartRatePipe...");
				pipeClient.Connect();
				Core.Logger.Msg("Connected to HeartRatePipe!");
				using StreamReader reader = new StreamReader(pipeClient, Encoding.UTF8);
				while (true)
				{
					string text = await reader.ReadLineAsync();
					if (text != null && text.StartsWith("HeartRate:"))
					{
						HeartHud.UpdateHeartUi(int.Parse(text.Replace("HeartRate:", "").Trim()));
					}
				}
			}
			catch (Exception ex)
			{
				Core.Logger.Msg("Exception occured connecting to bluetooth: " + ex.Message);
			}
		}

		private static void StartBluetoothHandler()
		{
			try
			{
				bluetoothProcess = new Process
				{
					StartInfo = new ProcessStartInfo
					{
						FileName = "UserData/BluetoothConnectionManager.exe",
						Arguments = Settings.Instance.BluetoothDeviceName,
						CreateNoWindow = true,
						UseShellExecute = false
					}
				};
				bluetoothProcess.Start();
				Core.Logger.Msg("Bluetooth handler started, looking for a device named " + Settings.Instance.BluetoothDeviceName);
			}
			catch (Exception ex)
			{
				Core.Logger.Msg("Failed to start Bluetooth handler: " + ex.Message);
			}
		}

		public static void StopBluetoothHandler()
		{
			try
			{
				HeartHud.UpdateHeartUi(0);
				if (bluetoothProcess != null && !bluetoothProcess.HasExited)
				{
					bluetoothProcess.Kill();
					Core.Logger.Msg("Bluetooth handler stopped.");
				}
			}
			catch (Exception ex)
			{
				Core.Logger.Msg("Failed to stop Bluetooth handler: " + ex.Message);
			}
		}

		public static async void RestartBluetoothHandler(HeartRateReceiver receiverInstance)
		{
			StopBluetoothHandler();
			await receiverInstance.StartStreamingHeartRate();
		}
	}
	internal class HeartUiElements
	{
		public GameObject Container { get; set; }

		public TextMeshProUGUI HeartRate { get; set; }

		public int Position { get; set; }
	}
	internal class ModResources
	{
		private static Il2CppAssetBundle bundle;

		private static TMP_FontAsset tmpFont;

		private static GameObject heartImageObject;

		private static bool initialized = false;

		public static readonly Color HeartLowColor = new Color(0.6431373f, 49f / 51f, 26f / 51f);

		public static readonly Color HeartMediumColor = new Color(1f, 0.7058824f, 0f);

		public static readonly Color HeartHighColor = new Color(1f, 0f, 0f);

		public static readonly Color HeartDefaultColor = new Color(1f, 1f, 1f);

		public static bool Initialized => initialized;

		public static TMP_FontAsset TmpFont => tmpFont;

		public static GameObject HeartImageObject => heartImageObject;

		public static void LoadResources(bool reload = false)
		{
			if (!initialized || reload)
			{
				bundle = Il2CppAssetBundleManager.LoadFromFile("UserData/heartratebundle");
				tmpFont = Object.Instantiate<TMP_FontAsset>(bundle.LoadAsset<TMP_FontAsset>("TMP_GoodDogPlain"));
				heartImageObject = Object.Instantiate<GameObject>(bundle.LoadAsset<GameObject>("HeartImageObject"));
				((Object)heartImageObject).name = "RumbleHeartHud_heartImageObject";
				Object.DontDestroyOnLoad((Object)(object)heartImageObject);
				initialized = true;
			}
		}
	}
	public class Settings
	{
		public static Settings Instance { get; private set; }

		public string BluetoothDeviceName { get; set; }

		public static Settings Initialize()
		{
			Settings obj = new Settings
			{
				BluetoothDeviceName = "Pixel Watch"
			};
			Instance = obj;
			return obj;
		}

		public static Settings FromXmlFile(string filePath)
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(Settings));
			using FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
			return Instance = (Settings)xmlSerializer.Deserialize(stream);
		}

		public void ToXmlFile(string filePath)
		{
			using StreamWriter streamWriter = new StreamWriter(filePath);
			new XmlSerializer(GetType()).Serialize(streamWriter, this);
			streamWriter.Flush();
		}
	}
}

UserLibs/InTheHand.BluetoothLE.dll

Decompiled a month ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Devices.Radios;
using Windows.Foundation;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("In The Hand Ltd")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2004-2022 In The Hand Ltd")]
[assembly: AssemblyDescription("32feet.NET is an open-source project to make personal area networking technologies such as Bluetooth easily accessible from .NET code.")]
[assembly: AssemblyFileVersion("4.0.23.327")]
[assembly: AssemblyInformationalVersion("4.0.23+7156b6d5e96fc1f09828f6fa454a3f57433aa896")]
[assembly: AssemblyProduct("32feet.NET")]
[assembly: AssemblyTitle("InTheHand.BluetoothLE")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/inthehand/32feet")]
[assembly: TargetPlatform("Windows10.0.19041.0")]
[assembly: SupportedOSPlatform("Windows10.0.17763.0")]
[assembly: AssemblyVersion("4.0.0.0")]
namespace InTheHand.Bluetooth;

public static class Bluetooth
{
	[ComImport]
	[Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IInitializeWithWindow
	{
		void Initialize(IntPtr hwnd);
	}

	internal static Dictionary<ulong, WeakReference> KnownDevices = new Dictionary<ulong, WeakReference>();

	private static bool _oldAvailability;

	private static event EventHandler availabilityChanged;

	public static event EventHandler AvailabilityChanged
	{
		add
		{
			if (Bluetooth.availabilityChanged == null)
			{
				AddAvailabilityChanged();
			}
			availabilityChanged += value;
		}
		remove
		{
			availabilityChanged -= value;
			if (Bluetooth.availabilityChanged == null)
			{
				RemoveAvailabilityChanged();
			}
		}
	}

	public static event EventHandler<BluetoothAdvertisingEvent> AdvertisementReceived;

	public static Task<bool> GetAvailabilityAsync()
	{
		return PlatformGetAvailability();
	}

	public static Task<BluetoothDevice> RequestDeviceAsync(RequestDeviceOptions options = null)
	{
		ThrowOnInvalidOptions(options);
		return PlatformRequestDevice(options);
	}

	private static void ThrowOnInvalidOptions(RequestDeviceOptions options)
	{
		if (options != null && (options.Filters != null && options.Filters.Count > 0) == options.AcceptAllDevices)
		{
			throw new ArgumentException("Cannot set both Filters and AcceptAllDevices");
		}
	}

	private static void OnAvailabilityChanged()
	{
		Bluetooth.availabilityChanged?.Invoke(null, EventArgs.Empty);
	}

	public static Task<IReadOnlyCollection<BluetoothDevice>> GetPairedDevicesAsync()
	{
		return PlatformGetPairedDevices();
	}

	public static Task<IReadOnlyCollection<BluetoothDevice>> ScanForDevicesAsync(RequestDeviceOptions options = null)
	{
		ThrowOnInvalidOptions(options);
		return PlatformScanForDevices(options);
	}

	public static Task<BluetoothLEScan> RequestLEScanAsync(BluetoothLEScanOptions options = null)
	{
		return PlatformRequestLEScan(options);
	}

	internal static void OnAdvertisementReceived(BluetoothAdvertisingEvent advertisingEvent)
	{
		Bluetooth.AdvertisementReceived?.Invoke(null, advertisingEvent);
	}

	private static async Task<bool> PlatformGetAvailability()
	{
		TaskAwaiter<BluetoothAdapter> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothAdapter>(BluetoothAdapter.GetDefaultAsync());
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<BluetoothAdapter> taskAwaiter2 = default(TaskAwaiter<BluetoothAdapter>);
			taskAwaiter = taskAwaiter2;
		}
		BluetoothAdapter result = taskAwaiter.GetResult();
		BluetoothAdapter val = result;
		return val.IsLowEnergySupported;
	}

	private static async Task<BluetoothDevice> PlatformRequestDevice(RequestDeviceOptions options)
	{
		DevicePicker val = new DevicePicker();
		Rect val2 = Rect.Empty;
		uint bufferLength = 64u;
		byte[] buffer = new byte[bufferLength];
		_ = IntPtr.Zero;
		try
		{
			if (!string.IsNullOrEmpty(Console.Title))
			{
				val2 = new Rect(0f, 0f, 480f, 480f);
				IntPtr consoleWindow = GetConsoleWindow();
				((IInitializeWithWindow)val).Initialize(consoleWindow);
			}
		}
		catch
		{
		}
		int currentPackageId = GetCurrentPackageId(ref bufferLength, buffer);
		if (currentPackageId == 15700)
		{
			using IEnumerator<Attribute> enumerator = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute)).GetEnumerator();
			if (enumerator.MoveNext())
			{
				Attribute current = enumerator.Current;
				val.Appearance.Title = ((AssemblyProductAttribute)current).Product + " wants to pair";
			}
		}
		else
		{
			val.Appearance.Title = Package.Current.DisplayName + " wants to pair";
		}
		if (options != null && !options.AcceptAllDevices)
		{
			foreach (BluetoothLEScanFilter filter in options.Filters)
			{
				if (!string.IsNullOrEmpty(filter.Name))
				{
					val.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromDeviceName(filter.Name));
				}
				foreach (BluetoothUuid service in filter.Services)
				{
					val.Filter.SupportedDeviceSelectors.Add(GattDeviceService.GetDeviceSelectorFromUuid((Guid)service));
				}
			}
		}
		if (val.Filter.SupportedDeviceSelectors.Count == 0)
		{
			val.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));
			val.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));
		}
		try
		{
			TaskAwaiter<DeviceInformation> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<DeviceInformation>(val.PickSingleDeviceAsync(val2));
			if (!taskAwaiter.IsCompleted)
			{
				await taskAwaiter;
				TaskAwaiter<DeviceInformation> taskAwaiter2 = default(TaskAwaiter<DeviceInformation>);
				taskAwaiter = taskAwaiter2;
			}
			DeviceInformation result = taskAwaiter.GetResult();
			DeviceInformation val3 = result;
			if (val3 == (DeviceInformation)null)
			{
				return null;
			}
			TaskAwaiter<BluetoothLEDevice> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothLEDevice>(BluetoothLEDevice.FromIdAsync(val3.Id));
			if (!taskAwaiter3.IsCompleted)
			{
				await taskAwaiter3;
				TaskAwaiter<BluetoothLEDevice> taskAwaiter4 = default(TaskAwaiter<BluetoothLEDevice>);
				taskAwaiter3 = taskAwaiter4;
			}
			BluetoothLEDevice result2 = taskAwaiter3.GetResult();
			BluetoothLEDevice device = result2;
			TaskAwaiter<DeviceAccessStatus> taskAwaiter5 = WindowsRuntimeSystemExtensions.GetAwaiter<DeviceAccessStatus>(device.RequestAccessAsync());
			if (!taskAwaiter5.IsCompleted)
			{
				await taskAwaiter5;
				TaskAwaiter<DeviceAccessStatus> taskAwaiter6 = default(TaskAwaiter<DeviceAccessStatus>);
				taskAwaiter5 = taskAwaiter6;
			}
			taskAwaiter5.GetResult();
			return new BluetoothDevice(device);
		}
		catch (Exception ex)
		{
			if (ex.HResult == -2147023496)
			{
				throw new PlatformNotSupportedException("RequestDevice cannot be called from a Console application.");
			}
			return null;
		}
	}

	private static async Task<IReadOnlyCollection<BluetoothDevice>> PlatformScanForDevices(RequestDeviceOptions options)
	{
		List<BluetoothDevice> devices = new List<BluetoothDevice>();
		TaskAwaiter<DeviceInformationCollection> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<DeviceInformationCollection>(DeviceInformation.FindAllAsync("System.Devices.DevObjectType:=5 AND System.Devices.Aep.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" AND (System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.Bluetooth.IssueInquiry:=System.StructuredQueryType.Boolean#True)"));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<DeviceInformationCollection> taskAwaiter2 = default(TaskAwaiter<DeviceInformationCollection>);
			taskAwaiter = taskAwaiter2;
		}
		DeviceInformationCollection result = taskAwaiter.GetResult();
		TaskAwaiter<BluetoothLEDevice> taskAwaiter4 = default(TaskAwaiter<BluetoothLEDevice>);
		foreach (DeviceInformation item in result)
		{
			try
			{
				List<BluetoothDevice> list = devices;
				TaskAwaiter<BluetoothLEDevice> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothLEDevice>(BluetoothLEDevice.FromIdAsync(item.Id));
				if (!taskAwaiter3.IsCompleted)
				{
					await taskAwaiter3;
					taskAwaiter3 = taskAwaiter4;
					taskAwaiter4 = default(TaskAwaiter<BluetoothLEDevice>);
				}
				BluetoothLEDevice result2 = taskAwaiter3.GetResult();
				list.Add(result2);
			}
			catch (ArgumentException)
			{
			}
		}
		return devices.AsReadOnly();
	}

	private static async Task<IReadOnlyCollection<BluetoothDevice>> PlatformGetPairedDevices()
	{
		List<BluetoothDevice> devices = new List<BluetoothDevice>();
		TaskAwaiter<DeviceInformationCollection> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<DeviceInformationCollection>(DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<DeviceInformationCollection> taskAwaiter2 = default(TaskAwaiter<DeviceInformationCollection>);
			taskAwaiter = taskAwaiter2;
		}
		DeviceInformationCollection result = taskAwaiter.GetResult();
		TaskAwaiter<BluetoothLEDevice> taskAwaiter4 = default(TaskAwaiter<BluetoothLEDevice>);
		foreach (DeviceInformation item in result)
		{
			try
			{
				List<BluetoothDevice> list = devices;
				TaskAwaiter<BluetoothLEDevice> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothLEDevice>(BluetoothLEDevice.FromIdAsync(item.Id));
				if (!taskAwaiter3.IsCompleted)
				{
					await taskAwaiter3;
					taskAwaiter3 = taskAwaiter4;
					taskAwaiter4 = default(TaskAwaiter<BluetoothLEDevice>);
				}
				BluetoothLEDevice result2 = taskAwaiter3.GetResult();
				list.Add(result2);
			}
			catch (ArgumentException)
			{
			}
		}
		return devices.AsReadOnly();
	}

	private static async void AddAvailabilityChanged()
	{
		_oldAvailability = await PlatformGetAvailability();
		TaskAwaiter<BluetoothAdapter> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothAdapter>(BluetoothAdapter.GetDefaultAsync());
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<BluetoothAdapter> taskAwaiter2 = default(TaskAwaiter<BluetoothAdapter>);
			taskAwaiter = taskAwaiter2;
		}
		BluetoothAdapter result = taskAwaiter.GetResult();
		BluetoothAdapter val = result;
		TaskAwaiter<Radio> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<Radio>(val.GetRadioAsync());
		if (!taskAwaiter3.IsCompleted)
		{
			await taskAwaiter3;
			TaskAwaiter<Radio> taskAwaiter4 = default(TaskAwaiter<Radio>);
			taskAwaiter3 = taskAwaiter4;
		}
		Radio result2 = taskAwaiter3.GetResult();
		Radio val2 = result2;
		val2.StateChanged += Radio_StateChanged;
	}

	private static async void Radio_StateChanged(Radio sender, object args)
	{
		bool flag = await PlatformGetAvailability();
		if (flag != _oldAvailability)
		{
			_oldAvailability = flag;
			OnAvailabilityChanged();
		}
	}

	private static async void RemoveAvailabilityChanged()
	{
		TaskAwaiter<BluetoothAdapter> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothAdapter>(BluetoothAdapter.GetDefaultAsync());
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<BluetoothAdapter> taskAwaiter2 = default(TaskAwaiter<BluetoothAdapter>);
			taskAwaiter = taskAwaiter2;
		}
		BluetoothAdapter result = taskAwaiter.GetResult();
		BluetoothAdapter val = result;
		TaskAwaiter<Radio> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<Radio>(val.GetRadioAsync());
		if (!taskAwaiter3.IsCompleted)
		{
			await taskAwaiter3;
			TaskAwaiter<Radio> taskAwaiter4 = default(TaskAwaiter<Radio>);
			taskAwaiter3 = taskAwaiter4;
		}
		Radio result2 = taskAwaiter3.GetResult();
		Radio val2 = result2;
		val2.StateChanged -= Radio_StateChanged;
	}

	private static async Task<BluetoothLEScan> PlatformRequestLEScan(BluetoothLEScanOptions options)
	{
		if (options == null)
		{
			return (BluetoothLEScan)new BluetoothLEAdvertisementWatcher();
		}
		return (BluetoothLEScan)new BluetoothLEAdvertisementWatcher((BluetoothLEAdvertisementFilter)options);
	}

	private static void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
	{
		Bluetooth.AdvertisementReceived?.Invoke(null, args);
	}

	[DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
	private static extern int GetCurrentPackageId(ref uint bufferLength, byte[] buffer);

	[DllImport("Kernel32")]
	private static extern IntPtr GetConsoleWindow();

	[DllImport("User32")]
	private static extern IntPtr GetActiveWindow();
}
public sealed class BluetoothAdvertisingEvent
{
	private readonly short _rssi;

	private readonly BluetoothLEAdvertisement _advertisement;

	private ushort _appearance;

	private sbyte _txPower;

	public BluetoothDevice Device { get; private set; }

	public BluetoothUuid[] Uuids => GetUuids();

	public string Name => GetName();

	public ushort Appearance => GetAppearance();

	public sbyte TxPower => GetTxPower();

	public short Rssi => GetRssi();

	public IReadOnlyDictionary<ushort, byte[]> ManufacturerData => GetManufacturerData();

	public IReadOnlyDictionary<BluetoothUuid, byte[]> ServiceData => GetServiceData();

	internal BluetoothAdvertisingEvent(BluetoothDevice device)
	{
		Device = device;
	}

	internal BluetoothAdvertisingEvent(BluetoothLEAdvertisementReceivedEventArgs args)
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		_rssi = args.RawSignalStrengthInDBm;
		_txPower = (sbyte)(args.TransmitPowerLevelInDBm.HasValue ? ((sbyte)args.TransmitPowerLevelInDBm.Value) : 0);
		IReadOnlyList<BluetoothLEAdvertisementDataSection> sectionsByType = args.Advertisement.GetSectionsByType((byte)25);
		if (sectionsByType != null && sectionsByType.Count > 0)
		{
			byte[] value = WindowsRuntimeBufferExtensions.ToArray(sectionsByType[0].Data);
			_appearance = BitConverter.ToUInt16(value, 0);
		}
		IAsyncOperation<BluetoothLEDevice> val = BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress, args.BluetoothAddressType);
		if (WindowsRuntimeSystemExtensions.AsTask<BluetoothLEDevice>(val).Wait(7000))
		{
			Device = val.GetResults();
		}
		else
		{
			try
			{
				((IAsyncInfo)val).Cancel();
			}
			catch
			{
			}
		}
		_advertisement = args.Advertisement;
	}

	public static implicit operator BluetoothAdvertisingEvent(BluetoothLEAdvertisementReceivedEventArgs args)
	{
		return new BluetoothAdvertisingEvent(args);
	}

	private ushort GetAppearance()
	{
		return _appearance;
	}

	private short GetRssi()
	{
		return _rssi;
	}

	private sbyte GetTxPower()
	{
		return _txPower;
	}

	private BluetoothUuid[] GetUuids()
	{
		List<BluetoothUuid> list = new List<BluetoothUuid>();
		foreach (Guid serviceUuid in _advertisement.ServiceUuids)
		{
			list.Add(serviceUuid);
		}
		return list.ToArray();
	}

	private string GetName()
	{
		return _advertisement.LocalName;
	}

	private IReadOnlyDictionary<ushort, byte[]> GetManufacturerData()
	{
		Dictionary<ushort, byte[]> dictionary = new Dictionary<ushort, byte[]>();
		foreach (BluetoothLEManufacturerData manufacturerDatum in _advertisement.ManufacturerData)
		{
			dictionary.Add(manufacturerDatum.CompanyId, WindowsRuntimeBufferExtensions.ToArray(manufacturerDatum.Data));
		}
		return new ReadOnlyDictionary<ushort, byte[]>(dictionary);
	}

	private IReadOnlyDictionary<BluetoothUuid, byte[]> GetServiceData()
	{
		Dictionary<BluetoothUuid, byte[]> dictionary = new Dictionary<BluetoothUuid, byte[]>();
		foreach (BluetoothLEAdvertisementDataSection dataSection in _advertisement.DataSections)
		{
			byte[] array = new byte[16];
			if (dataSection.DataType == BluetoothLEAdvertisementDataTypes.ServiceData128BitUuids)
			{
				WindowsRuntimeBufferExtensions.CopyTo(dataSection.Data, 0u, array, 0, 16);
				byte[] array2 = new byte[dataSection.Data.Length - 16];
				WindowsRuntimeBufferExtensions.CopyTo(dataSection.Data, 16u, array2, 0, array2.Length);
				dictionary.Add(new Guid(array), array2);
			}
			else if (dataSection.DataType == BluetoothLEAdvertisementDataTypes.ServiceData32BitUuids)
			{
				WindowsRuntimeBufferExtensions.CopyTo(dataSection.Data, 0u, array, 0, 4);
				byte[] array3 = new byte[dataSection.Data.Length - 4];
				WindowsRuntimeBufferExtensions.CopyTo(dataSection.Data, 4u, array3, 0, array3.Length);
				dictionary.Add(BluetoothUuid.FromShortId(BitConverter.ToUInt16(array, 0)), array3);
			}
			else if (dataSection.DataType == BluetoothLEAdvertisementDataTypes.ServiceData16BitUuids)
			{
				WindowsRuntimeBufferExtensions.CopyTo(dataSection.Data, 0u, array, 0, 2);
				byte[] array4 = new byte[dataSection.Data.Length - 2];
				WindowsRuntimeBufferExtensions.CopyTo(dataSection.Data, 2u, array4, 0, array4.Length);
				dictionary.Add(BluetoothUuid.FromShortId(BitConverter.ToUInt16(array, 0)), array4);
			}
			else
			{
				_ = dataSection.DataType;
				_ = BluetoothLEAdvertisementDataTypes.Flags;
			}
		}
		return new ReadOnlyDictionary<BluetoothUuid, byte[]>(dictionary);
	}
}
public enum BluetoothAppearance : ushort
{
	Unknown = 0,
	GenericPhone = 64,
	GenericComputer = 128,
	GenericWatch = 192,
	GenericClock = 256,
	GenericDisplay = 320,
	GenericRemoteControl = 384,
	GenericEyeGlasses = 448,
	GenericTag = 512,
	GenericKeyring = 576,
	GenericMediaPlayer = 640,
	GenericBarcodeScanner = 704,
	GenericThermometer = 768,
	GenericHeartRateSensor = 832,
	GenericBloodPressure = 896,
	GenericHumanInterfaceDevice = 960,
	GenericGlucoseMeter = 1024,
	GenericRunningWalkingSensor = 1088,
	GenericCycling = 1152,
	GenericControlDevice = 1216,
	GenericNetworkDevice = 1280,
	GenericSensor = 1344,
	GenericLightFixture = 1408,
	GenericFan = 1472,
	GenericHvac = 1536,
	GenericAirConditioning = 1600,
	GenericHumidifier = 1664,
	GenericHeating = 1728,
	GenericAccessControl = 1792,
	GenericMotorizedDevice = 1856,
	GenericPowerDevice = 1920,
	GenericLightSource = 1984,
	GenericPulseOximeter = 3136,
	GenericWeightScale = 3200,
	GenericOutdoorSportsActivity = 5184
}
[DebuggerDisplay("{Id} ({Name})")]
public sealed class BluetoothDevice
{
	internal BluetoothLEDevice NativeDevice;

	internal readonly ConcurrentDictionary<int, IDisposable> NativeDisposeList = new ConcurrentDictionary<int, IDisposable>();

	private string _cachedId;

	private string _cachedName;

	internal ulong LastKnownAddress;

	private RemoteGattServer _remoteGattServer;

	public string Id => GetId();

	public string Name => GetName();

	public RemoteGattServer Gatt => GetGatt();

	public event EventHandler GattServerDisconnected;

	public static Task<BluetoothDevice> FromIdAsync(string id)
	{
		return PlatformFromId(id);
	}

	internal void OnGattServerDisconnected()
	{
		this.GattServerDisconnected?.Invoke(this, EventArgs.Empty);
	}

	public override bool Equals(object obj)
	{
		if (obj is BluetoothDevice bluetoothDevice)
		{
			return Id.Equals(bluetoothDevice.Id);
		}
		return base.Equals(obj);
	}

	internal BluetoothDevice(BluetoothLEDevice device)
	{
		NativeDevice = device;
		AddDisposableObject(this, (IDisposable)device);
		if (!(device == (BluetoothLEDevice)null))
		{
			LastKnownAddress = device.BluetoothAddress;
			GetId();
			GetName();
		}
	}

	~BluetoothDevice()
	{
		DisposeAllNativeObjects();
	}

	internal void AddDisposableObject(object container, IDisposable disposableObject)
	{
		if (NativeDisposeList.TryGetValue(container.GetHashCode(), out var value))
		{
			NativeDisposeList.TryUpdate(container.GetHashCode(), disposableObject, value);
		}
		else
		{
			NativeDisposeList.TryAdd(container.GetHashCode(), disposableObject);
		}
	}

	internal void DisposeAllNativeObjects()
	{
		Dictionary<int, IDisposable> dictionary = new Dictionary<int, IDisposable>();
		foreach (KeyValuePair<int, IDisposable> nativeDispose in NativeDisposeList)
		{
			nativeDispose.Value?.Dispose();
			dictionary.Add(nativeDispose.Key, nativeDispose.Value);
		}
		foreach (KeyValuePair<int, IDisposable> item in dictionary)
		{
			NativeDisposeList.TryUpdate(item.Key, null, item.Value);
		}
	}

	internal async Task<bool> CreateNativeInstance()
	{
		if (LastKnownAddress == 0L)
		{
			return false;
		}
		if (NativeDisposeList.TryGetValue(GetHashCode(), out var value) && value == null)
		{
			TaskAwaiter<BluetoothLEDevice> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothLEDevice>(BluetoothLEDevice.FromBluetoothAddressAsync(LastKnownAddress));
			if (!taskAwaiter.IsCompleted)
			{
				await taskAwaiter;
				TaskAwaiter<BluetoothLEDevice> taskAwaiter2 = default(TaskAwaiter<BluetoothLEDevice>);
				taskAwaiter = taskAwaiter2;
			}
			BluetoothLEDevice result = taskAwaiter.GetResult();
			BluetoothLEDevice val = result;
			if (val != (BluetoothLEDevice)null)
			{
				AddDisposableObject(this, (IDisposable)val);
				NativeDevice = val;
				return true;
			}
		}
		return false;
	}

	internal bool IsDisposedItem(object container)
	{
		if (NativeDisposeList.TryGetValue(container.GetHashCode(), out var value))
		{
			return value == null;
		}
		return false;
	}

	public static implicit operator BluetoothLEDevice(BluetoothDevice device)
	{
		return device.NativeDevice;
	}

	public static implicit operator BluetoothDevice(BluetoothLEDevice device)
	{
		if (!(device == (BluetoothLEDevice)null))
		{
			return new BluetoothDevice(device);
		}
		return null;
	}

	private static async Task<BluetoothDevice> PlatformFromId(string id)
	{
		TaskAwaiter<BluetoothLEDevice> taskAwaiter2 = default(TaskAwaiter<BluetoothLEDevice>);
		BluetoothLEDevice device;
		if (ulong.TryParse(id, NumberStyles.HexNumber, null, out var result))
		{
			if (Bluetooth.KnownDevices.ContainsKey(result))
			{
				BluetoothDevice bluetoothDevice = (BluetoothDevice)Bluetooth.KnownDevices[result].Target;
				if (bluetoothDevice != null)
				{
					return bluetoothDevice;
				}
			}
			TaskAwaiter<BluetoothLEDevice> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothLEDevice>(BluetoothLEDevice.FromBluetoothAddressAsync(result));
			if (!taskAwaiter.IsCompleted)
			{
				await taskAwaiter;
				taskAwaiter = taskAwaiter2;
			}
			BluetoothLEDevice result2 = taskAwaiter.GetResult();
			device = result2;
		}
		else
		{
			TaskAwaiter<BluetoothLEDevice> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<BluetoothLEDevice>(BluetoothLEDevice.FromIdAsync(id));
			if (!taskAwaiter3.IsCompleted)
			{
				await taskAwaiter3;
				taskAwaiter3 = taskAwaiter2;
			}
			BluetoothLEDevice result3 = taskAwaiter3.GetResult();
			device = result3;
		}
		if (device != (BluetoothLEDevice)null)
		{
			TaskAwaiter<DeviceAccessStatus> taskAwaiter4 = WindowsRuntimeSystemExtensions.GetAwaiter<DeviceAccessStatus>(device.RequestAccessAsync());
			if (!taskAwaiter4.IsCompleted)
			{
				await taskAwaiter4;
				TaskAwaiter<DeviceAccessStatus> taskAwaiter5 = default(TaskAwaiter<DeviceAccessStatus>);
				taskAwaiter4 = taskAwaiter5;
			}
			taskAwaiter4.GetResult();
		}
		return device;
	}

	internal string GetId()
	{
		if (IsDisposedItem(this))
		{
			return _cachedId;
		}
		_cachedId = NativeDevice.BluetoothAddress.ToString("X6");
		return _cachedId;
	}

	internal string GetName()
	{
		if (IsDisposedItem(this))
		{
			return _cachedName;
		}
		if (NativeDevice.Name.StartsWith("Bluetooth "))
		{
			_cachedName = NativeDevice.DeviceInformation.Name;
		}
		else
		{
			_cachedName = NativeDevice.Name;
		}
		return _cachedName;
	}

	private RemoteGattServer GetGatt()
	{
		if (_remoteGattServer == null)
		{
			_remoteGattServer = new RemoteGattServer(this);
		}
		return _remoteGattServer;
	}
}
public sealed class BluetoothLEScan
{
	private List<BluetoothLEScanFilter> _filters = new List<BluetoothLEScanFilter>();

	private readonly BluetoothLEAdvertisementWatcher _watcher;

	public IReadOnlyList<BluetoothLEScanFilter> Filters => _filters.AsReadOnly();

	public bool KeepRepeatedDevices => PlatformKeepRepeatedDevices;

	public bool AcceptAllAdvertisements => PlatformAcceptAllAdvertisements;

	public bool Active { get; private set; }

	private bool PlatformAcceptAllAdvertisements => _watcher.AdvertisementFilter == (BluetoothLEAdvertisementFilter)null;

	private bool PlatformKeepRepeatedDevices => true;

	internal BluetoothLEScan()
	{
	}

	public void Stop()
	{
		Active = false;
		PlatformStop();
	}

	private BluetoothLEScan(BluetoothLEAdvertisementWatcher watcher)
	{
		_watcher = watcher;
		_watcher.Received += _watcher_Received;
		_watcher.Start();
		Active = true;
	}

	public static implicit operator BluetoothLEAdvertisementWatcher(BluetoothLEScan scan)
	{
		return scan._watcher;
	}

	public static implicit operator BluetoothLEScan(BluetoothLEAdvertisementWatcher watcher)
	{
		return new BluetoothLEScan(watcher);
	}

	private void _watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
	{
		Bluetooth.OnAdvertisementReceived(args);
	}

	private void PlatformStop()
	{
		_watcher.Stop();
	}
}
public sealed class BluetoothLEScanFilter
{
	public IList<BluetoothUuid> Services { get; } = new List<BluetoothUuid>();


	public string Name { get; set; }

	public string NamePrefix { get; set; }
}
public sealed class BluetoothLEScanOptions
{
	public readonly List<BluetoothLEScanFilter> Filters = new List<BluetoothLEScanFilter>();

	private readonly BluetoothLEAdvertisementFilter _platformFilter;

	public bool KeepRepeatedDevices { get; set; }

	public bool AcceptAllAdvertisements { get; set; }

	public BluetoothLEScanOptions()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		_platformFilter = new BluetoothLEAdvertisementFilter();
	}

	internal BluetoothLEScanOptions(BluetoothLEAdvertisementFilter filter)
	{
		_platformFilter = filter;
	}

	public static implicit operator BluetoothLEAdvertisementFilter(BluetoothLEScanOptions options)
	{
		return options._platformFilter;
	}

	public static implicit operator BluetoothLEScanOptions(BluetoothLEAdvertisementFilter filter)
	{
		return new BluetoothLEScanOptions(filter);
	}
}
public enum BluetoothPhy
{
	Le1m = 1,
	Le2m,
	LeCoded
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field)]
public sealed class BluetoothUtiAttribute : Attribute
{
	public string Uti { get; private set; }

	public BluetoothUtiAttribute()
	{
	}

	public BluetoothUtiAttribute(string uti)
	{
		Uti = uti;
	}
}
[DebuggerDisplay("{ToString()}")]
public struct BluetoothUuid
{
	internal static readonly Guid BluetoothBase = new Guid(0, 0, 4096, 128, 0, 0, 128, 95, 155, 52, 251);

	private Guid _uuid;

	[DebuggerDisplay("{0}")]
	public Guid Value => _uuid;

	public static BluetoothUuid Empty => default(BluetoothUuid);

	private BluetoothUuid(Guid uuid)
	{
		_uuid = uuid;
	}

	public static implicit operator Guid(BluetoothUuid uuid)
	{
		return uuid._uuid;
	}

	public static implicit operator BluetoothUuid(Guid uuid)
	{
		return new BluetoothUuid(uuid);
	}

	public static implicit operator BluetoothUuid(ushort uuid)
	{
		return FromShortId(uuid);
	}

	public static explicit operator BluetoothUuid(string uuid)
	{
		return FromId(uuid);
	}

	public static explicit operator ushort(BluetoothUuid uuid)
	{
		ushort? num = TryGetShortId(uuid);
		if (num.HasValue)
		{
			return num.Value;
		}
		return 0;
	}

	public static bool operator ==(BluetoothUuid uuid1, BluetoothUuid uuid2)
	{
		return uuid1.Value == uuid2.Value;
	}

	public static bool operator ==(BluetoothUuid uuid1, Guid uuid2)
	{
		return uuid1.Value == uuid2;
	}

	public static bool operator !=(BluetoothUuid uuid1, BluetoothUuid uuid2)
	{
		return uuid1.Value != uuid2.Value;
	}

	public static bool operator !=(BluetoothUuid uuid1, Guid uuid2)
	{
		return uuid1.Value != uuid2;
	}

	public override bool Equals(object obj)
	{
		if (obj is BluetoothUuid bluetoothUuid)
		{
			return Value == bluetoothUuid.Value;
		}
		if (obj is ushort num)
		{
			ushort? num2 = TryGetShortId(Value);
			if (num2.HasValue && num2.Value == num)
			{
				return true;
			}
		}
		else if (obj is Guid guid)
		{
			return Value == guid;
		}
		return false;
	}

	public override int GetHashCode()
	{
		return Value.GetHashCode();
	}

	public override string ToString()
	{
		ushort? num = TryGetShortId(Value);
		if (num.HasValue)
		{
			return num.Value.ToString("X4");
		}
		return Value.ToString();
	}

	public static BluetoothUuid FromGuid(Guid uuid)
	{
		return new BluetoothUuid(uuid);
	}

	public static BluetoothUuid FromShortId(ushort shortId)
	{
		byte[] array = BluetoothBase.ToByteArray();
		BitConverter.GetBytes(shortId).CopyTo(array, 0);
		return new Guid(array);
	}

	public static ushort? TryGetShortId(Guid uuid)
	{
		byte[] array = uuid.ToByteArray();
		byte[] array2 = BluetoothBase.ToByteArray();
		bool flag = true;
		for (int i = 4; i < 16; i++)
		{
			if (array[i] != array2[i])
			{
				flag = false;
				break;
			}
		}
		if (!flag)
		{
			return null;
		}
		return BitConverter.ToUInt16(array, 0);
	}

	public static BluetoothUuid FromId(string uuidName)
	{
		if (uuidName.StartsWith("org.bluetooth.service"))
		{
			return GattServiceUuids.FromBluetoothUti(uuidName);
		}
		if (uuidName.StartsWith("org.bluetooth.characteristic"))
		{
			return GattCharacteristicUuids.FromBluetoothUti(uuidName);
		}
		if (uuidName.StartsWith("org.bluetooth.descriptor"))
		{
			return GattDescriptorUuids.FromBluetoothUti(uuidName);
		}
		return default(BluetoothUuid);
	}

	public static BluetoothUuid GetService(string name)
	{
		if (Guid.TryParse(name, out var result))
		{
			return result;
		}
		if (ushort.TryParse(name, out var result2))
		{
			return FromShortId(result2);
		}
		return GattServiceUuids.FromBluetoothUti(name);
	}

	public static BluetoothUuid GetCharacteristic(string name)
	{
		if (Guid.TryParse(name, out var result))
		{
			return result;
		}
		if (ushort.TryParse(name, out var result2))
		{
			return FromShortId(result2);
		}
		return GattCharacteristicUuids.FromBluetoothUti(name);
	}

	public static BluetoothUuid GetDescriptor(string name)
	{
		if (Guid.TryParse(name, out var result))
		{
			return result;
		}
		if (ushort.TryParse(name, out var result2))
		{
			return FromShortId(result2);
		}
		return GattDescriptorUuids.FromBluetoothUti(name);
	}
}
[Flags]
internal enum ClientCharacteristicDescriptorValue
{
	None = 0,
	Notify = 1,
	Indicate = 2
}
[DebuggerDisplay("{Uuid} (Characteristic)")]
public sealed class GattCharacteristic
{
	private readonly GattCharacteristic _characteristic;

	public GattService Service { get; private set; }

	public BluetoothUuid Uuid => GetUuid();

	public GattCharacteristicProperties Properties => GetProperties();

	public string UserDescription => GetUserDescription();

	public byte[] Value => PlatformGetValue();

	private event EventHandler<GattCharacteristicValueChangedEventArgs> characteristicValueChanged;

	public event EventHandler<GattCharacteristicValueChangedEventArgs> CharacteristicValueChanged
	{
		add
		{
			characteristicValueChanged += value;
			AddCharacteristicValueChanged();
		}
		remove
		{
			characteristicValueChanged -= value;
			RemoveCharacteristicValueChanged();
		}
	}

	internal GattCharacteristic(GattService service)
	{
		Service = service;
	}

	private string GetManualUserDescription()
	{
		GattDescriptor result = GetDescriptorAsync(GattDescriptorUuids.CharacteristicUserDescription).Result;
		if (result != null)
		{
			byte[] result2 = result.ReadValueAsync().Result;
			return Encoding.UTF8.GetString(result2);
		}
		return string.Empty;
	}

	public Task<byte[]> ReadValueAsync()
	{
		return PlatformReadValue();
	}

	public Task WriteValueWithResponseAsync(byte[] value)
	{
		ThrowOnInvalidValue(value);
		return PlatformWriteValue(value, requireResponse: true);
	}

	public Task WriteValueWithoutResponseAsync(byte[] value)
	{
		ThrowOnInvalidValue(value);
		return PlatformWriteValue(value, requireResponse: false);
	}

	private void ThrowOnInvalidValue(byte[] value)
	{
		if (value == null)
		{
			throw new ArgumentNullException("value");
		}
		if (value.Length > 512)
		{
			throw new ArgumentOutOfRangeException("value", "Attribute value cannot be longer than 512 bytes");
		}
	}

	public Task<GattDescriptor> GetDescriptorAsync(BluetoothUuid descriptor)
	{
		return PlatformGetDescriptor(descriptor);
	}

	public Task<IReadOnlyList<GattDescriptor>> GetDescriptorsAsync()
	{
		return PlatformGetDescriptors();
	}

	private void OnCharacteristicValueChanged(GattCharacteristicValueChangedEventArgs args)
	{
		this.characteristicValueChanged?.Invoke(this, args);
	}

	public Task StartNotificationsAsync()
	{
		return PlatformStartNotifications();
	}

	public Task StopNotificationsAsync()
	{
		return PlatformStopNotifications();
	}

	internal GattCharacteristic(GattService service, GattCharacteristic characteristic)
		: this(service)
	{
		_characteristic = characteristic;
	}

	public static implicit operator GattCharacteristic(GattCharacteristic characteristic)
	{
		return characteristic._characteristic;
	}

	private BluetoothUuid GetUuid()
	{
		return _characteristic.Uuid;
	}

	private string GetUserDescription()
	{
		return _characteristic.UserDescription;
	}

	private GattCharacteristicProperties GetProperties()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected I4, but got Unknown
		return (GattCharacteristicProperties)_characteristic.CharacteristicProperties;
	}

	private async Task<GattDescriptor> PlatformGetDescriptor(Guid descriptor)
	{
		TaskAwaiter<GattDescriptorsResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattDescriptorsResult>(_characteristic.GetDescriptorsForUuidAsync(descriptor));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattDescriptorsResult> taskAwaiter2 = default(TaskAwaiter<GattDescriptorsResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattDescriptorsResult result = taskAwaiter.GetResult();
		GattDescriptorsResult val = result;
		if ((int)val.Status == 0 && val.Descriptors.Count > 0)
		{
			return new GattDescriptor(this, val.Descriptors[0]);
		}
		return null;
	}

	private async Task<IReadOnlyList<GattDescriptor>> PlatformGetDescriptors()
	{
		List<GattDescriptor> descriptors = new List<GattDescriptor>();
		TaskAwaiter<GattDescriptorsResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattDescriptorsResult>(_characteristic.GetDescriptorsAsync());
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattDescriptorsResult> taskAwaiter2 = default(TaskAwaiter<GattDescriptorsResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattDescriptorsResult result = taskAwaiter.GetResult();
		GattDescriptorsResult val = result;
		if ((int)val.Status == 0)
		{
			foreach (GattDescriptor descriptor in val.Descriptors)
			{
				descriptors.Add(new GattDescriptor(this, descriptor));
			}
		}
		return descriptors;
	}

	private byte[] PlatformGetValue()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		Task<GattReadResult> task = WindowsRuntimeSystemExtensions.AsTask<GattReadResult>(_characteristic.ReadValueAsync((BluetoothCacheMode)0));
		task.Wait();
		GattReadResult result = task.Result;
		if ((int)result.Status == 0)
		{
			return WindowsRuntimeBufferExtensions.ToArray(result.Value);
		}
		return null;
	}

	private async Task<byte[]> PlatformReadValue()
	{
		GattReadResult val = await WindowsRuntimeSystemExtensions.AsTask<GattReadResult>(_characteristic.ReadValueAsync((BluetoothCacheMode)1)).ConfigureAwait(continueOnCapturedContext: false);
		if ((int)val.Status == 0)
		{
			return WindowsRuntimeBufferExtensions.ToArray(val.Value);
		}
		return null;
	}

	private async Task PlatformWriteValue(byte[] value, bool requireResponse)
	{
		TaskAwaiter<GattCommunicationStatus> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattCommunicationStatus>(_characteristic.WriteValueAsync(WindowsRuntimeBufferExtensions.AsBuffer(value), (GattWriteOption)((!requireResponse) ? 1 : 0)));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattCommunicationStatus> taskAwaiter2 = default(TaskAwaiter<GattCommunicationStatus>);
			taskAwaiter = taskAwaiter2;
		}
		taskAwaiter.GetResult();
	}

	private void AddCharacteristicValueChanged()
	{
		_characteristic.ValueChanged += Characteristic_ValueChanged;
	}

	private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
	{
		OnCharacteristicValueChanged(new GattCharacteristicValueChangedEventArgs(WindowsRuntimeBufferExtensions.ToArray(args.CharacteristicValue)));
	}

	private void RemoveCharacteristicValueChanged()
	{
		_characteristic.ValueChanged -= Characteristic_ValueChanged;
	}

	private async Task PlatformStartNotifications()
	{
		GattClientCharacteristicConfigurationDescriptorValue val;
		if (((Enum)_characteristic.CharacteristicProperties).HasFlag((Enum)(object)(GattCharacteristicProperties)16))
		{
			val = (GattClientCharacteristicConfigurationDescriptorValue)1;
		}
		else
		{
			if (!((Enum)_characteristic.CharacteristicProperties).HasFlag((Enum)(object)(GattCharacteristicProperties)32))
			{
				return;
			}
			val = (GattClientCharacteristicConfigurationDescriptorValue)2;
		}
		try
		{
			TaskAwaiter<GattCommunicationStatus> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattCommunicationStatus>(_characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(val));
			if (!taskAwaiter.IsCompleted)
			{
				await taskAwaiter;
				TaskAwaiter<GattCommunicationStatus> taskAwaiter2 = default(TaskAwaiter<GattCommunicationStatus>);
				taskAwaiter = taskAwaiter2;
			}
			taskAwaiter.GetResult();
		}
		catch (UnauthorizedAccessException)
		{
		}
	}

	private async Task PlatformStopNotifications()
	{
		try
		{
			TaskAwaiter<GattCommunicationStatus> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattCommunicationStatus>(_characteristic.WriteClientCharacteristicConfigurationDescriptorAsync((GattClientCharacteristicConfigurationDescriptorValue)0));
			if (!taskAwaiter.IsCompleted)
			{
				await taskAwaiter;
				TaskAwaiter<GattCommunicationStatus> taskAwaiter2 = default(TaskAwaiter<GattCommunicationStatus>);
				taskAwaiter = taskAwaiter2;
			}
			taskAwaiter.GetResult();
		}
		catch
		{
			throw new NotSupportedException();
		}
	}
}
public sealed class GattCharacteristicValueChangedEventArgs : EventArgs
{
	public byte[] Value { get; private set; }

	internal GattCharacteristicValueChangedEventArgs(byte[] newValue)
	{
		Value = newValue;
	}
}
[Flags]
public enum GattCharacteristicProperties
{
	None = 0,
	Broadcast = 1,
	Read = 2,
	WriteWithoutResponse = 4,
	Write = 8,
	Notify = 0x10,
	Indicate = 0x20,
	AuthenticatedSignedWrites = 0x40,
	ExtendedProperties = 0x80,
	ReliableWrites = 0x100,
	WriteableAuxiliaries = 0x200
}
[BluetoothUti("org.bluetooth.characteristic")]
public static class GattCharacteristicUuids
{
	internal const string Namespace = "org.bluetooth.characteristic";

	[BluetoothUti("aerobic_heart_rate_lower_limit")]
	public static readonly BluetoothUuid AerobicHeartRateLowerLimit = (ushort)10878;

	[BluetoothUti("aerobic_heart_rate_upper_limit")]
	public static readonly BluetoothUuid AerobicHeartRateUpperLimit = (ushort)10884;

	[BluetoothUti("aerobic_threshold")]
	public static readonly BluetoothUuid AerobicThreshold = (ushort)10879;

	[BluetoothUti("age")]
	public static readonly BluetoothUuid Age = (ushort)10880;

	[BluetoothUti("aggregate")]
	public static readonly BluetoothUuid Aggregate = (ushort)10842;

	[BluetoothUti("alert_category_id")]
	public static readonly BluetoothUuid AlertCategoryId = (ushort)10819;

	[BluetoothUti("alert_category_id_bit_mask")]
	public static readonly BluetoothUuid AlertCategoryIdBitMask = (ushort)10818;

	[BluetoothUti("alert_level")]
	public static readonly BluetoothUuid AlertLevel = (ushort)10758;

	[BluetoothUti("alert_notification_control_point")]
	public static readonly BluetoothUuid AlertNotificationControlPoint = (ushort)10820;

	[BluetoothUti("alert_status")]
	public static readonly BluetoothUuid AlertStatus = (ushort)10815;

	[BluetoothUti("altitude")]
	public static readonly BluetoothUuid Altitude = (ushort)10931;

	[BluetoothUti("anaerobic_heart_rate_lower_limit")]
	public static readonly BluetoothUuid AnaerobicHeartRateLowerLimit = (ushort)10881;

	[BluetoothUti("anaerobic_heart_rate_upper_limit")]
	public static readonly BluetoothUuid AnaerobicHeartRateUpperLimit = (ushort)10882;

	[BluetoothUti("anaerobic_threshold")]
	public static readonly BluetoothUuid AnaerobicThreshold = (ushort)10883;

	[BluetoothUti("analog")]
	public static readonly BluetoothUuid Analog = (ushort)10840;

	[BluetoothUti("analog_output")]
	public static readonly BluetoothUuid AnalogOutput = (ushort)10841;

	[BluetoothUti("apparent_wind_direction")]
	public static readonly BluetoothUuid ApparentWindDirection = (ushort)10867;

	[BluetoothUti("apparent_wind_speed")]
	public static readonly BluetoothUuid ApparentWindSpeed = (ushort)10866;

	[BluetoothUti("gap.appearance")]
	public static readonly BluetoothUuid Appearance = (ushort)10753;

	[BluetoothUti("barometric_pressure_trend")]
	public static readonly BluetoothUuid BarometricPressureTrend = (ushort)10915;

	[BluetoothUti("battery_level")]
	public static readonly BluetoothUuid BatteryLevel = (ushort)10777;

	[BluetoothUti("battery_level_state")]
	public static readonly BluetoothUuid BatteryLevelState = (ushort)10779;

	[BluetoothUti("battery_power_state")]
	public static readonly BluetoothUuid BatteryPowerState = (ushort)10778;

	[BluetoothUti("blood_pressure_feature")]
	public static readonly BluetoothUuid BloodPressureFeature = (ushort)10825;

	[BluetoothUti("blood_pressure_measurement")]
	public static readonly BluetoothUuid BloodPressureMeasurement = (ushort)10805;

	[BluetoothUti("body_composition_feature")]
	public static readonly BluetoothUuid BodyCompositionFeature = (ushort)10907;

	[BluetoothUti("body_composition_measurement")]
	public static readonly BluetoothUuid BodyCompositionMeasurement = (ushort)10908;

	[BluetoothUti("body_sensor_location")]
	public static readonly BluetoothUuid BodySensorLocation = (ushort)10808;

	[BluetoothUti("bond_management_control_point")]
	public static readonly BluetoothUuid BondManagementControlPoint = (ushort)10916;

	[BluetoothUti("bond_management_feature")]
	public static readonly BluetoothUuid BondManagementFeatures = (ushort)10917;

	[BluetoothUti("boot_keyboard_input_report")]
	public static readonly BluetoothUuid BootKeyboardInputReport = (ushort)10786;

	[BluetoothUti("boot_keyboard_output_report")]
	public static readonly BluetoothUuid BootKeyboardOutputReport = (ushort)10802;

	[BluetoothUti("boot_mouse_input_report")]
	public static readonly BluetoothUuid BootMouseInputReport = (ushort)10803;

	public static readonly BluetoothUuid BssControlPoint = (ushort)11051;

	public static readonly BluetoothUuid BssResponse = (ushort)11052;

	[BluetoothUti("gap.central_address_resolution")]
	public static readonly BluetoothUuid CentralAddressResolution = (ushort)10918;

	[BluetoothUti("cgm_feature")]
	public static readonly BluetoothUuid CgmFeature = (ushort)10920;

	[BluetoothUti("cgm_measurement")]
	public static readonly BluetoothUuid CgmMeasurement = (ushort)10919;

	[BluetoothUti("cgm_session_run_time")]
	public static readonly BluetoothUuid CgmSessionRunTime = (ushort)10923;

	[BluetoothUti("cgm_session_start_time")]
	public static readonly BluetoothUuid CgmSessionStartTime = (ushort)10922;

	[BluetoothUti("cgm_specific_ops_control_point")]
	public static readonly BluetoothUuid CgmSpecificOpsControlPoint = (ushort)10924;

	[BluetoothUti("cgm_status")]
	public static readonly BluetoothUuid CgmStatus = (ushort)10921;

	public static readonly BluetoothUuid ClientSupportedFeatures = (ushort)11049;

	[BluetoothUti("cross_trainer_data")]
	public static readonly BluetoothUuid CrossTrainerData = (ushort)10958;

	[BluetoothUti("csc_feature")]
	public static readonly BluetoothUuid CscFeature = (ushort)10844;

	[BluetoothUti("csc_measurement")]
	public static readonly BluetoothUuid CscMeasurement = (ushort)10843;

	[BluetoothUti("current_time")]
	public static readonly BluetoothUuid CurrentTime = (ushort)10795;

	[BluetoothUti("cycling_power_control_point")]
	public static readonly BluetoothUuid CyclingPowerControlPoint = (ushort)10854;

	[BluetoothUti("cycling_power_feature")]
	public static readonly BluetoothUuid CyclingPowerFeature = (ushort)10853;

	[BluetoothUti("cycling_power_measurement")]
	public static readonly BluetoothUuid CyclingPowerMeasurement = (ushort)10851;

	[BluetoothUti("cycling_power_vector")]
	public static readonly BluetoothUuid CyclingPowerVector = (ushort)10852;

	[BluetoothUti("database_change_increment")]
	public static readonly BluetoothUuid DatabaseChangeIncrement = (ushort)10905;

	[BluetoothUti("database_hash")]
	public static readonly BluetoothUuid DatabaseHash = (ushort)11050;

	[BluetoothUti("date_of_birth")]
	public static readonly BluetoothUuid DateOfBirth = (ushort)10885;

	[BluetoothUti("date_of_threshold_assessment")]
	public static readonly BluetoothUuid DateOfThresholdAssessment = (ushort)10886;

	[BluetoothUti("date_time")]
	public static readonly BluetoothUuid DateTime = (ushort)10760;

	[BluetoothUti("date_utc")]
	public static readonly BluetoothUuid DateUtc = (ushort)10989;

	[BluetoothUti("day_date_time")]
	public static readonly BluetoothUuid DayDateTime = (ushort)10762;

	[BluetoothUti("day_of_week")]
	public static readonly BluetoothUuid DayOfWeek = (ushort)10761;

	[BluetoothUti("descriptor_value_changed")]
	public static readonly BluetoothUuid DescriptorValueChanged = (ushort)10877;

	[BluetoothUti("gap.device_name")]
	public static readonly BluetoothUuid DeviceName = (ushort)10752;

	[BluetoothUti("dew_point")]
	public static readonly BluetoothUuid DewPoint = (ushort)10875;

	[BluetoothUti("digital")]
	public static readonly BluetoothUuid Digital = (ushort)10838;

	[BluetoothUti("digital_output")]
	public static readonly BluetoothUuid DigitalOutput = (ushort)10839;

	[BluetoothUti("dst_offset")]
	public static readonly BluetoothUuid DstOffset = (ushort)10765;

	[BluetoothUti("elevation")]
	public static readonly BluetoothUuid Elevation = (ushort)10860;

	[BluetoothUti("email_address")]
	public static readonly BluetoothUuid EmailAddress = (ushort)10887;

	public static readonly BluetoothUuid EmergencyId = (ushort)11053;

	public static readonly BluetoothUuid EmergencyText = (ushort)11054;

	[BluetoothUti("exact_time_100")]
	public static readonly BluetoothUuid ExactTime100 = (ushort)10763;

	[BluetoothUti("exact_time_256")]
	public static readonly BluetoothUuid ExactTime256 = (ushort)10764;

	[BluetoothUti("fat_burn_heart_rate_lower_limit")]
	public static readonly BluetoothUuid FatBurnHeartRateLowerLimit = (ushort)10888;

	[BluetoothUti("fat_burn_heart_rate_upper_limit")]
	public static readonly BluetoothUuid FatBurnHeartRateUpperLimit = (ushort)10889;

	[BluetoothUti("firmware_revision_string")]
	public static readonly BluetoothUuid FirmwareRevisionString = (ushort)10790;

	[BluetoothUti("first_name")]
	public static readonly BluetoothUuid FirstName = (ushort)10890;

	[BluetoothUti("fitness_machine_control_point")]
	public static readonly BluetoothUuid FitnessMachineControlPoint = (ushort)10969;

	[BluetoothUti("fitness_machine_feature")]
	public static readonly BluetoothUuid FitnessMachineFeature = (ushort)10956;

	[BluetoothUti("fitness_machine_status")]
	public static readonly BluetoothUuid FitnessMachineStatus = (ushort)10970;

	[BluetoothUti("five_zone_heart_rate_limits")]
	public static readonly BluetoothUuid FiveZoneHeartRateLimits = (ushort)10891;

	[BluetoothUti("floor_number")]
	public static readonly BluetoothUuid FloorNumber = (ushort)10930;

	[BluetoothUti("gender")]
	public static readonly BluetoothUuid Gender = (ushort)10892;

	[BluetoothUti("glucose_feature")]
	public static readonly BluetoothUuid GlucoseFeature = (ushort)10833;

	[BluetoothUti("glucose_measurement")]
	public static readonly BluetoothUuid GlucoseMeasurement = (ushort)10776;

	[BluetoothUti("glucose_measurement_context")]
	public static readonly BluetoothUuid GlucoseMeasurementContext = (ushort)10804;

	[BluetoothUti("gust_factor")]
	public static readonly BluetoothUuid GustFactor = (ushort)10868;

	[BluetoothUti("hardware_revision_string")]
	public static readonly BluetoothUuid HardwareRevisionString = (ushort)10791;

	[BluetoothUti("heart_rate_control_point")]
	public static readonly BluetoothUuid HeartRateControlPoint = (ushort)10809;

	[BluetoothUti("heart_rate_max")]
	public static readonly BluetoothUuid HeartRateMax = (ushort)10893;

	[BluetoothUti("heart_rate_measurement")]
	public static readonly BluetoothUuid HeartRateMeasurement = (ushort)10807;

	[BluetoothUti("heat_index")]
	public static readonly BluetoothUuid HeatIndex = (ushort)10874;

	[BluetoothUti("height")]
	public static readonly BluetoothUuid Height = (ushort)10894;

	[BluetoothUti("hid_control_point")]
	public static readonly BluetoothUuid HidControlPoint = (ushort)10828;

	[BluetoothUti("hid_information")]
	public static readonly BluetoothUuid HidInformation = (ushort)10826;

	[BluetoothUti("hip_circumference")]
	public static readonly BluetoothUuid HipCircumference = (ushort)10895;

	[BluetoothUti("http_control_point")]
	public static readonly BluetoothUuid HttpControlPoint = (ushort)10938;

	[BluetoothUti("http_entity_body")]
	public static readonly BluetoothUuid HttpEntityBody = (ushort)10937;

	[BluetoothUti("http_headers")]
	public static readonly BluetoothUuid HttpHeaders = (ushort)10935;

	[BluetoothUti("http_status_code")]
	public static readonly BluetoothUuid HttpStatusCode = (ushort)10936;

	[BluetoothUti("https_security")]
	public static readonly BluetoothUuid HttpsSecurity = (ushort)10939;

	[BluetoothUti("humidity")]
	public static readonly BluetoothUuid Humidity = (ushort)10863;

	[BluetoothUti("idd_annunciation_status")]
	public static readonly BluetoothUuid IddAnnunciationStatus = (ushort)11042;

	[BluetoothUti("idd_command_control_point")]
	public static readonly BluetoothUuid IddCommandControlPoint = (ushort)11045;

	[BluetoothUti("idd_command_data")]
	public static readonly BluetoothUuid IddCommandData = (ushort)11046;

	[BluetoothUti("idd_features")]
	public static readonly BluetoothUuid IddFeatures = (ushort)11043;

	[BluetoothUti("idd_history_data")]
	public static readonly BluetoothUuid IddHistoryData = (ushort)11048;

	[BluetoothUti("idd_record_access_control_point")]
	public static readonly BluetoothUuid IddRecordAccessControlPoint = (ushort)11047;

	[BluetoothUti("idd_status")]
	public static readonly BluetoothUuid IddStatus = (ushort)11041;

	[BluetoothUti("idd_status_changed")]
	public static readonly BluetoothUuid IddStatusChanged = (ushort)11040;

	[BluetoothUti("idd_status_reader_control_point")]
	public static readonly BluetoothUuid IddStatusReaderControlPoint = (ushort)11044;

	[BluetoothUti("indoor_bike_data")]
	public static readonly BluetoothUuid IndoorBikeData = (ushort)10962;

	[BluetoothUti("indoor_positioning_configuration")]
	public static readonly BluetoothUuid IndoorPositioningConfiguration = (ushort)10925;

	[BluetoothUti("intermediate_cuff_pressure")]
	public static readonly BluetoothUuid IntermediateCuffPressure = (ushort)10806;

	[BluetoothUti("intermediate_temperature")]
	public static readonly BluetoothUuid IntermediateTemperature = (ushort)10782;

	[BluetoothUti("irradiance")]
	public static readonly BluetoothUuid Irradiance = (ushort)10871;

	[BluetoothUti("language")]
	public static readonly BluetoothUuid Language = (ushort)10914;

	[BluetoothUti("last_name")]
	public static readonly BluetoothUuid LastName = (ushort)10896;

	[BluetoothUti("latitude")]
	public static readonly BluetoothUuid Latitude = (ushort)10926;

	[BluetoothUti("ln_control_point")]
	public static readonly BluetoothUuid LNControlPoint = (ushort)10859;

	[BluetoothUti("ln_feature")]
	public static readonly BluetoothUuid LNFeature = (ushort)10858;

	[BluetoothUti("local_east_coordinate")]
	public static readonly BluetoothUuid LocalEastCoordinate = (ushort)10929;

	[BluetoothUti("local_north_coordinate")]
	public static readonly BluetoothUuid LocalNorthCoordinate = (ushort)10928;

	[BluetoothUti("local_time_information")]
	public static readonly BluetoothUuid LocalTimeInformation = (ushort)10767;

	[BluetoothUti("location_and_speed")]
	public static readonly BluetoothUuid LocationAndSpeed = (ushort)10855;

	[BluetoothUti("location_name")]
	public static readonly BluetoothUuid LocationName = (ushort)10933;

	[BluetoothUti("longitude")]
	public static readonly BluetoothUuid Longitude = (ushort)10927;

	[BluetoothUti("magnetic_declination")]
	public static readonly BluetoothUuid MagneticDeclination = (ushort)10796;

	[BluetoothUti("Magnetic_flux_density_2D")]
	public static readonly BluetoothUuid MagneticFluxDensity2D = (ushort)10912;

	[BluetoothUti("Magnetic_flux_density_3D")]
	public static readonly BluetoothUuid MagneticFluxDensity3D = (ushort)10913;

	[BluetoothUti("manufacturer_name_string")]
	public static readonly BluetoothUuid ManufacturerNameString = (ushort)10793;

	[BluetoothUti("maximum_recommended_heart_rate")]
	public static readonly BluetoothUuid MaximumRecommendedHeartRate = (ushort)10897;

	[BluetoothUti("measurement_interval")]
	public static readonly BluetoothUuid MeasurementInterval = (ushort)10785;

	[BluetoothUti("model_number_string")]
	public static readonly BluetoothUuid ModelNumberString = (ushort)10788;

	[BluetoothUti("navigation")]
	public static readonly BluetoothUuid Navigation = (ushort)10856;

	[BluetoothUti("network_availability")]
	public static readonly BluetoothUuid NetworkAvailability = (ushort)10814;

	[BluetoothUti("new_alert")]
	public static readonly BluetoothUuid NewAlert = (ushort)10822;

	[BluetoothUti("object_action_control_point")]
	public static readonly BluetoothUuid ObjectActionControlPoint = (ushort)10949;

	[BluetoothUti("object_changed")]
	public static readonly BluetoothUuid ObjectChanged = (ushort)10952;

	[BluetoothUti("object_first_created")]
	public static readonly BluetoothUuid ObjectFirstCreated = (ushort)10945;

	[BluetoothUti("object_id")]
	public static readonly BluetoothUuid ObjectID = (ushort)10947;

	[BluetoothUti("object_last_modified")]
	public static readonly BluetoothUuid ObjectLastModified = (ushort)10946;

	[BluetoothUti("object_list_control_point")]
	public static readonly BluetoothUuid ObjectListControlPoint = (ushort)10950;

	[BluetoothUti("object_list_filter")]
	public static readonly BluetoothUuid ObjectListFilter = (ushort)10951;

	[BluetoothUti("object_name")]
	public static readonly BluetoothUuid ObjectName = (ushort)10942;

	[BluetoothUti("object_properties")]
	public static readonly BluetoothUuid ObjectProperties = (ushort)10948;

	[BluetoothUti("object_size")]
	public static readonly BluetoothUuid ObjectSize = (ushort)10944;

	[BluetoothUti("object_type")]
	public static readonly BluetoothUuid ObjectType = (ushort)10943;

	[BluetoothUti("ots_feature")]
	public static readonly BluetoothUuid OtsFeature = (ushort)10941;

	[BluetoothUti("gap.peripheral_preferred_connection_parameters")]
	public static readonly BluetoothUuid PeripheralPreferredConnectionParameters = (ushort)10756;

	[BluetoothUti("gap.peripheral_privacy_flag")]
	public static readonly BluetoothUuid PeripheralPrivacyFlag = (ushort)10754;

	[BluetoothUti("plx_spot_check_measurement")]
	public static readonly BluetoothUuid PlxSpotCheckMeasurement = (ushort)10846;

	[BluetoothUti("plx_continuous_measurement")]
	public static readonly BluetoothUuid PlxContinuousMeasurement = (ushort)10847;

	[BluetoothUti("plx_features")]
	public static readonly BluetoothUuid PlxFeatures = (ushort)10848;

	[BluetoothUti("pollen_concentration")]
	public static readonly BluetoothUuid PollenConcentration = (ushort)10869;

	[BluetoothUti("position_quality")]
	public static readonly BluetoothUuid PositionQuality = (ushort)10857;

	[BluetoothUti("pressure")]
	public static readonly BluetoothUuid Pressure = (ushort)10861;

	[BluetoothUti("rainfall")]
	public static readonly BluetoothUuid Rainfall = (ushort)10872;

	[BluetoothUti("gap.reconnection_address")]
	public static readonly BluetoothUuid ReconnectionAddress = (ushort)10755;

	[BluetoothUti("reference_time_information")]
	public static readonly BluetoothUuid ReferenceTimeInformation = (ushort)10772;

	[BluetoothUti("ieee_11073-20601_regulatoryertification_data_list")]
	public static readonly BluetoothUuid RegulatoryCertificationDataList = (ushort)10794;

	[BluetoothUti("sensor_location")]
	public static readonly BluetoothUuid SensorLocation = (ushort)10845;

	[BluetoothUti("server_supported_features")]
	public static readonly BluetoothUuid ServerSupportedFeatures = (ushort)11066;

	[BluetoothUti("gap.service_changed")]
	public static readonly BluetoothUuid ServiceChanged = (ushort)10757;

	[BluetoothUti("tempurature")]
	public static readonly BluetoothUuid Tempurature = (ushort)10862;

	[BluetoothUti("tempurature_measurement")]
	public static readonly BluetoothUuid TempuratureMeasurement = (ushort)10780;

	[BluetoothUti("tempurature_type")]
	public static readonly BluetoothUuid TempuratureType = (ushort)10781;

	[BluetoothUti("time_accuracy")]
	public static readonly BluetoothUuid TimeAccuracy = (ushort)10770;

	[BluetoothUti("time_source")]
	public static readonly BluetoothUuid TimeSource = (ushort)10771;

	[BluetoothUti("time_update_control_point")]
	public static readonly BluetoothUuid TimeUpdateControlPoint = (ushort)10774;

	[BluetoothUti("time_update_state")]
	public static readonly BluetoothUuid TimeUpdateState = (ushort)10775;

	[BluetoothUti("time_with_dst")]
	public static readonly BluetoothUuid TimeWithDst = (ushort)10769;

	[BluetoothUti("time_zone")]
	public static readonly BluetoothUuid TimeZone = (ushort)10766;

	[BluetoothUti("true_wind_direction")]
	public static readonly BluetoothUuid TrueWindDirection = (ushort)10865;

	[BluetoothUti("true_wind_speed")]
	public static readonly BluetoothUuid TrueWindSpeed = (ushort)10864;

	[BluetoothUti("uv_index")]
	public static readonly BluetoothUuid UVIndex = (ushort)10870;

	[BluetoothUti("wind_chill")]
	public static readonly BluetoothUuid WindChill = (ushort)10873;

	public static BluetoothUuid FromBluetoothUti(string bluetoothUti)
	{
		string text = bluetoothUti.ToLower();
		if (text.StartsWith("org.bluetooth.characteristic"))
		{
			text = text.Replace("org.bluetooth.characteristic.", string.Empty);
		}
		FieldInfo[] fields = typeof(GattCharacteristicUuids).GetFields(BindingFlags.Static | BindingFlags.Public);
		FieldInfo[] array = fields;
		foreach (FieldInfo fieldInfo in array)
		{
			Attribute customAttribute = fieldInfo.GetCustomAttribute(typeof(BluetoothUtiAttribute));
			if (customAttribute != null && ((BluetoothUtiAttribute)customAttribute).Uti == text)
			{
				return (BluetoothUuid)fieldInfo.GetValue(null);
			}
		}
		return default(BluetoothUuid);
	}

	public static string GetCharacteristicName(BluetoothUuid uuid, bool includeNamespace = false)
	{
		ushort? num = BluetoothUuid.TryGetShortId(uuid);
		if (num.HasValue && (num.Value & 0xF200) == 8704)
		{
			FieldInfo[] fields = typeof(GattCharacteristicUuids).GetFields(BindingFlags.Static | BindingFlags.Public);
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				if ((BluetoothUuid)fieldInfo.GetValue(null) == uuid)
				{
					Attribute customAttribute = fieldInfo.GetCustomAttribute(typeof(BluetoothUtiAttribute));
					if (customAttribute != null)
					{
						return (includeNamespace ? "org.bluetooth.characteristic." : string.Empty) + ((BluetoothUtiAttribute)customAttribute).Uti;
					}
					return string.Empty;
				}
			}
		}
		return string.Empty;
	}
}
[DebuggerDisplay("{Uuid} (Descriptor)")]
public sealed class GattDescriptor
{
	private GattDescriptor _descriptor;

	public GattCharacteristic Characteristic { get; private set; }

	public BluetoothUuid Uuid => GetUuid();

	public byte[] Value => PlatformGetValue();

	internal GattDescriptor(GattCharacteristic characteristic)
	{
		Characteristic = characteristic;
	}

	public Task<byte[]> ReadValueAsync()
	{
		return PlatformReadValue();
	}

	public Task WriteValueAsync(byte[] value)
	{
		return PlatformWriteValue(value);
	}

	internal GattDescriptor(GattCharacteristic characteristic, GattDescriptor descriptor)
		: this(characteristic)
	{
		_descriptor = descriptor;
	}

	public static implicit operator GattDescriptor(GattDescriptor descriptor)
	{
		return descriptor._descriptor;
	}

	private Guid GetUuid()
	{
		return _descriptor.Uuid;
	}

	private byte[] PlatformGetValue()
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		GattReadResult results = _descriptor.ReadValueAsync((BluetoothCacheMode)0).GetResults();
		if ((int)results.Status == 0)
		{
			return WindowsRuntimeBufferExtensions.ToArray(results.Value);
		}
		return null;
	}

	private async Task<byte[]> PlatformReadValue()
	{
		GattReadResult val = await WindowsRuntimeSystemExtensions.AsTask<GattReadResult>(_descriptor.ReadValueAsync((BluetoothCacheMode)1)).ConfigureAwait(continueOnCapturedContext: false);
		if ((int)val.Status == 0)
		{
			return WindowsRuntimeBufferExtensions.ToArray(val.Value);
		}
		return null;
	}

	private async Task PlatformWriteValue(byte[] value)
	{
		TaskAwaiter<GattCommunicationStatus> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattCommunicationStatus>(_descriptor.WriteValueAsync(WindowsRuntimeBufferExtensions.AsBuffer(value)));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattCommunicationStatus> taskAwaiter2 = default(TaskAwaiter<GattCommunicationStatus>);
			taskAwaiter = taskAwaiter2;
		}
		taskAwaiter.GetResult();
	}
}
[BluetoothUti("org.bluetooth.descriptor")]
public static class GattDescriptorUuids
{
	internal const string Namespace = "org.bluetooth.descriptor";

	[BluetoothUti("gatt.characteristic_aggregate_format")]
	public static readonly BluetoothUuid CharacteristicAggregateFormat = (ushort)10501;

	[BluetoothUti("gatt.characteristic_extended_properties")]
	public static readonly BluetoothUuid CharacteristicExtendedProperties = (ushort)10496;

	[BluetoothUti("gatt.characteristic_presentation_format")]
	public static readonly BluetoothUuid CharacteristicPresentationFormat = (ushort)10500;

	[BluetoothUti("gatt.characteristic_user_description")]
	public static readonly BluetoothUuid CharacteristicUserDescription = (ushort)10497;

	[BluetoothUti("gatt.client_characteristic_configuration")]
	public static readonly BluetoothUuid ClientCharacteristicConfiguration = (ushort)10498;

	[BluetoothUti("es_configuration")]
	public static readonly BluetoothUuid EnvironmentalSensingConfiguration = (ushort)10507;

	[BluetoothUti("es_measurement")]
	public static readonly BluetoothUuid EnvironmentalSensingMeasurement = (ushort)10508;

	[BluetoothUti("es_trigger_setting")]
	public static readonly BluetoothUuid EnvironmentalSensingTriggerSetting = (ushort)10509;

	[BluetoothUti("external_report_reference")]
	public static readonly BluetoothUuid EnvironmentalSensingReportReference = (ushort)10503;

	[BluetoothUti("number_of_digitals")]
	public static readonly BluetoothUuid NumberOfDigitals = (ushort)10505;

	[BluetoothUti("report_reference")]
	public static readonly BluetoothUuid ReportReference = (ushort)10504;

	[BluetoothUti("gatt.server_characteristic_configuration")]
	public static readonly BluetoothUuid ServerCharacteristicConfiguration = (ushort)10499;

	[BluetoothUti("time_trigger_setting")]
	public static readonly BluetoothUuid TimeTriggerSetting = (ushort)10510;

	[BluetoothUti("valid_range")]
	public static readonly BluetoothUuid ValidRange = (ushort)10502;

	[BluetoothUti("value_trigger_setting")]
	public static readonly BluetoothUuid ValueTriggerSetting = (ushort)10506;

	public static BluetoothUuid FromBluetoothUti(string bluetoothUti)
	{
		string text = bluetoothUti.ToLower();
		if (text.StartsWith("org.bluetooth.descriptor"))
		{
			text = text.Replace("org.bluetooth.descriptor.", string.Empty);
		}
		FieldInfo[] fields = typeof(GattDescriptorUuids).GetFields(BindingFlags.Static | BindingFlags.Public);
		FieldInfo[] array = fields;
		foreach (FieldInfo fieldInfo in array)
		{
			Attribute customAttribute = fieldInfo.GetCustomAttribute(typeof(BluetoothUtiAttribute));
			if (customAttribute != null && ((BluetoothUtiAttribute)customAttribute).Uti == text)
			{
				return (BluetoothUuid)fieldInfo.GetValue(null);
			}
		}
		return default(BluetoothUuid);
	}

	public static string GetDescriptorName(BluetoothUuid uuid, bool includeNamespace = false)
	{
		ushort? num = BluetoothUuid.TryGetShortId(uuid);
		if (num.HasValue && (num.Value & 0xFF00) == 10496)
		{
			FieldInfo[] fields = typeof(GattDescriptorUuids).GetFields(BindingFlags.Static | BindingFlags.Public);
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				if ((BluetoothUuid)fieldInfo.GetValue(null) == uuid)
				{
					Attribute customAttribute = fieldInfo.GetCustomAttribute(typeof(BluetoothUtiAttribute));
					if (customAttribute != null)
					{
						return (includeNamespace ? "org.bluetooth.descriptor." : string.Empty) + ((BluetoothUtiAttribute)customAttribute).Uti;
					}
					return string.Empty;
				}
			}
		}
		return string.Empty;
	}
}
[DebuggerDisplay("{Uuid} (Service)")]
public sealed class GattService
{
	private readonly GattDeviceService _service;

	private readonly bool _isPrimary;

	public BluetoothDevice Device { get; private set; }

	public BluetoothUuid Uuid => GetUuid();

	public bool IsPrimary => GetIsPrimary();

	internal GattService(BluetoothDevice device)
	{
		Device = device;
	}

	public Task<GattCharacteristic> GetCharacteristicAsync(BluetoothUuid characteristic)
	{
		return PlatformGetCharacteristic(characteristic);
	}

	public Task<IReadOnlyList<GattCharacteristic>> GetCharacteristicsAsync()
	{
		return PlatformGetCharacteristics();
	}

	public Task<GattService> GetIncludedServiceAsync(BluetoothUuid service)
	{
		return PlatformGetIncludedServiceAsync(service);
	}

	public Task<IReadOnlyList<GattService>> GetIncludedServicesAsync()
	{
		return PlatformGetIncludedServicesAsync();
	}

	internal GattService(BluetoothDevice device, GattDeviceService service, bool isPrimary)
		: this(device)
	{
		_service = service;
		_isPrimary = isPrimary;
		device.AddDisposableObject(this, (IDisposable)service);
	}

	public static implicit operator GattDeviceService(GattService service)
	{
		return service._service;
	}

	public static implicit operator GattService(GattDeviceService service)
	{
		return new GattService(service.Device, service, isPrimary: false);
	}

	private async Task<bool> OpenAsync()
	{
		TaskAwaiter<GattOpenStatus> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattOpenStatus>(_service.OpenAsync((GattSharingMode)3));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattOpenStatus> taskAwaiter2 = default(TaskAwaiter<GattOpenStatus>);
			taskAwaiter = taskAwaiter2;
		}
		GattOpenStatus result = taskAwaiter.GetResult();
		return IsOpenSuccess(result);
	}

	private static bool IsOpenSuccess(GattOpenStatus status)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0004: Invalid comparison between Unknown and I4
		if (status - 1 <= 1)
		{
			return true;
		}
		return false;
	}

	private async Task<GattCharacteristic> PlatformGetCharacteristic(BluetoothUuid characteristic)
	{
		if (!(await OpenAsync()))
		{
			return null;
		}
		TaskAwaiter<GattCharacteristicsResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattCharacteristicsResult>(_service.GetCharacteristicsForUuidAsync((Guid)characteristic, (BluetoothCacheMode)0));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattCharacteristicsResult> taskAwaiter2 = default(TaskAwaiter<GattCharacteristicsResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattCharacteristicsResult result = taskAwaiter.GetResult();
		GattCharacteristicsResult val = result;
		if ((int)val.Status == 0 && val.Characteristics.Count > 0)
		{
			return new GattCharacteristic(this, val.Characteristics[0]);
		}
		return null;
	}

	private async Task<IReadOnlyList<GattCharacteristic>> PlatformGetCharacteristics()
	{
		if (!(await OpenAsync()))
		{
			return null;
		}
		List<GattCharacteristic> characteristics = new List<GattCharacteristic>();
		TaskAwaiter<GattCharacteristicsResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattCharacteristicsResult>(_service.GetCharacteristicsAsync((BluetoothCacheMode)0));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattCharacteristicsResult> taskAwaiter2 = default(TaskAwaiter<GattCharacteristicsResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattCharacteristicsResult result = taskAwaiter.GetResult();
		GattCharacteristicsResult val = result;
		if ((int)val.Status == 0)
		{
			foreach (GattCharacteristic characteristic in val.Characteristics)
			{
				characteristics.Add(new GattCharacteristic(this, characteristic));
			}
		}
		return characteristics.AsReadOnly();
	}

	private async Task<GattService> PlatformGetIncludedServiceAsync(BluetoothUuid service)
	{
		if (!(await OpenAsync()))
		{
			return null;
		}
		TaskAwaiter<GattDeviceServicesResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattDeviceServicesResult>(_service.GetIncludedServicesForUuidAsync((Guid)service, (BluetoothCacheMode)0));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattDeviceServicesResult> taskAwaiter2 = default(TaskAwaiter<GattDeviceServicesResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattDeviceServicesResult result = taskAwaiter.GetResult();
		GattDeviceServicesResult val = result;
		if ((int)val.Status == 0)
		{
			return new GattService(Device, val.Services[0], isPrimary: false);
		}
		return null;
	}

	private async Task<IReadOnlyList<GattService>> PlatformGetIncludedServicesAsync()
	{
		if (!(await OpenAsync()))
		{
			return null;
		}
		List<GattService> services = new List<GattService>();
		TaskAwaiter<GattDeviceServicesResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattDeviceServicesResult>(_service.GetIncludedServicesAsync());
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattDeviceServicesResult> taskAwaiter2 = default(TaskAwaiter<GattDeviceServicesResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattDeviceServicesResult result = taskAwaiter.GetResult();
		GattDeviceServicesResult val = result;
		if ((int)val.Status == 0)
		{
			foreach (GattDeviceService service in val.Services)
			{
				services.Add(new GattService(Device, service, isPrimary: false));
			}
			return services;
		}
		return null;
	}

	private BluetoothUuid GetUuid()
	{
		return _service.Uuid;
	}

	private bool GetIsPrimary()
	{
		return _isPrimary;
	}
}
[BluetoothUti("org.bluetooth.service")]
public static class GattServiceUuids
{
	internal const string Namespace = "org.bluetooth.service";

	[BluetoothUti("generic_access")]
	public static readonly BluetoothUuid GenericAccess = (ushort)6144;

	[BluetoothUti("alert_notification")]
	public static readonly BluetoothUuid AlertNotification = (ushort)6161;

	[BluetoothUti("automation_io")]
	public static readonly BluetoothUuid AutomationIO = (ushort)6165;

	[BluetoothUti("battery_service")]
	public static readonly BluetoothUuid Battery = (ushort)6159;

	[BluetoothUti("binary_sensor")]
	public static readonly BluetoothUuid BinarySensor = (ushort)6203;

	[BluetoothUti("blood_pressure")]
	public static readonly BluetoothUuid BloodPressure = (ushort)6160;

	[BluetoothUti("body_composition")]
	public static readonly BluetoothUuid BodyComposition = (ushort)6171;

	[BluetoothUti("bond_management")]
	public static readonly BluetoothUuid BondManagement = (ushort)6174;

	[BluetoothUti("continuous_glucose_monitoring")]
	public static readonly BluetoothUuid ContinuousGlucoseMonitoring = (ushort)6175;

	[BluetoothUti("current_time")]
	public static readonly BluetoothUuid CurrentTime = (ushort)6149;

	[BluetoothUti("cycling_power")]
	public static readonly BluetoothUuid CyclingPower = (ushort)6168;

	[BluetoothUti("cycling_speed_and_cadence")]
	public static readonly BluetoothUuid CyclingSpeedAndCadence = (ushort)6166;

	[BluetoothUti("device_information")]
	public static readonly BluetoothUuid DeviceInformation = (ushort)6154;

	[BluetoothUti("environmental_sensing")]
	public static readonly BluetoothUuid EnvironmentalSensing = (ushort)6170;

	[BluetoothUti("fitness_machine")]
	public static readonly BluetoothUuid FitnessMachine = (ushort)6182;

	[BluetoothUti("generic_attribute")]
	public static readonly BluetoothUuid GenericAttribute = (ushort)6145;

	[BluetoothUti("glucose")]
	public static readonly BluetoothUuid Glucose = (ushort)6152;

	[BluetoothUti("health_thermometer")]
	public static readonly BluetoothUuid HealthThermometer = (ushort)6153;

	[BluetoothUti("heart_rate")]
	public static readonly BluetoothUuid HeartRate = (ushort)6157;

	[BluetoothUti("http_proxy")]
	public static readonly BluetoothUuid HttpProxy = (ushort)6179;

	[BluetoothUti("human_interface_device")]
	public static readonly BluetoothUuid HumanInterfaceDevice = (ushort)6162;

	[BluetoothUti("immediate_alert")]
	public static readonly BluetoothUuid ImmediateAlert = (ushort)6146;

	[BluetoothUti("indoor_positioning")]
	public static readonly BluetoothUuid IndoorPositioning = (ushort)6177;

	[BluetoothUti("insulin_delivery")]
	public static readonly BluetoothUuid InsulinDelivery = (ushort)6202;

	[BluetoothUti("internet_protocol_support")]
	public static readonly BluetoothUuid InternetProtocolSupport = (ushort)6176;

	[BluetoothUti("link_loss")]
	public static readonly BluetoothUuid LinkLoss = (ushort)6147;

	[BluetoothUti("location_and_navigation")]
	public static readonly BluetoothUuid LocationAndNavigation = (ushort)6169;

	[BluetoothUti("mesh_provisioning")]
	public static readonly BluetoothUuid MeshProvisioning = (ushort)6183;

	[BluetoothUti("mesh_proxy")]
	public static readonly BluetoothUuid MeshProxy = (ushort)6184;

	[BluetoothUti("next_dst_change")]
	public static readonly BluetoothUuid NextDstChange = (ushort)6151;

	[BluetoothUti("object_transfer")]
	public static readonly BluetoothUuid ObjectTransfer = (ushort)6181;

	[BluetoothUti("phone_alert_status")]
	public static readonly BluetoothUuid PhoneAlertStatus = (ushort)6158;

	[BluetoothUti("pulse_oximeter")]
	public static readonly BluetoothUuid PulseOximeter = (ushort)6178;

	[BluetoothUti("reconnection_configuration")]
	public static readonly BluetoothUuid ReconnectionConfiguration = (ushort)6185;

	[BluetoothUti("reference_time_update")]
	public static readonly BluetoothUuid ReferenceTimeUpdate = (ushort)6150;

	[BluetoothUti("running_speed_and_cadence")]
	public static readonly BluetoothUuid RunningSpeedAndCadence = (ushort)6164;

	[BluetoothUti("scan_parameters")]
	public static readonly BluetoothUuid ScanParameters = (ushort)6163;

	[BluetoothUti("transport_discovery")]
	public static readonly BluetoothUuid TransportDiscovery = (ushort)6180;

	[BluetoothUti("tx_power")]
	public static readonly BluetoothUuid TxPower = (ushort)6148;

	[BluetoothUti("user_data")]
	public static readonly BluetoothUuid UserData = (ushort)6172;

	[BluetoothUti("weight_scale")]
	public static readonly BluetoothUuid WeightScale = (ushort)6173;

	public static BluetoothUuid FromBluetoothUti(string bluetoothUti)
	{
		string text = bluetoothUti.ToLower();
		if (text.StartsWith("org.bluetooth.service"))
		{
			text = text.Substring(text.LastIndexOf("."));
		}
		FieldInfo[] fields = typeof(GattServiceUuids).GetFields(BindingFlags.Static | BindingFlags.Public);
		FieldInfo[] array = fields;
		foreach (FieldInfo fieldInfo in array)
		{
			Attribute customAttribute = fieldInfo.GetCustomAttribute(typeof(BluetoothUtiAttribute));
			if (customAttribute != null && ((BluetoothUtiAttribute)customAttribute).Uti == text)
			{
				return (BluetoothUuid)fieldInfo.GetValue(null);
			}
		}
		return default(BluetoothUuid);
	}

	public static string GetServiceName(BluetoothUuid uuid, bool includeNamespace = false)
	{
		ushort? num = BluetoothUuid.TryGetShortId(uuid);
		if (num.HasValue && (num.Value & 0xFF00) == 6144)
		{
			FieldInfo[] fields = typeof(GattServiceUuids).GetFields(BindingFlags.Static | BindingFlags.Public);
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				if ((BluetoothUuid)fieldInfo.GetValue(null) == uuid)
				{
					Attribute customAttribute = fieldInfo.GetCustomAttribute(typeof(BluetoothUtiAttribute));
					if (customAttribute != null)
					{
						return (includeNamespace ? "org.bluetooth.service." : string.Empty) + ((BluetoothUtiAttribute)customAttribute).Uti;
					}
					return string.Empty;
				}
			}
		}
		return string.Empty;
	}
}
public sealed class RemoteGattServer
{
	[DebuggerBrowsable(DebuggerBrowsableState.Never)]
	private BluetoothPhy _preferredPhy = BluetoothPhy.Le1m;

	public bool AutoConnect { get; set; }

	public BluetoothDevice Device { get; private set; }

	[Obsolete("Use IsConnected instead", true)]
	public bool Connected => IsConnected;

	public bool IsConnected => GetConnected();

	public int Mtu { get; internal set; }

	public BluetoothPhy PreferredPhy
	{
		get
		{
			return _preferredPhy;
		}
		set
		{
			_preferredPhy = value;
			PlatformSetPreferredPhy(value);
		}
	}

	internal RemoteGattServer(BluetoothDevice device)
	{
		Device = device;
		PlatformInit();
	}

	private void Device_GattServerDisconnected(object sender, EventArgs e)
	{
		Device.OnGattServerDisconnected();
	}

	public Task ConnectAsync()
	{
		return PlatformConnect();
	}

	public void Disconnect()
	{
		PlatformDisconnect();
		Device.OnGattServerDisconnected();
		PlatformCleanup();
	}

	public Task<GattService> GetPrimaryServiceAsync(BluetoothUuid service)
	{
		return PlatformGetPrimaryService(service);
	}

	public Task<List<GattService>> GetPrimaryServicesAsync(BluetoothUuid? service = null)
	{
		return PlatformGetPrimaryServices(service);
	}

	public Task<short> ReadRssi()
	{
		return PlatformReadRssi();
	}

	private void PlatformInit()
	{
		Device.NativeDevice.ConnectionStatusChanged += NativeDevice_ConnectionStatusChanged;
	}

	private void NativeDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		if ((int)sender.ConnectionStatus == 0)
		{
			Device.OnGattServerDisconnected();
		}
	}

	private bool GetConnected()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Invalid comparison between Unknown and I4
		if (Device.IsDisposedItem(Device))
		{
			return false;
		}
		return (int)Device.NativeDevice.ConnectionStatus == 1;
	}

	private async Task PlatformConnect()
	{
		if (await Device.CreateNativeInstance())
		{
			PlatformInit();
		}
		TaskAwaiter<DeviceAccessStatus> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<DeviceAccessStatus>(Device.NativeDevice.RequestAccessAsync());
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<DeviceAccessStatus> taskAwaiter2 = default(TaskAwaiter<DeviceAccessStatus>);
			taskAwaiter = taskAwaiter2;
		}
		DeviceAccessStatus result = taskAwaiter.GetResult();
		DeviceAccessStatus val = result;
		if ((int)val == 1)
		{
			Device.LastKnownAddress = Device.NativeDevice.BluetoothAddress;
			TaskAwaiter<GattSession> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<GattSession>(GattSession.FromDeviceIdAsync(Device.NativeDevice.BluetoothDeviceId));
			if (!taskAwaiter3.IsCompleted)
			{
				await taskAwaiter3;
				TaskAwaiter<GattSession> taskAwaiter4 = default(TaskAwaiter<GattSession>);
				taskAwaiter3 = taskAwaiter4;
			}
			GattSession result2 = taskAwaiter3.GetResult();
			GattSession val2 = result2;
			if (val2 != (GattSession)null)
			{
				Mtu = val2.MaxPduSize;
				val2.MaxPduSizeChanged += Session_MaxPduSizeChanged;
				Device.AddDisposableObject(this, (IDisposable)val2);
				val2.MaintainConnection = true;
			}
			TaskAwaiter<GattDeviceServicesResult> taskAwaiter5 = WindowsRuntimeSystemExtensions.GetAwaiter<GattDeviceServicesResult>(Device.NativeDevice.GetGattServicesAsync((BluetoothCacheMode)1));
			if (!taskAwaiter5.IsCompleted)
			{
				await taskAwaiter5;
				TaskAwaiter<GattDeviceServicesResult> taskAwaiter6 = default(TaskAwaiter<GattDeviceServicesResult>);
				taskAwaiter5 = taskAwaiter6;
			}
			GattDeviceServicesResult result3 = taskAwaiter5.GetResult();
			GattDeviceServicesResult val3 = result3;
			{
				foreach (GattDeviceService service in val3.Services)
				{
					service.Dispose();
				}
				return;
			}
		}
		throw new SecurityException();
	}

	private void Session_MaxPduSizeChanged(GattSession sender, object args)
	{
		Mtu = sender.MaxPduSize;
	}

	private void PlatformDisconnect()
	{
	}

	private void PlatformCleanup()
	{
		if (Device.NativeDisposeList.TryGetValue(Device.GetHashCode(), out var value) && value != null)
		{
			Device.NativeDevice.ConnectionStatusChanged -= NativeDevice_ConnectionStatusChanged;
			Device.DisposeAllNativeObjects();
		}
	}

	private async Task<GattService> PlatformGetPrimaryService(BluetoothUuid service)
	{
		if (await Device.CreateNativeInstance())
		{
			PlatformInit();
		}
		TaskAwaiter<GattDeviceServicesResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattDeviceServicesResult>(Device.NativeDevice.GetGattServicesForUuidAsync((Guid)service, (BluetoothCacheMode)1));
		if (!taskAwaiter.IsCompleted)
		{
			await taskAwaiter;
			TaskAwaiter<GattDeviceServicesResult> taskAwaiter2 = default(TaskAwaiter<GattDeviceServicesResult>);
			taskAwaiter = taskAwaiter2;
		}
		GattDeviceServicesResult result = taskAwaiter.GetResult();
		GattDeviceServicesResult val = result;
		if (val == (GattDeviceServicesResult)null || val.Services.Count == 0)
		{
			return null;
		}
		return new GattService(Device, val.Services[0], isPrimary: true);
	}

	private async Task<List<GattService>> PlatformGetPrimaryServices(BluetoothUuid? service)
	{
		if (await Device.CreateNativeInstance())
		{
			PlatformInit();
		}
		List<GattService> services = new List<GattService>();
		BluetoothLEDevice nativeDevice = Device.NativeDevice;
		BluetoothCacheMode val = (BluetoothCacheMode)((!nativeDevice.DeviceInformation.Pairing.IsPaired) ? 1 : 0);
		TaskAwaiter<GattDeviceServicesResult> taskAwaiter2 = default(TaskAwaiter<GattDeviceServicesResult>);
		GattDeviceServicesResult val2;
		if (!service.HasValue)
		{
			TaskAwaiter<GattDeviceServicesResult> taskAwaiter = WindowsRuntimeSystemExtensions.GetAwaiter<GattDeviceServicesResult>(nativeDevice.GetGattServicesAsync(val));
			if (!taskAwaiter.IsCompleted)
			{
				await taskAwaiter;
				taskAwaiter = taskAwaiter2;
			}
			GattDeviceServicesResult result = taskAwaiter.GetResult();
			val2 = result;
		}
		else
		{
			TaskAwaiter<GattDeviceServicesResult> taskAwaiter3 = WindowsRuntimeSystemExtensions.GetAwaiter<GattDeviceServicesResult>(nativeDevice.GetGattServicesForUuidAsync((Guid)service.Value, val));
			if (!taskAwaiter3.IsCompleted)
			{
				await taskAwaiter3;
				taskAwaiter3 = taskAwaiter2;
			}
			GattDeviceServicesResult result2 = taskAwaiter3.GetResult();
			val2 = result2;
		}
		if (val2 != (GattDeviceServicesResult)null && val2.Services.Count > 0)
		{
			foreach (GattDeviceService service2 in val2.Services)
			{
				services.Add(new GattService(Device, service2, isPrimary: true));
			}
		}
		return services;
	}

	private Task<short> PlatformReadRssi()
	{
		return Task.FromResult((short)0);
	}

	private void PlatformSetPreferredPhy(BluetoothPhy phy)
	{
	}
}
public sealed class RequestDeviceOptions
{
	public IList<BluetoothLEScanFilter> Filters { get; } = new List<BluetoothLEScanFilter>();


	public IList<Guid> OptionalServices { get; } = new List<Guid>();


	public bool AcceptAllDevices { get; set; }
}