private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { var ad = new Advertisement(args.Advertisement); var addr = BluetoothAddress.FromULong(args.BluetoothAddress); OnReceived(ad, addr, args.RawSignalStrengthInDBm); }
/* * Reading Data and translating to required values. */ private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { byte[] data = args.Advertisement.ManufacturerData[0].Data.ToArray(); // Dispatch the 'OnReceived' event lat = BitConverter.ToDouble(data, 0); lon = BitConverter.ToDouble(data, 8); hea = BitConverter.ToSingle(data, 16); //var eventArgs = new GPSDataReceivedEventArgs(BitConverter.ToDouble(data, 0),BitConverter.ToDouble(data,8),BitConverter.ToSingle(data,16)); //Debug.Log(BitConverter.ToDouble(data, 0)); if (!currentCoordinates.Contains(new Coordinates(lat, lon, hea))) { if (currentCoordinates.Count != 0) { coo_id++; } if (currentCoordinates.Count == 60) { currentCoordinates.Clear(); coo_id = 0; } currentCoordinates.Add(new Coordinates(lat, lon, hea)); } }
private void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv) { string name = btAdv.Advertisement.LocalName.ToString(); string address = btAdv.BluetoothAddress.ToString(); deviceList.Items.Add(address, name); }
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); if (device != null) { if (device.Name == "Galaxy A70") { _device = device; var gaUID = Guid.Parse("ffe0ecd2-3d16-4f8d-90de-e89e7fc396a5"); GattDeviceServicesResult result = await device.GetGattServicesForUuidAsync(gaUID); if (result.Status == GattCommunicationStatus.Success) { var genericAccess = result.Services.FirstOrDefault(s => s.Uuid == gaUID); var charUID = Guid.Parse("d8de624e-140f-4a22-8594-e2216b84a5f2"); var chara = await genericAccess.GetCharacteristicsForUuidAsync(charUID); if (chara.Status == GattCommunicationStatus.Success) { sender.Stop(); var c = chara.Characteristics.FirstOrDefault(x => x.Uuid == charUID); _characteristic = c; System.Timers.Timer Timer1 = new System.Timers.Timer(); Timer1.Interval = 1000; Timer1.Enabled = true; Timer1.Elapsed += Timer1_Elapsed; Timer1.Start(); } } } } }
private async void ScaleFound(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs btAdv) { Debug.WriteLine(btAdv.Advertisement.LocalName); if (!ScalesConnected && btAdv.Advertisement.LocalName == ScaleName) { await Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() => { var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress); if (device.GattServices.Any()) { ScalesConnected = true; device.ConnectionStatusChanged += (sender, args) => { if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected) { ScalesConnected = false; } }; SetupScalesStream(device); } else if (device.DeviceInformation.Pairing.CanPair && !device.DeviceInformation.Pairing.IsPaired) { await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None); } }); } }
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { await this.Dispatcher.InvokeAsync(() => { // http://sonic.blue/it/605 // Windows10デバイスでiBeaconの全データを取得する方法 iBeacon bcon = new iBeacon(args); if (bcon.UUID != null) { // iBeacon DateTimeOffset timestamp = args.Timestamp; string retBeaconData; retBeaconData = "{"; retBeaconData += string.Format("vendor:'{0}',", bcon.iBeaconVendor); retBeaconData += string.Format("uuid:'{0}',", bcon.UUID); retBeaconData += string.Format("major:{0},", bcon.Major.ToString("D")); retBeaconData += string.Format("minor:{0},", bcon.Minor.ToString("D")); retBeaconData += string.Format("measuredPower:{0},", bcon.MeasuredPower.ToString("D")); retBeaconData += string.Format("rssi:{0},", bcon.Rssi.ToString("D")); retBeaconData += string.Format("accuracy:{0},", bcon.Accuracy.ToString("F6")); retBeaconData += string.Format("proximity:'{0}',", bcon.Proximity); retBeaconData += string.Format("BluetoothAddress:'{0}',", bcon.BluetoothAddress); retBeaconData += string.Format("RawSignalStrengthInDBm:{0}", bcon.RawSignalStrengthInDBm); retBeaconData += "}"; this.textBox.Text = this.textBox.Text + timestamp.ToString("HH\\:mm\\:ss\\.fff") + ":" + retBeaconData + "\r\n"; } }); }
/// <summary> /// Analyze the received Bluetooth LE advertisement, and either add a new unique /// beacon to the list of known beacons, or update a previously known beacon /// with the new information. /// </summary> /// <param name="btAdv">Bluetooth advertisement to parse, as received from /// the Windows Bluetooth LE API.</param> public void ReceivedAdvertisement(BluetoothLEAdvertisementReceivedEventArgs btAdv) { if (btAdv == null) { return; } // Check if we already know this bluetooth address foreach (var bluetoothBeacon in BluetoothBeacons) { if (bluetoothBeacon.BluetoothAddress == btAdv.BluetoothAddress) { // We already know this beacon // Update / Add info to existing beacon bluetoothBeacon.UpdateBeacon(btAdv); return; } } // Beacon was not yet known - add it to the list. var newBeacon = new Beacon(btAdv); if (newBeacon.BeaconType != Beacon.BeaconTypeEnum.Unknown) { BluetoothBeacons.Add(newBeacon); } }
private async void DeviceDiscovered(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs advertisement) { var isNew = false; lock (this) { if (false == advertisedDevices.Contains(advertisement.BluetoothAddress)) { this.advertisedDevices.Add(advertisement.BluetoothAddress); isNew = true; } } if (true == isNew) { var device = await BluetoothLEDevice.FromBluetoothAddressAsync(advertisement.BluetoothAddress); DevicePairingKinds ceremoniesSelected = DevicePairingKinds.ConfirmOnly; DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.None; DeviceInformationCustomPairing customPairing = device.DeviceInformation.Pairing.Custom; customPairing.PairingRequested += PairingRequestedHandler; DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel); customPairing.PairingRequested -= PairingRequestedHandler; if ((result.Status == DevicePairingResultStatus.AlreadyPaired) || (result.Status == DevicePairingResultStatus.Paired)) { sender.Stop(); } } }
/// <summary> /// Received broadcasting data. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> async void BluetoothWatcher_Connected(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { // Stop all Bluetooth broadcasting or watching StopBroadcastingOrWatching(); // Get the payload of advertisement var item = args.Advertisement.GetManufacturerDataByCompanyId(0xFFFE); var advertisement = ReadFromBuffer(item.FirstOrDefault().Data); try { this._socket = new StreamSocket(); // Connect to the broadcasting peer. await this._socket.ConnectAsync( new EndpointPair( null, string.Empty, new HostName(advertisement.IP.ToString()), advertisement.Port.ToString())); // flag success in connection isConnected = true; this._connectionMadeTask.SetResult(true); } catch { this._socket.Dispose(); this._socket = null; isConnected = false; this._connectionMadeTask.SetResult(false); } }
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { var addr = CommonExts.ToHex(args.BluetoothAddress); var uuids = args.Advertisement.ServiceUuids; var manu = args.Advertisement.ManufacturerData.Select( d => d.Data.ToArray()).SelectMany(b => b).ToArray(); var data = args.Advertisement.DataSections.Select( d => d.Data.ToArray()).SelectMany(b => b).ToArray(); OnBlueEvent?.Invoke(this, new BlueEvent { TimeStamp = args.Timestamp, Flags = args.Advertisement.Flags.ToString(), Advertisement = new Advertisement { Address = addr, AddressType = AddressType.Random, RSSI = args.RawSignalStrengthInDBm, Connectable = IsConnectable(args.AdvertisementType), Name = args.Advertisement.LocalName, Services = uuids.Select(u => u.ToString()).ToArray(), ID = addr, UUID = addr, ManufacturerData = manu, ServiceData = data } }); }
private async void DeviceFound(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs btAdv) { if (!ConnectedDevices.Contains(btAdv.Advertisement.LocalName) && _devices.Contains(btAdv.Advertisement.LocalName)) { await Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() => { var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress); if (device.GattServices.Any()) { ConnectedDevices.Add(device.Name); device.ConnectionStatusChanged += async(sender, args) => { if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected) { await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { ConnectedDevices .Remove( sender .Name); }); } }; SetupWaxStream(device); } else if (device.DeviceInformation.Pairing.CanPair && !device.DeviceInformation.Pairing.IsPaired) { await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None); } }); } }
private void ParseAxaBeaconData(BluetoothLEAdvertisementReceivedEventArgs btAdv) { BeaconFrameBase beaconFrame = null; if (btAdv.Advertisement.DataSections.Any(_ => _.DataType == 9)) { var data = btAdv.Advertisement.DataSections.First(_ => _.DataType == 9).Data.ToArray(); beaconFrame = new AxaCompleteNameFrame(data); } else if (btAdv.Advertisement.DataSections.Any(_ => _.DataType == 22)) { var data = btAdv.Advertisement.DataSections.First(_ => _.DataType == 22).Data.ToArray(); beaconFrame = new AxaBatTempHumFrame(data); } if (beaconFrame != null) { var existingFrame = BeaconFrames.FirstOrDefault(_ => _.GetType() == beaconFrame.GetType()); if (existingFrame != null) { existingFrame.Update(beaconFrame); } else { BeaconFrames.Add(beaconFrame); } } }
private void ParseEddystoneData(BluetoothLEAdvertisementReceivedEventArgs btAdv) { // Parse Eddystone data foreach (var dataSection in btAdv.Advertisement.DataSections) { //Debug.WriteLine("Beacon data: " + dataSection.DataType + " = " + // BitConverter.ToString(dataSection.Data.ToArray())); //+ " (" + Encoding.UTF8.GetString(dataSection.Data.ToArray()) + ")\n"); // Relvant data of Eddystone is in data section 0x16 // Windows receives: 0x01 = 0x06 // 0x03 = 0xAA 0xFE // 0x16 = 0xAA 0xFE [type] [data] if (dataSection.DataType == 0x16) { var beaconFrame = dataSection.Data.ToArray().CreateEddystoneBeaconFrame(); if (beaconFrame == null) { continue; } var found = false; for (var i = 0; i < BeaconFrames.Count; i++) { if (BeaconFrames[i].GetType() == beaconFrame.GetType()) { var updateFrame = false; if (beaconFrame.GetType() == typeof(UnknownBeaconFrame)) { // Unknown frame - also compare eddystone type var existingEddystoneFrameType = BeaconFrames[i].Payload.GetEddystoneFrameType(); var newEddystoneFrameType = beaconFrame.Payload.GetEddystoneFrameType(); if (existingEddystoneFrameType != null && existingEddystoneFrameType == newEddystoneFrameType) { updateFrame = true; } } else { updateFrame = true; } if (updateFrame) { BeaconFrames[i].Update(beaconFrame); found = true; break; // Don't analyze any other known frames of this beacon } } } if (!found) { BeaconFrames.Add(beaconFrame); } } } }
private async void WatcherReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { // Noticed a build warning here, WatcherReceived isn't waiting on this async operation to finish. ExceptionLogger.Run(async() => { //AssertSameThreadAndContext(); GlobalCounters.IncrementAdvertisementsSeen(); var address = args.BluetoothAddress; if (_devices.ContainsKey(args.BluetoothAddress)) { return; } var device = new Device(address, GlobalCounters.IncrementDevicesConnected, () => { GlobalCounters.IncrementDevicesClosed(); _devices.Remove(address); }); _devices[address] = device; await device.Start(); }); }
private BluetoothDevice(BluetoothManager bluetoothManager, BluetoothLEAdvertisementReceivedEventArgs uwpAdvertisementReceivedEventArgs) { BluetoothManager = bluetoothManager; LatestUwpBluetoothLEAdvertisementReceivedEventArgs = uwpAdvertisementReceivedEventArgs; Name = uwpAdvertisementReceivedEventArgs.Advertisement.LocalName; Address = uwpAdvertisementReceivedEventArgs.BluetoothAddress; }
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { var manufacturerData = args.Advertisement.ManufacturerData.ToList().FirstOrDefault(c => c.CompanyId == AppleConstants.CompanyId); if (manufacturerData == null) { return; } var rawData = new byte[manufacturerData.Data.Length]; if (manufacturerData.Data.Length != AppleConstants.ManufacturerDataLenght) { return; } if (await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress) == null) { return; } using DataReader reader = DataReader.FromBuffer(manufacturerData.Data); reader.ReadBytes(rawData); char[] airpodsInfoHex = BitConverter.ToString(rawData).Split("-").SelectMany(s => s).ToArray(); _onBleStatusChanged.Invoke(airpodsInfoHex); if (!taskCompletionSource.Task.IsCompleted) { taskCompletionSource.SetResult(true); } watcher.Stop(); }
/// <summary> /// Event when new device detected /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { try { var address = args.BluetoothAddress; getDeviceAsync(address); if (device == null) { return; } if (!DevicesList.Any(c => c.Name.Equals(device.Name))) { DevicesList.Add(device); //DevicesNames.Add(device.Name); NewDevice(this, null); Console.WriteLine("Got new device: " + device.Name); } else { watcher.Stop(); } } catch (Exception) { } }
private void PrintDataSections(BluetoothLEAdvertisementReceivedEventArgs e) { // Tell the user we see an advertisement and print some properties Log.d("--------------------------------------------------------------------"); Log.d(String.Format("Advertisement:")); Log.d(String.Format(" BT_ADDR: {0} -- {1}", e.BluetoothAddress, BitConverter.ToString(BitConverter.GetBytes(e.BluetoothAddress).Reverse().ToArray()))); Log.d(String.Format(" FR_NAME: {0}", e.Advertisement.LocalName)); Log.d(String.Format(" FR_TYPE: {0}", e.AdvertisementType)); IList <BluetoothLEAdvertisementDataSection> dataSections = e.Advertisement.DataSections; if (dataSections != null && dataSections.Count > 0) { Log.d("DATA COUNT: " + dataSections.Count); foreach (BluetoothLEAdvertisementDataSection section in dataSections) { var data = new byte[section.Data.Length]; using (var reader = DataReader.FromBuffer(section.Data)) { reader.ReadBytes(data); } string manufacturerDataString = string.Format("0x{0}: {1}", section.DataType.ToString("X"), BitConverter.ToString(data)); Log.d(string.Format(" DATA({0}): {1}", data.Length, manufacturerDataString)); if (section.DataType == (byte)BleDataType.CompleteLocalName) { string name = Encoding.UTF8.GetString(data); Log.d(" NAME: " + name); } } } }
private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { if (string.IsNullOrEmpty(eventArgs.Advertisement.LocalName)) { return; } var timestamp = eventArgs.Timestamp; var advertisementType = eventArgs.AdvertisementType; var rssi = eventArgs.RawSignalStrengthInDBm; var localName = eventArgs.Advertisement.LocalName; Debug.WriteLine($"[{DateTime.Now}] [{timestamp}] [{localName}] [{rssi}] [{advertisementType}]"); lock (_locker) { var foundDevice = Devices.FirstOrDefault(d => d.BluetoothAddress == eventArgs.BluetoothAddress.ToString()); if (foundDevice != null) { foundDevice.LastSeen = timestamp.ToString(); return; } } Application.Current.Dispatcher.Invoke(() => { lock (_locker) { var device = new DeviceViewModel(eventArgs.Advertisement.LocalName, eventArgs.BluetoothAddress, timestamp); Devices.Add(device); } }); }
/// <summary> /// Tries to read proximity beacon data from the given advertisementReceivedEventArgs. /// </summary> /// <param name="advertisementReceivedEventArgs">The bluetooth advertisement message from which to read a proximity beacon message from.</param> /// <param name="beacon">The resulting proximity beacon data that can be read from the advertisement.</param> /// <param name="requestedTypes">The type(s) of proximity beacons to look for.</param> /// <returns>True when proximity beacon data can be read from the advertisement.</returns> public static bool TryReadProximityBeacon(BluetoothLEAdvertisementReceivedEventArgs advertisementReceivedEventArgs, out ProximityBeacon beacon, params ProximityBeaconType[] requestedTypes) { if (requestedTypes.Count() == 1 && requestedTypes[0] == ProximityBeaconType.Unknown) { throw new ArgumentException($"Proximity Beacon Type {nameof(ProximityBeaconType.Unknown)} cannot be parsed!"); } bool result = false; beacon = null; foreach (var parser in AvailableParsers.Where(a => requestedTypes.Contains(a.Type))) { if (parser.CanParseAdvertisement(advertisementReceivedEventArgs)) { try { beacon = parser.Parse(advertisementReceivedEventArgs); result = true; break; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } else continue; } return result; }
/// <summary> /// Event handler which runs when a BLE advertisement is received. /// </summary> /// <param name="sender">The watcher which called this event handler</param> /// <param name="args">Information about the advertisement which generated this event</param> private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { Console.WriteLine(args.Advertisement.LocalName + "--" + args.BluetoothAddress); if (args.RawSignalStrengthInDBm == -127) { // TODO: figure out why we get redundant(?) advertisements with RSSI=-127 return; } //if (args.AdvertisementType != BluetoothLEAdvertisementType.ConnectableDirected && // args.AdvertisementType != BluetoothLEAdvertisementType.ConnectableUndirected) //{ // // Advertisement does not indicate that the device can connect // return; //} if (!_filters.Any(filter => filter.Matches(args.Advertisement))) { // No matching filters return; } var peripheralData = new JObject { new JProperty("name", new JValue(args.Advertisement.LocalName ?? "")), new JProperty("rssi", new JValue(args.RawSignalStrengthInDBm)), new JProperty("peripheralId", new JValue(args.BluetoothAddress)) }; _reportedPeripherals.Add(args.BluetoothAddress); SendRemoteRequest("didDiscoverPeripheral", peripheralData); m_peripheralData = peripheralData; }
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); } Task.Run(async() => { var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress, args.BluetoothAddressType); if (device != null) { Device = device; } }); _advertisement = args.Advertisement; }
private void _advWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { // Ignore non-Bluetera devices if (!BlueteraConstants.ValidDeviceNames.Contains(args.Advertisement.LocalName)) { return; } // Ignore duplicate calls if (_devicesFound.Contains(args.BluetoothAddress)) { return; } // add to found devices _devicesFound.Add(args.BluetoothAddress); // notify BlueteraAdvertisement adv = new BlueteraAdvertisement() { Address = args.BluetoothAddress, Rssi = (double)args.RawSignalStrengthInDBm }; AdvertismentReceived?.Invoke(this, adv); }
private static void WatcherHandle(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (args.Advertisement.LocalName.IndexOf("Mi Smart Band 4") != -1) { Console.WriteLine(args.BluetoothAddress); } }
void OnBluetoothAdvertisementSpotted( BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { foreach (var item in args.Advertisement.GetManufacturerDataByCompanyId( BluetoothLEStreamSocketAdvertisement.MS_BLUETOOTH_LE_ID)) { var advertisement = BluetoothLEStreamSocketAdvertisement.ReadFromBuffer(item.Data); if (advertisement != null) { if ((advertisement.Address.ToString() != this.localAddress.ToString()) && !IsRepeatAdvertisement(advertisement)) { this.StreamSocketDiscovered?.Invoke(this, new BluetoothLEStreamSocketDiscoveredEventArgs() { Advertisement = advertisement }); this.uniqueAdvertisements.Add(advertisement); } } } }
private void PrintManufacturerData(BluetoothLEAdvertisementReceivedEventArgs e, MData m) { { if (m.ManufacturerData.Count > 0) { Log.d(" SECTIONS: " + m.ManufacturerData.Count); foreach (MData.Section section in m.ManufacturerData) { //// Print the company ID + the raw data in hex format string manufacturerDataString = string.Format("0x{0}: {1}", section.CompanyId.ToString("X"), BitConverter.ToString(section.Buffer)); Log.d(string.Format(" COMPANY({0}): {1}", section.Buffer.Length, manufacturerDataString)); if (!_records.ContainsKey(section.CompanyId)) { _records[section.CompanyId] = new DeviceRecordVM(e.Advertisement.LocalName, section.CompanyId, section.Buffer); } _records[section.CompanyId].Buffer = section.Buffer; if (!string.IsNullOrWhiteSpace(e.Advertisement.LocalName)) { _records[section.CompanyId].Name = e.Advertisement.LocalName; } } } } }
internal AdvertisementData( BluetoothLEAdvertisementReceivedEventArgs args, BluetoothLEAdvertisement?scanResponse = null) { this.args = args; this.scanResponse = scanResponse; }
private void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (!EnableToggle) { return; } if (connectedMyos.Count < 2 && currentDevice == null) // myos yet to be found && not busy finding one { Task devChk = getDevice(args.BluetoothAddress).ContinueWith((antecedant) => { if (antecedant.Status == TaskStatus.RanToCompletion && antecedant.Result != null) // if the result is confirmed { if (deviceList.Contains(antecedant.Result.Name) && !bondedMyos.Contains(antecedant.Result.Name)) // and it's not already connected { isConnecting = true; currentDevice = antecedant.Result; Guid myoId = AddMyoArmbandFromDevice(currentDevice); UpdateArmbandInfo(currentDevice); if (connectedMyos.Count == 1 || connectedMyos.Count == 2) { ConnectToArmband(myoId); } } } }); devChk.Wait(); } }
private void _Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (Discovered != null) { Discovered(args); } }
private void HandleWatcher(BluetoothLEAdvertisementReceivedEventArgs watcherArgs) { string _name = watcherArgs.Advertisement.LocalName; ulong btAddr = watcherArgs.BluetoothAddress; if (_name.Length == 0) { _name = btAddr.ToString(); } KeyValuePair <ulong, string> watcherResult = new KeyValuePair <ulong, string>(btAddr, _name); AddOrUpdateDevice(watcherResult); // check for connectability try { BluetoothLEDevice attemptDev = null; Task.Run(async() => { attemptDev = await getBLEDeviceFromAddress(btAddr); }).ContinueWith((antecedant) => { if (attemptDev != null) { KeyValuePair <ulong, string> attemptConnResult = new KeyValuePair <ulong, string>(btAddr, attemptDev.Name); AddOrUpdateDevice(attemptConnResult); } }).ConfigureAwait(false); } catch { Debug.Log("device connection attempt failed..."); } }
private void OnAdvertisementReceipt(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (args.BluetoothAddress == tagNo) { Rssi = args.RawSignalStrengthInDBm; } }
async private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // The timestamp of the event DateTimeOffset timestamp = eventArgs.Timestamp; // The type of advertisement BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType; // The received signal strength indicator (RSSI) Int16 rssi = eventArgs.RawSignalStrengthInDBm; // The local name of the advertising device contained within the payload, if any string localName = eventArgs.Advertisement.LocalName; // Check if there are any manufacturer-specific sections. // If there is, print the raw data of the first manufacturer section (if there are multiple). string manufacturerDataString = ""; var manufacturerSections = eventArgs.Advertisement.ManufacturerData; var res = String.Empty; if (manufacturerSections.Count > 0) { // Only print the first one of the list var manufacturerData = manufacturerSections[0]; var data = new byte[manufacturerData.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerData.Data)) { reader.ReadBytes(data); } var str = BitConverter.ToString(data); //Char.ConvertFromUtf32(value); string[] hexValuesSplit = str.Split('-'); foreach (String hex in hexValuesSplit) { int value = Convert.ToInt32(hex, 16); string stringValue = Char.ConvertFromUtf32(value); char charValue = (char)value; res += charValue; } // Print the company ID + the raw data in hex format manufacturerDataString = string.Format("0x{0}: {1}", manufacturerData.CompanyId.ToString("X"), res); } // Serialize UI update to the main UI thread await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { // Display these inf myTextBox.Text = $"[{timestamp.ToString("hh\\:mm\\:ss\\.fff")}]: {res}]"; }); }
private async void _watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (args.AdvertisementType == BluetoothLEAdvertisementType.ConnectableUndirected) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { await TryAddDeviceToList(args); }); } }
private void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv) { // Let the library manager handle the advertisement to analyse & store the advertisement _beaconManager.ReceivedAdvertisement(btAdv); foreach (var bluetoothBeacon in _beaconManager.BluetoothBeacons.ToList()) { Debug.WriteLine("\nBeacon: " + bluetoothBeacon.BluetoothAddressAsString); Debug.WriteLine("Type: " + bluetoothBeacon.BeaconType); Debug.WriteLine("Last Update: " + bluetoothBeacon.Timestamp); Debug.WriteLine("RSSI: " + bluetoothBeacon.Rssi); foreach (var beaconFrame in bluetoothBeacon.BeaconFrames.ToList()) { // Print a small sample of the available data parsed by the library if (beaconFrame is UidEddystoneFrame) { Debug.WriteLine("Eddystone UID Frame"); Debug.WriteLine("ID: " + ((UidEddystoneFrame) beaconFrame).NamespaceIdAsNumber.ToString("X") + " / " + ((UidEddystoneFrame) beaconFrame).InstanceIdAsNumber.ToString("X")); } else if (beaconFrame is UrlEddystoneFrame) { Debug.WriteLine("Eddystone URL Frame"); Debug.WriteLine("URL: " + ((UrlEddystoneFrame) beaconFrame).CompleteUrl); } else if (beaconFrame is TlmEddystoneFrame) { Debug.WriteLine("Eddystone Telemetry Frame"); Debug.WriteLine("Temperature [°C]: " + ((TlmEddystoneFrame) beaconFrame).TemperatureInC); Debug.WriteLine("Battery [mV]: " + ((TlmEddystoneFrame) beaconFrame).BatteryInMilliV); } else { Debug.WriteLine("Unknown frame - not parsed by the library, write your own derived beacon frame type!"); Debug.WriteLine("Payload: " + BitConverter.ToString(((UnknownBeaconFrame) beaconFrame).Payload)); } } } // Optional: distinguish beacons based on the Bluetooth address (btAdv.BluetoothAddress) // Check if it's a beacon by Apple /*if (btAdv.Advertisement.ManufacturerData.Any()) { foreach (var manufacturerData in btAdv.Advertisement.ManufacturerData) { // 0x4C is the ID assigned to Apple by the Bluetooth SIG if (manufacturerData.CompanyId == 0x4C) { // Parse the beacon data according to the Apple iBeacon specification // Access it through: var manufacturerDataArry = manufacturerData.Data.ToArray(); var data = manufacturerData.Data.ToArray(); Messenger.Default.Send(new BleBeaconMessage {Data = data}); } } }*/ }
/// <summary> /// Checks if the given Advertisement can be parsed by this parser. /// </summary> /// <param name="advertisementReceivedEventArgs"></param> /// <returns>True if the advertisement can be parsed as a proximity beacon by this parser.</returns> internal virtual bool CanParseAdvertisement(BluetoothLEAdvertisementReceivedEventArgs advertisementReceivedEventArgs) { var dataSections = advertisementReceivedEventArgs.Advertisement.DataSections; if (dataSections.Count() > 1) { var datasection = dataSections.ElementAt(1); var bytes = datasection.Data.ToArray(); return CanParseAdvertisement(bytes); } return false; }
/// <summary> /// Parses the given advertisementReceivedEventArgs to a Proximity Beacon data type /// </summary> /// <param name="advertisementReceivedEventArgs">The Advertisement to parse.</param> /// <returns>The Advertisement as a ProximityBeacon</returns> internal virtual ProximityBeacon Parse(BluetoothLEAdvertisementReceivedEventArgs advertisementReceivedEventArgs) { var dataSections = advertisementReceivedEventArgs.Advertisement.DataSections; if (dataSections.Count() > 1) { var datasection = dataSections.ElementAt(1); var bytes = datasection.Data.ToArray(); return Parse(bytes); } return null; }
private async Task TryAddDeviceToList(BluetoothLEAdvertisementReceivedEventArgs args) { if (_devices.All(d => d.BluetoothAddress != args.BluetoothAddress)) { try { var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); _devices.Add(device); } catch (Exception e) { Debug.WriteLine(e.Message); } } }
/// <summary> /// Constructs a Beacon instance and sets the properties based on the given data. /// </summary> /// <param name="args"></param> /// <returns>A newly created Beacon instance or null in case of a failure.</returns> public static Beacon BeaconFromBluetoothLeAdvertisementReceivedEventArgs(BluetoothLEAdvertisementReceivedEventArgs args) { Beacon beacon = null; if (args != null && args.Advertisement != null) { beacon = BeaconFromDataSectionList(args.Advertisement.DataSections); if (beacon != null) { beacon.Timestamp = args.Timestamp; beacon.RawSignalStrengthInDBm = args.RawSignalStrengthInDBm; } } return beacon; }
/// <summary> /// Analyze the received Bluetooth LE advertisement, and either add a new unique /// beacon to the list of known beacons, or update a previously known beacon /// with the new information. /// </summary> /// <param name="btAdv">Bluetooth advertisement to parse, as received from /// the Windows Bluetooth LE API.</param> public void ReceivedAdvertisement(BluetoothLEAdvertisementReceivedEventArgs btAdv) { // Check if we already know this bluetooth address foreach (var bluetoothBeacon in BluetoothBeacons) { if (bluetoothBeacon.BluetoothAddress == btAdv.BluetoothAddress) { // We already know this beacon // Update / Add info to existing beacon bluetoothBeacon.UpdateBeacon(btAdv); return; } } // Beacon was not yet known - add it to the list. var newBeacon = new Beacon(btAdv); BluetoothBeacons.Add(newBeacon); }
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { var manufacturerData = args.Advertisement.ManufacturerData; if (manufacturerData.Any()) { var manufacturerDataSection = manufacturerData[0]; var data = new byte[manufacturerDataSection.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerDataSection.Data)) { reader.ReadBytes(data); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.Rssi = (int)args.RawSignalStrengthInDBm; this.BeaconData = BitConverter.ToString(data); }); } }
/// <summary> /// Invoked as an event handler when an advertisement is received. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the advertisement event.</param> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // We can obtain various information about the advertisement we just received by accessing // the properties of the EventArgs class var newDevice = new BluetoothLEAdvertismentViewModel(eventArgs); BluetoothLEAdvertismentViewModel oldDevice = null; _table.TryGetValue(newDevice.Address, out oldDevice); _table[newDevice.Address] = newDevice; // Notify the user that the watcher was stopped await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (oldDevice != null) { _devices.Remove(oldDevice); } _devices.Add(newDevice); }); }
/** * Triggered when we receive data **/ private async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // Let the library manager handle the advertisement to analyse & store the advertisement beaconManager.ReceivedAdvertisement(eventArgs); }
public BluetoothLEAdvertismentViewModel(BluetoothLEAdvertisementReceivedEventArgs device) { ble = device; ad = ble.Advertisement; this.Address = ble.BluetoothAddress.ToString(); }
private async void OnAdvertisemenetReceivedAsync(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Beacon beacon = BeaconFactory.BeaconFromBluetoothLEAdvertisementReceivedEventArgs(args); if (beacon != null) { System.Diagnostics.Debug.WriteLine("Received advertisement from beacon " + beacon.ToString()); bool existingBeaconUpdated = false; foreach (Beacon existingBeacon in BeaconCollection) { if (existingBeacon.Update(beacon)) { existingBeaconUpdated = true; beacon.Dispose(); } } if (!existingBeaconUpdated) { BeaconCollection.Add(beacon); } } }); }
private void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // Signal strength var rssi = eventArgs.RawSignalStrengthInDBm; // Extract manufacturer data (if present) var manufacturerDataString = string.Empty; if (eventArgs.Advertisement.ManufacturerData.Any()) { var manufacturerData = eventArgs.Advertisement.ManufacturerData.First(); var data = new byte[manufacturerData.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerData.Data)) { reader.ReadBytes(data); } // Print the company ID + the raw data in hex format manufacturerDataString = $"0x{manufacturerData.CompanyId.ToString("X")}: {BitConverter.ToString(data)}"; } SetStatusOutput($"Beacon detected (Strength: {rssi}): {manufacturerDataString}"); }
/// <summary> /// Invoked as an event handler when an advertisement is received. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the advertisement event.</param> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // We can obtain various information about the advertisement we just received by accessing // the properties of the EventArgs class // The timestamp of the event DateTimeOffset timestamp = eventArgs.Timestamp; // The type of advertisement BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType; // The received signal strength indicator (RSSI) Int16 rssi = eventArgs.RawSignalStrengthInDBm; // The local name of the advertising device contained within the payload, if any string localName = eventArgs.Advertisement.LocalName; // Get iBeacon specific data var beaconData = eventArgs.Advertisement.iBeaconParseAdvertisement(eventArgs.RawSignalStrengthInDBm); if (beaconData == null) return; Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { var existing = beacons.Where(b => b.UUID == beaconData.UUID && b.Major == beaconData.Major && b.Minor == beaconData.Minor).FirstOrDefault(); if (existing != null) { var idx = beacons.IndexOf(existing); beacons.RemoveAt(idx); beacons.Insert(idx, beaconData); } else beacons.Add(beaconData); }); }
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; } } }
private void _Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { if (Discovered != null){ Discovered(args); } }
/// <summary> /// Invoked as an event handler when an advertisement is received. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the advertisement event.</param> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // We can obtain various information about the advertisement we just received by accessing // the properties of the EventArgs class // The timestamp of the event DateTimeOffset timestamp = eventArgs.Timestamp; // The type of advertisement BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType; // The received signal strength indicator (RSSI) Int16 rssi = eventArgs.RawSignalStrengthInDBm; // The local name of the advertising device contained within the payload, if any string localName = eventArgs.Advertisement.LocalName; // Check if there are any manufacturer-specific sections. // If there is, print the raw data of the first manufacturer section (if there are multiple). string manufacturerDataString = ""; var manufacturerSections = eventArgs.Advertisement.ManufacturerData; if (manufacturerSections.Count > 0) { // Only print the first one of the list var manufacturerData = manufacturerSections[0]; var data = new byte[manufacturerData.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerData.Data)) { reader.ReadBytes(data); } // Print the company ID + the raw data in hex format manufacturerDataString = string.Format("0x{0}: {1}", manufacturerData.CompanyId.ToString("X"), BitConverter.ToString(data)); } // Serialize UI update to the main UI thread await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { // Display these information on the list ReceivedAdvertisementListBox.Items.Add(string.Format("[{0}]: type={1}, rssi={2}, name={3}, manufacturerData=[{4}]", timestamp.ToString("hh\\:mm\\:ss\\.fff"), advertisementType.ToString(), rssi.ToString(), localName, manufacturerDataString)); }); }
private async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { try { _beaconManager.ReceivedAdvertisement(eventArgs); } catch (ArgumentException e) { // Ignore for real-life scenarios. // In some very rare cases, analyzing the data can result in an // Argument_BufferIndexExceedsCapacity. Ignore the error here, // assuming that the next received frame advertisement will be // correct. Debug.WriteLine(e); } }); }
private async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => _beaconManager.ReceivedAdvertisement(eventArgs)); }
/// <summary> /// Triggered when the watcher receives an advertisement. /// If the advertisement came from a beacon, a Beacon instance is created based on the /// received data. A new beacon is added to the list and an existing one is only updated. /// </summary> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { Logger.Debug("Scanner: Advertisement received " + args.Timestamp.ToString("HH:mm:ss.fff")); Beacon beacon = BeaconFactory.BeaconFromBluetoothLeAdvertisementReceivedEventArgs(args); if (beacon != null) { if (_enterDistanceThreshold != null && beacon.Distance > _enterDistanceThreshold.Value) { return; } if (!FilterBeaconByUuid(beacon)) { return; } NotifyBeaconEvent(beacon); } }
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { try { foreach (var beacon in BeaconsList) { if (beacon.BeaconType != Beacon.BeaconTypeEnum.Unknown) { BeaconMessage bm = new BeaconMessage(beacon); if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile") bm.Device = "NL635Gk_8"; else bm.Device = "GorkmaSP3"; _azureEventHubService.SendMessage(JsonConvert.SerializeObject(bm)); if (SelectedBeacon == beacon) SelectedBeaconMessage = bm; } else if (SelectedBeacon == beacon) SelectedBeaconMessage = null; } } catch (Exception) { // Sometimes the collection changes while getting through the foreach loop } }
private void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { foreach (var beacon in BeaconsList) { beacon.PropertyChanged -= Beacon_PropertyChanged; beacon.PropertyChanged += Beacon_PropertyChanged; } }
/// <summary> /// Invoked as an event handler when the Stop button is pressed. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> /// /* private void StopButton_Click(object sender, RoutedEventArgs e) { // Stopping the watcher will stop scanning if this is the only client requesting scan watcher.Stop(); }*/ /// <summary> /// Invoked as an event handler when an advertisement is received. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the advertisement event.</param> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { Debug.WriteLine("signal!"); // We can obtain various information about the advertisement we just received by accessing // the properties of the EventArgs class // The timestamp of the event DateTimeOffset timestamp = eventArgs.Timestamp; // The type of advertisement BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType; // The received signal strength indicator (RSSI) Int16 rssi = eventArgs.RawSignalStrengthInDBm; // The local name of the advertising device contained within the payload, if any string localName = eventArgs.Advertisement.LocalName; // Check if there are any manufacturer-specific sections. // If there is, print the raw data of the first manufacturer section (if there are multiple). var manufacturerSections = eventArgs.Advertisement.ManufacturerData; int client_num = manufacturerSections.Count+3; string[] client_ids = new string[client_num]; if (client_num > 0) { client_ids[0]="shin"; client_ids[1] = "mk"; client_ids[2] = "jh"; var manufacturerData = manufacturerSections[0]; var data = new byte[manufacturerData.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerData.Data)) { reader.ReadBytes(data); } // Print the company ID + the raw data in hex format client_ids[3] = string.Format("{0}", Encoding.UTF8.GetString(data)); Debug.WriteLine(client_ids[3]); /* for (int i = 0; i < client_num; i++) { var manufacturerData = manufacturerSections[i]; var data = new byte[manufacturerData.Data.Length]; using (var reader = DataReader.FromBuffer(manufacturerData.Data)) { reader.ReadBytes(data); } // Print the company ID + the raw data in hex format client_ids[i] = string.Format("{0}", Encoding.UTF8.GetString(data)); }*/ } // compare pre_member with current member current_client.check_exist(client_ids); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { for (int i = current_client.client_num; i > 0; i--) { Client client = current_client.client_id(i - 1); // Debug.WriteLine(client.Id); if (client.Profile_image != null) { BitmapImage bi = await Convert_module.convert_base64_to_bitmapImage(client.Profile_image); if (i == current_client.client_num) { UserList0_Ring.IsActive = false; UserList0_Ring.Visibility = Visibility.Collapsed; UserList0_Image.Source = bi; UserList0_Name.Text = client.Nickname; UserList0_Status.Text = client.Status_message; } else if (i == current_client.client_num - 1) { UserList1_Ring.IsActive = false; UserList1_Ring.Visibility = Visibility.Collapsed; UserList1_Image.Source = bi; UserList1_Name.Text = client.Nickname; UserList1_Status.Text = client.Status_message; } else if (i == current_client.client_num - 2) { UserList2_Ring.IsActive = false; UserList2_Ring.Visibility = Visibility.Collapsed; UserList2_Image.Source = bi; UserList2_Name.Text = client.Nickname; UserList2_Status.Text = client.Status_message; } else if (i == current_client.client_num - 3) { UserList3_Ring.IsActive = false; UserList3_Ring.Visibility = Visibility.Collapsed; UserList3_Image.Source = bi; UserList3_Name.Text = client.Nickname; UserList3_Status.Text = client.Status_message; } else { Debug.WriteLine("Not show more than 4 peoples"); } } } }); }
public AdvertisedBLEDevice(BluetoothLEAdvertisementReceivedEventArgs inAd) { ad = inAd; }
/// <summary> /// Received a new advertisement for this beacon. /// If the Bluetooth address of the new advertisement matches this beacon, /// it will parse the contents of the advertisement and extract known frames. /// </summary> /// <param name="btAdv">Bluetooth advertisement to parse, as received from /// the Windows Bluetooth LE API.</param> public void UpdateBeacon(BluetoothLEAdvertisementReceivedEventArgs btAdv) { if (btAdv == null) return; if (btAdv.BluetoothAddress != BluetoothAddress) { throw new BeaconException("Bluetooth address of beacon does not match - not updating beacon information"); } Rssi = btAdv.RawSignalStrengthInDBm; Timestamp = btAdv.Timestamp; //Debug.WriteLine($"Beacon advertisment detected (Strength: {Rssi}): Address: {BluetoothAddress}"); // Check if beacon advertisement contains any actual usable data if (btAdv.Advertisement == null) return; if (btAdv.Advertisement.ServiceUuids.Any()) { foreach (var serviceUuid in btAdv.Advertisement.ServiceUuids) { // If we have multiple service UUIDs and already recognized a beacon type, // don't overwrite it with another service Uuid. if (BeaconType == BeaconTypeEnum.Unknown) { BeaconType = serviceUuid.Equals(_eddystoneGuid) ? BeaconTypeEnum.Eddystone : BeaconTypeEnum.Unknown; } } } else { //Debug.WriteLine("Bluetooth LE device does not send Service UUIDs"); } // Data sections if (btAdv.Advertisement.DataSections.Any()) { if (BeaconType == BeaconTypeEnum.Eddystone) { // This beacon is according to the Eddystone specification - parse data ParseEddystoneData(btAdv); } else if (BeaconType == BeaconTypeEnum.Unknown) { // Unknown beacon type //Debug.WriteLine("\nUnknown beacon"); //foreach (var dataSection in btAdv.Advertisement.DataSections) //{ // Debug.WriteLine("Data section 0x: " + dataSection.DataType.ToString("X") + " = " + // BitConverter.ToString(dataSection.Data.ToArray())); //} } } // Manufacturer data - currently unused if (btAdv.Advertisement.ManufacturerData.Any()) { foreach (var manufacturerData in btAdv.Advertisement.ManufacturerData) { // Print the company ID + the raw data in hex format //var manufacturerDataString = $"0x{manufacturerData.CompanyId.ToString("X")}: {BitConverter.ToString(manufacturerData.Data.ToArray())}"; //Debug.WriteLine("Manufacturer data: " + manufacturerDataString); var manufacturerDataArry = manufacturerData.Data.ToArray(); if (BeaconFrameHelper.IsProximityBeaconPayload(manufacturerData.CompanyId, manufacturerDataArry)) { BeaconType = BeaconTypeEnum.iBeacon; //Debug.WriteLine("iBeacon Frame: " + BitConverter.ToString(manufacturerDataArry)); var beaconFrame = new ProximityBeaconFrame(manufacturerDataArry); // Only one relevant data frame for iBeacons if (BeaconFrames.Any()) { BeaconFrames[0].Update(beaconFrame); } else { BeaconFrames.Add(beaconFrame); } } } } }
/// <summary> /// Invoked as an event handler when an advertisement is received. /// </summary> /// <param name="watcher">Instance of watcher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the advertisement event.</param> private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { // We can obtain various information about the advertisement we just received by accessing // the properties of the EventArgs class // The timestamp of the event DateTimeOffset timestamp = eventArgs.Timestamp; // The type of advertisement BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType; // The received signal strength indicator (RSSI) Int16 rssi = eventArgs.RawSignalStrengthInDBm; // The local name of the advertising device contained within the payload, if any string localName = eventArgs.Advertisement.LocalName; // Check if there are any manufacturer-specific sections. // If there is, print the raw data of the first manufacturer section (if there are multiple). string manufacturerDataString = ""; var manufacturerSections = eventArgs.Advertisement.ManufacturerData; if(manufacturerSections.Count > 0) { // Only print the first one of the list var manufacturerData = manufacturerSections[0]; var data = new byte[manufacturerData.Data.Length]; using(var reader = DataReader.FromBuffer(manufacturerData.Data)) reader.ReadBytes(data); // Print the company ID + the raw data in hex format manufacturerDataString = string.Format("0x{0}: {1}", manufacturerData.CompanyId, BitConverter.ToString(data)); } var eventMessage = $"[{timestamp.ToString("hh\\:mm\\:ss\\.fff")}]: " + $"type={advertisementType}, " + $"rssi={rssi}, " + $"name={localName}, " + $"manufacturerData=[{manufacturerDataString}]"; _tracker.AddBeaconReading(new BeaconReading { Beacon = new Beacon(eventArgs.BluetoothAddress.ToString()) { ManufacturerCode = manufacturerSections[0].CompanyId.ToString() }, MeasurementTime = eventArgs.Timestamp, RawSignalStrengthInDBm = eventArgs.RawSignalStrengthInDBm, RawData = manufacturerDataString, EventMessage = eventMessage }); // Serialize UI update to the main UI thread await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ReceivedAdvertisementListBox.Items?.Add(eventMessage)); }
/// <summary> /// Construct a new Bluetooth beacon based on the received advertisement. /// Tries to find out if it's a known type, and then parses the contents accordingly. /// </summary> /// <param name="btAdv">Bluetooth advertisement to parse, as received from /// the Windows Bluetooth LE API.</param> public Beacon(BluetoothLEAdvertisementReceivedEventArgs btAdv) { BluetoothAddress = btAdv.BluetoothAddress; UpdateBeacon(btAdv); }
private void ParseEddystoneData(BluetoothLEAdvertisementReceivedEventArgs btAdv) { // Parse Eddystone data foreach (var dataSection in btAdv.Advertisement.DataSections) { //Debug.WriteLine("Beacon data: " + dataSection.DataType + " = " + // BitConverter.ToString(dataSection.Data.ToArray())); //+ " (" + Encoding.UTF8.GetString(dataSection.Data.ToArray()) + ")\n"); // Relvant data of Eddystone is in data section 0x16 // Windows receives: 0x01 = 0x06 // 0x03 = 0xAA 0xFE // 0x16 = 0xAA 0xFE [type] [data] if (dataSection.DataType == 0x16) { var beaconFrame = dataSection.Data.ToArray().CreateEddystoneBeaconFrame(); if (beaconFrame == null) continue; var found = false; for (var i = 0; i < BeaconFrames.Count; i++) { if (BeaconFrames[i].GetType() == beaconFrame.GetType()) { var updateFrame = false; if (beaconFrame.GetType() == typeof(UnknownBeaconFrame)) { // Unknown frame - also compare eddystone type var existingEddystoneFrameType = BeaconFrames[i].Payload.GetEddystoneFrameType(); var newEddystoneFrameType = beaconFrame.Payload.GetEddystoneFrameType(); if (existingEddystoneFrameType != null && existingEddystoneFrameType == newEddystoneFrameType) { updateFrame = true; } } else { updateFrame = true; } if (updateFrame) { BeaconFrames[i].Update(beaconFrame); found = true; break; // Don't analyze any other known frames of this beacon } } } if (!found) { BeaconFrames.Add(beaconFrame); } } } }