public static string GetDeviceName(this BluetoothLEAdvertisement adv) { var data = adv.GetSectionDataOrNull(AdvertisementRecordType.CompleteLocalName); if (data == null) { return(adv.LocalName); } var name = Encoding.UTF8.GetString(data); return(name); }
public Advertiser() { var manufacturerData = new BluetoothLEManufacturerData(ManufacturerId, (new byte[] { 0x12, 0x34 }).AsBuffer()); var advertisment = new BluetoothLEAdvertisement(); var data = new BluetoothLEAdvertisementDataSection {Data = SolicitationData.AsBuffer()}; advertisment.DataSections.Add(data); advertisment.ManufacturerData.Add(manufacturerData); this._publisher = new BluetoothLEAdvertisementPublisher(advertisment); }
internal BluetoothAdvertisingEvent(BluetoothLEAdvertisementReceivedEventArgs args) { _rssi = args.RawSignalStrengthInDBm; _txPower = args.TransmitPowerLevelInDBm.HasValue ? (sbyte)args.TransmitPowerLevelInDBm.Value : (sbyte)0; /*var sections = args.Advertisement.GetSectionsByType(0xA); * if(sections != null && sections.Count > 0) * { * var array = sections[0].Data.ToArray(); * * _txPower = sections[0].Data.GetByte(0); * }*/ var appearanceSections = args.Advertisement.GetSectionsByType(0x19); if (appearanceSections != null && appearanceSections.Count > 0) { var appearanceArray = appearanceSections[0].Data.ToArray(); _appearance = BitConverter.ToUInt16(appearanceArray, 0); } // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice.frombluetoothaddressasync?view=winrt-20348 // If there are no other pending request, and the remote device is unreachable, // then the system will wait for seven (7) seconds before it times out. If // there are other pending requests, then each of the requests in the queue can // take seven (7) seconds to process, so the further yours is toward the back // of the queue, the longer you'll wait. IAsyncOperation <BluetoothLEDevice> deviceAsync = BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress, args.BluetoothAddressType); // https://github.com/inthehand/32feet/issues/96 // Wait some time for this task to complete otherwise the event will fire // before the 'Device' property as been set. if (deviceAsync.AsTask().Wait(7000)) { Device = deviceAsync.GetResults(); } else { try { // The documents state that it is not possible to cancel 'FromBluetoothAddressAsync' // so mask any exceptions before calling this. deviceAsync.Cancel(); } catch { } } _advertisement = args.Advertisement; }
// See https://webbluetoothcg.github.io/web-bluetooth/#matches-a-filter public bool Matches(BluetoothLEAdvertisement advertisement) { if (!string.IsNullOrWhiteSpace(Name) && (advertisement.LocalName != Name)) { return(false); } if (!string.IsNullOrWhiteSpace(NamePrefix) && (!advertisement.LocalName.StartsWith(NamePrefix))) { return(false); } return(RequiredServices == null || RequiredServices.All(service => advertisement.ServiceUuids.Contains(service))); }
public Advertiser() { var manufacturerData = new BluetoothLEManufacturerData(ManufacturerId, (new byte[] { 0x12, 0x34 }).AsBuffer()); var advertisment = new BluetoothLEAdvertisement(); var data = new BluetoothLEAdvertisementDataSection { Data = SolicitationData.AsBuffer() }; advertisment.DataSections.Add(data); advertisment.ManufacturerData.Add(manufacturerData); this._publisher = new BluetoothLEAdvertisementPublisher(advertisment); }
private void CopyManufacturerData(BluetoothLEAdvertisement adv) { var manufacturer = adv.ManufacturerData; foreach (var data in manufacturer) { var destination = new byte[data.Data.Length]; data.Data.CopyTo(destination); _advertisementPackage.Advertisement.ManufacturerData.Add(new BluetoothLEManufacturerData { Data = destination.AsBuffer(), CompanyId = data.CompanyId }); } }
private void CopyDataSection(BluetoothLEAdvertisement adv) { var dataSection = adv.DataSections; foreach (var advertisementDataSection in dataSection) { var destination = new byte[advertisementDataSection.Data.Length]; advertisementDataSection.Data.CopyTo(destination); _advertisementPackage.Advertisement.DataSections.Add(new BluetoothLEAdvertisementDataSection { Data = destination.AsBuffer(), DataType = advertisementDataSection.DataType }); } }
/// <summary> /// Parses a given advertisement for various stored properties /// Currently only parses the manufacturer specific data /// </summary> /// <param name="adv">The advertisement to parse</param> /// <returns>List of generic advertisement records</returns> public static List <AdvertisementRecord> ParseAdvertisementData(BluetoothLEAdvertisement adv) { var advList = adv.DataSections; var records = new List <AdvertisementRecord>(); foreach (var data in advList) { var type = data.DataType; if (type == BluetoothLEAdvertisementDataTypes.ManufacturerSpecificData) { records.Add(new AdvertisementRecord(AdvertisementRecordType.ManufacturerSpecificData, data.Data.ToArray())); } //TODO: add more advertisement record types to parse } return(records); }
public AdvertiseObserver() { advertise = new BluetoothLEAdvertisement(); advertise.ServiceUuids.Add(Profiles.Services.Button); advertiseFilter = new BluetoothLEAdvertisementFilter() { Advertisement = advertise }; advertiseWatcher = new BluetoothLEAdvertisementWatcher() { AdvertisementFilter = advertiseFilter }; advertiseWatcher.SignalStrengthFilter.SamplingInterval = interval; advertiseWatcher.Received += OnAdvertisementReceived; advertiseSubject = new Subject <BluetoothLEAdvertisementReceivedEventArgs>(); }
public static iBeaconData iBeaconParseAdvertisement(this BluetoothLEAdvertisement Advertisment, short RawSignalStrengthInDBm) { //test string manufacturerData16String = String.Empty; if (Advertisment.LocalName.Contains("HTC")) { foreach (var adv in Advertisment.ManufacturerData) { var bytes = adv.Data.ToArray(); foreach (var oo in bytes) { manufacturerData16String += oo.ToString("X"); } } } iBeaconData beacon = null; foreach (var adv in Advertisment.ManufacturerData) { if (adv.CompanyId == 76) //Apple { var bytes = adv.Data.ToArray(); if (bytes[0] == 0x02 && bytes[1] == 0x15 && bytes.Length == 23) { //iBeacon Data beacon = new iBeaconData(); //beacon.UUID =new Guid(bytes.Skip(2).Take(16).ToArray()); beacon.UUID = ToLittleEndianFormattedUuidString(bytes.Skip(2).Take(16).ToArray()); beacon.Major = BitConverter.ToUInt16(bytes.Skip(18).Take(2).Reverse().ToArray(), 0); beacon.Minor = BitConverter.ToUInt16(bytes.Skip(20).Take(2).Reverse().ToArray(), 0); beacon.TxPower = (short)(sbyte)bytes[22]; beacon.Rssi = RawSignalStrengthInDBm; //Estimated value //Read this article http://developer.radiusnetworks.com/2014/12/04/fundamentals-of-beacon-ranging.html beacon.Distance = CalculateDistance(beacon.TxPower, RawSignalStrengthInDBm); Debug.WriteLine("UUID: " + beacon.UUID.ToString() + " Major: " + beacon.Major + " Minor:" + beacon.Minor + " Power: " + beacon.TxPower + " Rssi: " + RawSignalStrengthInDBm + " Distance:" + beacon.Distance); } } } return(beacon); }
public BleDeviceAdvertisement(BluetoothLEAdvertisement advertisement, ulong address, int rssi) { this.Advertisement = advertisement; this.Address = address; this.Rssi = rssi; var manufacturerData = this.Advertisement.GetManufacturerDataByCompanyId(0x00fe).SingleOrDefault(); if (manufacturerData != null) { var buffer = new byte[4]; manufacturerData.Data.CopyTo(buffer); this.Temperature = BitConverter.ToInt32(buffer, 0); } else { this.Temperature = float.NaN; } }
/// <summary> /// Convert the Windows specific Bluetooth LE advertisment to the universal cross-platform structure /// used by the Universal Beacon Library. /// </summary> /// <param name="convertBleAdvertisment">Windows Bluetooth LE advertisment to convert to cross-platform format.</param> /// <returns>Packet converted to cross-platform format.</returns> public static BLEAdvertisement ToUniversalAdvertisement(this BluetoothLEAdvertisement convertBleAdvertisment) { if (convertBleAdvertisment == null) { return(null); } var result = new BLEAdvertisement { LocalName = convertBleAdvertisment.LocalName }; result.ServiceUuids.AddRange(convertBleAdvertisment.ServiceUuids); if (convertBleAdvertisment.DataSections != null) { foreach (var curDataSection in convertBleAdvertisment.DataSections) { var data = new BLEAdvertisementDataSection { DataType = curDataSection.DataType, Data = curDataSection.Data.ToArray() }; result.DataSections.Add(data); } } if (convertBleAdvertisment.ManufacturerData != null) { foreach (var curManufacturerData in convertBleAdvertisment.ManufacturerData) { var data = new BLEManufacturerData { CompanyId = curManufacturerData.CompanyId, Data = curManufacturerData.Data.ToArray() }; result.ManufacturerData.Add(data); } } return(result); }
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { BluetoothLEAdvertisement advert = args.Advertisement; if (advert == null) { return; } if (advert.ManufacturerData.Count > 0) { var temp = ParseAdvertisementBuffer(advert.ManufacturerData[0].Data); Debug.WriteLine("received - " + "rssi: " + args.RawSignalStrengthInDBm.ToString() + " | data: " + printBytes(temp)); if (args.RawSignalStrengthInDBm > -50) { Infected = true; } } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { await InitializeCameraAsync(); // Create a watcher to find a BLE Device with name "corten" or "Nordic_HRM" //TODO: Make a filter with the Manufacturer Data/Device ID, not a LocalName string BluetoothLEAdvertisement _bleAdv1 = new BluetoothLEAdvertisement(); _bleAdv1.LocalName = "corten"; BluetoothLEAdvertisementFilter _bleAdvFilter1 = new BluetoothLEAdvertisementFilter(); _bleAdvFilter1.Advertisement = _bleAdv1; bleWatch1 = new BluetoothLEAdvertisementWatcher(_bleAdvFilter1); bleWatch1.Received += BLEWatcher_Received; bleWatch1.Stopped += BLEWatcher_Stopped; bleWatch1.Start(); BluetoothLEAdvertisement _bleAdv2 = new BluetoothLEAdvertisement(); _bleAdv2.LocalName = "Nordic_HRM"; BluetoothLEAdvertisementFilter _bleAdvFilter2 = new BluetoothLEAdvertisementFilter(); _bleAdvFilter2.Advertisement = _bleAdv2; bleWatch2 = new BluetoothLEAdvertisementWatcher(_bleAdvFilter2); bleWatch2.Received += BLEWatcher_Received; bleWatch2.Stopped += BLEWatcher_Stopped; bleWatch2.Start(); base.OnNavigatedTo(e); // +=============================================+ // | Bluetooth LE Connection Pop-Up Selection | // +=============================================+ // // //DevicePicker picker = new DevicePicker(); //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); //picker.Show(new Rect(0, 0, 100, 500)); }
private static void Print(BluetoothLEAdvertisement advertisement, int indent) { DebugLine("Local Name: " + advertisement.LocalName, indent); DebugLine("Service Uuids:", indent); var serviceUuids = advertisement.ServiceUuids; foreach (var serviceUuid in serviceUuids) { DebugLine($"{serviceUuid}", indent + 1); PrintService(serviceUuid, indent + 2); } DebugLine("Flags:", indent); DebugLine(advertisement.Flags == null ? "null" : $"(0x{(uint)advertisement.Flags.Value:X}) {Enum.Format(typeof(BluetoothLEAdvertisementFlags), advertisement.Flags, "g")}", indent); DebugLine("Manufacturer Data:", indent); var manufacturerDatas = advertisement.ManufacturerData; foreach (var manufacturerData in manufacturerDatas) { DebugLine($"Company Id {manufacturerData.CompanyId:X}", indent + 1); DebugLine("Data:", indent + 1); var data = manufacturerData.Data; DebugLine(CryptographicBuffer.EncodeToHexString(data), indent + 1); } DebugLine("Data Sections:", indent); var dataSections = advertisement.DataSections; foreach (var dataSection in dataSections) { DebugLine($"Date Type {dataSection.DataType:X}", indent + 1); DebugLine("Data:", indent + 1); var data = dataSection.Data; DebugLine(CryptographicBuffer.EncodeToHexString(data), indent + 1); } }
// See https://webbluetoothcg.github.io/web-bluetooth/#matches-a-filter public bool Matches(BluetoothLEAdvertisement advertisement) { if (!string.IsNullOrWhiteSpace(Name) && (advertisement.LocalName != Name)) { return(false); } if (!string.IsNullOrWhiteSpace(NamePrefix) && (!advertisement.LocalName.StartsWith(NamePrefix))) { return(false); } if (RequiredServices != null) { if (!RequiredServices.All(service => advertisement.ServiceUuids.Contains(service))) { return(false); } } if (ManufacturerData != null) { foreach (var manufacturerDataFilter in ManufacturerData) { var advertisedData = advertisement.ManufacturerData .FirstOrDefault(d => d.CompanyId == manufacturerDataFilter.Key); if (advertisedData == null) { // the peripheral doesn't advertise any data under that manufacturer ID return(false); } if (!manufacturerDataFilter.Value.Matches(advertisedData.Data)) { // the advertised data doesn't match the filter return(false); } } } return(true); }
public BLEAdvertisement(BluetoothLEAdvertisement args) { this.LocalName = args.LocalName; this.Flags = args.Flags; DataSections = new List <BLEAdvertisementDataSection>(); foreach (var dataSections in args.DataSections) { this.DataSections.Add(new BLEAdvertisementDataSection(dataSections)); } ManufacturerData = new List <BLEManufacturerData>(); foreach (var manufacturerData in args.ManufacturerData) { this.ManufacturerData.Add(new BLEManufacturerData(manufacturerData)); } this.ServiceUuids = new List <string>(); foreach (var serviceUuids in args.ServiceUuids) { this.ServiceUuids.Add(serviceUuids.ToString()); } }
public static void iBeaconSetAdvertisement(this BluetoothLEAdvertisement Advertisment, iBeaconData data) { BluetoothLEManufacturerData manufacturerData = new BluetoothLEManufacturerData(); // Set Apple as the manufacturer data manufacturerData.CompanyId = 76; var writer = new DataWriter(); writer.WriteUInt16(0x0215); //bytes 0 and 1 of the iBeacon advertisment indicator if (data != null & data.UUID != Guid.Empty) { //If UUID is null scanning for all iBeacons writer.WriteBytes(data.UUID.ToByteArray()); if (data.Major != 0) { //If Major not null searching with UUID and Major writer.WriteBytes(BitConverter.GetBytes(data.Major).Reverse().ToArray()); if (data.Minor != 0) { //If Minor not null we are looking for a specific beacon not a class of beacons writer.WriteBytes(BitConverter.GetBytes(data.Minor).Reverse().ToArray()); if (data.TxPower != 0) { writer.WriteBytes(BitConverter.GetBytes(data.TxPower)); } } } } manufacturerData.Data = writer.DetachBuffer(); Advertisment.ManufacturerData.Clear(); Advertisment.ManufacturerData.Add(manufacturerData); }
internal BluetoothAdvertisingEvent(BluetoothDevice device, byte rssi, BluetoothLEAdvertisement advertisement) : this(device) { _rssi = rssi; _advertisement = advertisement; }
public static byte[] GetManufacturerSpecificData(this BluetoothLEAdvertisement adv) => adv.GetSectionDataOrNull(BluetoothLEAdvertisementDataTypes.ManufacturerSpecificData);
public static sbyte GetTxPower(this BluetoothLEAdvertisement adv) { var data = adv.GetSectionDataOrNull(BluetoothLEAdvertisementDataTypes.TxPowerLevel); return(data == null ? (sbyte)0 : (sbyte)data[0]); }
public static ManufacturerData[] GetManufacturerSpecificData(this BluetoothLEAdvertisement adv) => adv.ManufacturerData.Select(md => new ManufacturerData(md.CompanyId, md.Data.ToArray())).ToArray();
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { BluetoothLEAdvertisement advertisement = args.Advertisement; if (tryConnecting || connected || btAddresses.Contains(args.BluetoothAddress)) { return; } btAddresses.Add(args.BluetoothAddress); Log($"New advertisement from address {args.BluetoothAddress:x} with name {advertisement.LocalName}"); tryConnecting = true; device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); if (device != null) { connected = true; tryConnecting = false; Log($" BluetoothLEDevice Name={device.Name}"); Log("-- Enumerating all BLE services, characteristics, and descriptors"); GattDeviceServicesResult getGattServices = await device.GetGattServicesAsync(); if (GattCommunicationStatus.Success == getGattServices.Status) { foreach (GattDeviceService service in getGattServices.Services) { Log($" Service {service.Uuid}"); GattCharacteristicsResult getCharacteristics = await service.GetCharacteristicsAsync(); if (GattCommunicationStatus.Success == getCharacteristics.Status) { foreach (GattCharacteristic characteristic in getCharacteristics.Characteristics) { Log($" Characteristic {characteristic.Uuid} property {characteristic.CharacteristicProperties}"); if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read)) { GattReadResult readResult = await characteristic.ReadValueAsync(); if (GattCommunicationStatus.Success == readResult.Status) { LogBuffer($" Read value 0x", readResult.Value); } else { Log($" Failed to read from readable characteristic"); } } GattDescriptorsResult getDescriptors = await characteristic.GetDescriptorsAsync(); if (GattCommunicationStatus.Success == getDescriptors.Status) { foreach (GattDescriptor descriptor in getDescriptors.Descriptors) { GattReadResult readResult = await descriptor.ReadValueAsync(); if (GattCommunicationStatus.Success == readResult.Status) { LogBuffer($" Descriptor {descriptor.Uuid} value 0x", readResult.Value); } } } else { Log($"Getting GATT descriptors failed with status {getDescriptors.Status}"); } } } else { Log($"Getting GATT characteristics failed with status {getCharacteristics.Status}"); } } foreach (GattDeviceService service in getGattServices.Services) { service.Session.Dispose(); service.Dispose(); } } else { Log($"Getting GATT services failed with status {getGattServices.Status}"); } // Dump complete, release device. device.Dispose(); device = null; connected = false; } else { tryConnecting = false; Log($" Failed to obtain BluetoothLEDevice from that advertisement"); } }
public BluetoothLEAdvertismentViewModel(BluetoothLEAdvertisementReceivedEventArgs device) { ble = device; ad = ble.Advertisement; this.Address = ble.BluetoothAddress.ToString(); }
/// <summary> /// Parses a given advertisement for various stored properties /// Currently only parses the manufacturer specific data /// </summary> /// <param name="adv">The advertisement to parse</param> /// <returns>List of generic advertisement records</returns> public static List <AdvertisementRecord> ParseAdvertisementData(BluetoothLEAdvertisement adv) { var advList = adv.DataSections; return(advList.Select(data => new AdvertisementRecord((AdvertisementRecordType)data.DataType, data.Data?.ToArray())).ToList()); }
internal Advertisement(BluetoothLEAdvertisement ad) { this.ad = ad ?? throw new ArgumentNullException(nameof(ad)); }
public UnconnectedImbleDevice(ulong address, BluetoothLEAdvertisement advertisement, short rssi) { this.Address = address; this.Advertisement = advertisement; this.Rssi = rssi; }
/// <summary> /// This function tests an adv packet to determine whether it should be matched by thie filter /// </summary> /// <param name="adv">advertising packet to test</param> /// <returns>true if the advertising packet is matched by this filter</returns> public abstract bool PacketMatches(BluetoothLEAdvertisement adv);