private IBeaconAdModel TryParseAppleIBeacon(AdStructure adStruct, string bluetoothAddress) { try { // Check length of struct // (AD_APPLE_IBEACON_SIZE - 1 additional ad struct, size & struct ID bytes from this struct) if (adStruct.Data.Length != AD_APPLE_IBEACON_SIZE - 5) { return(null); } var data = adStruct.Data; var id = data.Take(2).ToHexString(true); if (!string.Equals(id, APPLE_ID, StringComparison.OrdinalIgnoreCase)) { return(null); } if (data[2] != 0x02) { return(null); } if (data[3] != 0x15) { return(null); // length } var proximityUUID = data.Skip(4).Take(16).ToHexString(); var major = BitConverter.ToUInt16(data.Skip(20).Take(2).Reverse().ToArray(), 0); var minor = BitConverter.ToUInt16(data.Skip(22).Take(2).Reverse().ToArray(), 0); var measuredPower = (sbyte)data.Last(); var appleIBeaconData = new IBeaconAdModel { Major = major, Minor = minor, ProximityUUID = proximityUUID, MeasuredPower = measuredPower, BluetoothAddress = bluetoothAddress }; Debug.WriteLine( $"Parsed AppleIBeaconAdData: " + $"maj={appleIBeaconData.Major} " + $"min={appleIBeaconData.Minor} " + $"prox={appleIBeaconData.ProximityUUID} " + $"txpwr={appleIBeaconData.MeasuredPower}" ); return(appleIBeaconData); } catch (Exception ex) { Debug.WriteLine($"Error while parsing AppleIBeacon ad: {ex.GetBaseException().Message}"); return(null); } }
public static Dictionary <GAPAdType, AdStructure> ParseAdData(byte[] ad) { if (ad == null || ad.Length == 0) { return(null); } var adStructDict = new Dictionary <GAPAdType, AdStructure>(); var i = ad.ToList().GetEnumerator(); try { while (i.MoveNext()) { byte len = i.Current; i.MoveNext(); byte type = i.Current; // len includes type and data var data = new List <byte>(); for (var idx = 0; idx < len - 1; idx++) { i.MoveNext(); data.Add(i.Current); } var adStruct = new AdStructure { Type = (GAPAdType)Enum.ToObject(typeof(GAPAdType), type), Data = data.ToArray() }; adStructDict.Add(adStruct.Type, adStruct); } } catch (Exception) { Debug.WriteLine("Warning: Silenced an exception while parsing BLE ad - ill formatted BLE packet"); return(adStructDict); } finally { i.Dispose(); } return(adStructDict); }