Example #1
0
        /// <summary>
        /// Creates the second part of the beacon advertizing packet.
        /// Uses the beacon IDs 1, 2, 3 and measured power to create the data section.
        /// </summary>
        /// <param name="beacon">A beacon instance.</param>
        /// <param name="includeMfgReservedByte">Defines whether we should add the additional, manufacturer reserved byte or not.</param>
        /// <returns>A newly created data section.</returns>
        public static BluetoothLEAdvertisementDataSection BeaconToSecondDataSection(
            Beacon beacon, bool includeMfgReservedByte = false)
        {
            string[] temp      = beacon.Id1.Split(HexStringSeparator);
            string   beaconId1 = string.Join("", temp);

            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(ManufacturerIdToString(beacon.ManufacturerId));
            stringBuilder.Append(BeaconCodeToString(beacon.Code));
            stringBuilder.Append(beaconId1.ToUpper());

            byte[] beginning = HexStringToByteArray(stringBuilder.ToString());

            byte[] data = includeMfgReservedByte
                ? new byte[SecondBeaconDataSectionMinimumLengthInBytes + 1]
                : new byte[SecondBeaconDataSectionMinimumLengthInBytes];

            beginning.CopyTo(data, 0);
            ChangeInt16ArrayEndianess(BitConverter.GetBytes(beacon.Id2)).CopyTo(data, 20);
            ChangeInt16ArrayEndianess(BitConverter.GetBytes(beacon.Id3)).CopyTo(data, 22);
            data[24] = (byte)Convert.ToSByte(beacon.MeasuredPower);

            if (includeMfgReservedByte)
            {
                data[25] = beacon.MfgReserved;
            }

            BluetoothLEAdvertisementDataSection dataSection = new BluetoothLEAdvertisementDataSection();

            dataSection.DataType = SecondBeaconDataSectionDataType;
            dataSection.Data     = data.AsBuffer();

            return(dataSection);
        }
        public ObservableBluetoothLEAdvertisementSection(BluetoothLEAdvertisementDataSection section)
        {
            TypeAsString        = section.DataType.ToString("X2");
            TypeAsDisplayString = AdvertisementDataTypeHelper.ConvertSectionTypeToString(section.DataType);

            DataAsString = GattConvert.ToHexString(section.Data);
            if (section.DataType == BluetoothLEAdvertisementDataTypes.Flags)
            {
                var flagsInt = GattConvert.ToInt32(section.Data);
                DataAsDisplayString = ((BluetoothLEAdvertisementFlags)Enum.ToObject(typeof(BluetoothLEAdvertisementFlags), flagsInt)).ToString();
            }
            else if (section.DataType == BluetoothLEAdvertisementDataTypes.CompleteLocalName ||
                     section.DataType == BluetoothLEAdvertisementDataTypes.ShortenedLocalName)
            {
                DataAsDisplayString = GattConvert.ToUTF8String(section.Data);
            }
            else if (section.DataType == BluetoothLEAdvertisementDataTypes.TxPowerLevel)
            {
                var txPowerLevel = GattConvert.ToInt16(section.Data);
                DataAsDisplayString = txPowerLevel.ToString();
            }
            else
            {
                DataAsDisplayString = "<Unknown>";
            }
        }
        public BLEAdvertisementDataSection(BluetoothLEAdvertisementDataSection args)
        {
            var data = new byte[args.Data.Length];

            using (var reader = DataReader.FromBuffer(args.Data))
            {
                reader.ReadBytes(data);
            }
            this.Data = string.Format("{0}", BitConverter.ToString(data));

            this.DataType = args.DataType;
        }
Example #4
0
        public void Start()
        {
            // Create and initialize a new publisher instance.
            this._publisher = new BluetoothLEAdvertisementPublisher();

            // Attach a event handler to monitor the status of the publisher, which
            // can tell us whether the advertising has been serviced or is waiting to be serviced
            // due to lack of resources. It will also inform us of unexpected errors such as the Bluetooth
            // radio being turned off by the user.
            this._publisher.StatusChanged += OnPublisherStatusChanged;

            // We need to add some payload to the advertisement. A publisher without any payload
            // or with invalid ones cannot be started. We only need to configure the payload once
            // for any publisher.

            // Add a manufacturer-specific section:
            // First, let create a manufacturer data section
            var manufacturerData = new BluetoothLEManufacturerData();

            // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
            manufacturerData.CompanyId = ManufacturerId;

            // Finally set the data payload within the manufacturer-specific section
            // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
            var    writer   = new DataWriter();
            UInt16 uuidData = 0x1234;

            writer.WriteUInt16(uuidData);

            // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
            manufacturerData.Data = writer.DetachBuffer();

            // Add the manufacturer data to the advertisement publisher:
            this._publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // From old code (Which is not commented)
            var data = new BluetoothLEAdvertisementDataSection {
                Data = SolicitationData.AsBuffer()
            };

            this._publisher.Advertisement.DataSections.Add(data);

            try
            {
                // Calling publisher start will start the advertising if resources are available to do so
                this._publisher.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #5
0
        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);
        }
Example #6
0
        public static string ParseAppearance(BluetoothLEAdvertisementDataSection section)
        {
            var dr = DataReader.FromBuffer(section.Data);

            dr.ByteOrder = ByteOrder.LittleEndian; // bluetooth is little-endian by default
            if (dr.UnconsumedBufferLength < 2)
            {
                return($"?len={dr.UnconsumedBufferLength}");
            }
            var appearance = dr.ReadUInt16();
            var retval     = BluetoothAppearance.AppearaceToString(appearance);

            return(retval);
        }
Example #7
0
        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);
        }
        /// <summary>
        /// Constructs a Beacon instance and sets the properties based on the given data.
        /// </summary>
        /// <param name="dataSection">A data section containing beacon data.</param>
        /// <returns>A newly created Beacon instance or null in case of a failure.</returns>
        public static Beacon BeaconFromDataSection(BluetoothLEAdvertisementDataSection dataSection)
        {
            Beacon beacon = null;

            if (dataSection != null && dataSection.Data != null)
            {
                beacon = BeaconFromByteArray(dataSection.Data.ToArray());
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("BeaconFactory.BeaconFromDataSection(): The given data (section) is null");
            }

            return beacon;
        }
Example #9
0
        /// <summary>
        /// Constructs a Beacon instance and sets the properties based on the given data.
        /// </summary>
        /// <param name="dataSection">A data section containing beacon data.</param>
        /// <returns>A newly created Beacon instance or null in case of a failure.</returns>
        public static Beacon BeaconFromDataSection(BluetoothLEAdvertisementDataSection dataSection)
        {
            Beacon beacon = null;

            if (dataSection != null && dataSection.Data != null)
            {
                beacon = BeaconFromByteArray(dataSection.Data.ToArray());
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("BeaconFactory.BeaconFromDataSection(): The given data (section) is null");
            }

            return(beacon);
        }
Example #10
0
        public static (string result, CommonManufacturerType) ParseManufacturerData(BluetoothLEAdvertisementDataSection section, sbyte txPower)
        {
            CommonManufacturerType manufacturerType = CommonManufacturerType.Other;

            try
            {
                var bytes = section.Data.ToArray();
                var dr    = DataReader.FromBuffer(section.Data);
                dr.ByteOrder = ByteOrder.LittleEndian; // bluetooth defaults to little endian.
                var companyId   = dr.ReadUInt16();
                var companyName = GetBluetoothCompanyIdentifier(companyId);
                var sb          = new StringBuilder();
                sb.Append(companyName);
                sb.Append(": ");
                bool displayAsHex = true;
                switch (companyId)
                {
                case 0x4C:     // Apple
                    var appleIBeacon = AppleIBeacon.Parse(section, txPower);
                    if (appleIBeacon.IsValid)
                    {
                        sb.Append(appleIBeacon.ToString());
                        sb.Append("\n");
                        displayAsHex = false;     // we have a better display
                    }
                    else if (appleIBeacon.IsApple10)
                    {
                        manufacturerType = CommonManufacturerType.Apple10;
                    }
                    break;
                }
                if (displayAsHex)
                {
                    while (dr.UnconsumedBufferLength > 0)
                    {
                        var b = dr.ReadByte().ToString("X2");
                        sb.Append(b); // As hex!
                        sb.Append(' ');
                    }
                    sb.Append('\n');
                }
                return(sb.ToString(), manufacturerType);
            }
            catch (Exception)
            {
                return("??\n", manufacturerType);
            }
        }
Example #11
0
 /// <summary>
 /// Check the advertisement data section is Service Solicitation and contains the specific UUID.
 /// </summary>
 /// <param name="section">An instance of BluetoothLEAdvertisementDataSection to check whether it contains the specified UUID.</param>
 /// <param name="uuid">The UUID which the advertisement data is expected to contain.</param>
 /// <returns></returns>
 private static bool MatchSolicitationServiceLong(BluetoothLEAdvertisementDataSection section, Guid uuid)
 {
     // We have to reverse the first 3 parts of an UUID contained by the AD to compare with another UUID represented by Guid object.
     var rawUuidBytes = section.Data.ToArray().Reverse().ToArray();
     var uuidBytes = new[]
         {
             rawUuidBytes.Take(4).Reverse(),
             rawUuidBytes.Skip(4).Take(2).Reverse(),
             rawUuidBytes.Skip(6).Take(2).Reverse(),
             rawUuidBytes.Skip(8)
         }
         .Aggregate((l, r) => l.Concat(r))
         .ToArray();
         
         
     return section.DataType == ServiceSolicitationADType && uuidBytes.SequenceEqual(uuid.ToByteArray());
 }
        /// <summary>
        /// Check the advertisement data section is Service Solicitation and contains the specific UUID.
        /// </summary>
        /// <param name="section">An instance of BluetoothLEAdvertisementDataSection to check whether it contains the specified UUID.</param>
        /// <param name="uuid">The UUID which the advertisement data is expected to contain.</param>
        /// <returns></returns>
        private static bool MatchSolicitationServiceLong(BluetoothLEAdvertisementDataSection section, Guid uuid)
        {
            // We have to reverse the first 3 parts of an UUID contained by the AD to compare with another UUID represented by Guid object.
            var rawUuidBytes = section.Data.ToArray().Reverse().ToArray();
            var uuidBytes    = new[]
            {
                rawUuidBytes.Take(4).Reverse(),
                rawUuidBytes.Skip(4).Take(2).Reverse(),
                rawUuidBytes.Skip(6).Take(2).Reverse(),
                rawUuidBytes.Skip(8)
            }
            .Aggregate((l, r) => l.Concat(r))
            .ToArray();


            return(section.DataType == ServiceSolicitationADType && uuidBytes.SequenceEqual(uuid.ToByteArray()));
        }
Example #13
0
            public static AppleIBeacon Parse(BluetoothLEAdvertisementDataSection section, sbyte RSSI)
            {
                AppleIBeacon retval = new AppleIBeacon();

                try
                {
                    var dr = DataReader.FromBuffer(section.Data);
                    dr.ByteOrder     = ByteOrder.LittleEndian; // bluetooth defaults to little endian.
                    retval.CompanyId = dr.ReadUInt16();        // Will be 76 == 0x4c but that's explicitly not enforced here

                    retval.BeaconType = dr.ReadByte();
                    retval.BeaconLen  = dr.ReadByte();
                    switch (retval.BeaconType)
                    {
                    case 0x02:
                        // See https://github.com/wrightLin/RaspiJob/blob/6004e46ec28535546add496eff0ed8d7947ed563/Beacons.Helper/Beacons.cs
                        // See https://github.com/blueSense/hub-application/blob/59ab67c17cb71883cf19027bf62050b953644750/lib/bluesense-superhub/monitor/parsers/ibeacon.js
                        if (retval.BeaconLen < 0x15)
                        {
                            return(retval);
                        }
                        byte[] guidBytes = new byte[16];
                        dr.ReadBytes(guidBytes);
                        retval.BeaconGuid    = new Guid(guidBytes);
                        retval.Major         = dr.ReadUInt16();
                        retval.Minor         = dr.ReadUInt16();
                        retval.MeasuredPower = (sbyte)dr.ReadByte();
                        retval.MeasuredPower = RSSI;
                        break;

                    case 0x10:
                    case 0x12:
                        // TODO: how to handle a typical phone?
                        break;

                    default:
                        break;     //TODO: what value here?
                    }
                }
                catch (Exception)
                {
                    ;
                }
                return(retval); // if there was an exception, the beacon is invalid...
            }
Example #14
0
 /// <summary>
 /// Gotta say, the flags data is pretty uninteresting. Maybe only show flags
 /// when there's a special switch set?
 /// </summary>
 /// <param name="section"></param>
 /// <returns></returns>
 public static string ParseFlags(BluetoothLEAdvertisementDataSection section)
 {
     try
     {
         var bytes = section.Data.ToArray();
         var b0    = bytes[0];
         var str   = "";
         if ((b0 & 0x01) != 0)
         {
             if (str != "")
             {
                 str += "+";
             }
             str += "LE Limited Discoverable Mode";
         }
         if ((b0 & 0x02) != 0)
         {
             if (str != "")
             {
                 str += "+";
             }
             str += "LE General Discoverable Mode";
         }
         // It just says if classic bluetooth is supported or not.
         if ((b0 & 0x04) != 0)
         {
             if (str != "")
             {
                 str += "+";
             }
             str += "BR/EDR Not Supported";
         }
         // BDR/EDR is not interesting.
         if (str != "")
         {
             str += "\n";
         }
         return(str);
     }
     catch (Exception)
     {
         return("??\n");
     }
 }
Example #15
0
        private async void OnTogglePublisherButtonClickedAsync(object sender, RoutedEventArgs e)
        {
            if (_bluetoothLEAdvertisementPublisher.Status != BluetoothLEAdvertisementPublisherStatus.Started)
            {
                Beacon beacon = new Beacon();
                beacon.ManufacturerId = ManufacturerId;
                beacon.Code           = BeaconCode;
                beacon.Id1            = BeaconId1;

                try
                {
                    beacon.Id2 = UInt16.Parse(BeaconId2);
                    beacon.Id3 = UInt16.Parse(BeaconId3);
                }
                catch (Exception)
                {
                }

                beacon.MeasuredPower = -58;

                System.Diagnostics.Debug.WriteLine("Will try to advertise as beacon " + beacon.ToString());

                BluetoothLEAdvertisementDataSection dataSection = BeaconFactory.BeaconToSecondDataSection(beacon);
                _bluetoothLEAdvertisementPublisher.Advertisement.DataSections.Add(dataSection);

                try
                {
                    _bluetoothLEAdvertisementPublisher.Start();
                }
                catch (Exception ex)
                {
                    MessageDialog messageDialog = new MessageDialog("Failed to start Bluetooth LE Advertisement Publisher: " + ex.Message);
                    await messageDialog.ShowAsync();
                }
            }
            else
            {
                _bluetoothLEAdvertisementPublisher.Stop();
            }
        }
Example #16
0
        /// <summary>
        /// Starts advertizing based on the set values (beacon ID 1, ID 2 and ID 3).
        /// Note that this method does not validate the values and will throw exception, if the
        /// values are invalid.
        /// </summary>
        public void Start()
        {
            if (!IsStarted)
            {
                _beacon                = new Beacon();
                _beacon.Id1            = BeaconId1;
                _beacon.ManufacturerId = ManufacturerId;
                _beacon.Code           = BeaconCode;
                _beacon.Id2            = BeaconId2;
                _beacon.Id3            = BeaconId3;
                _beacon.MeasuredPower  = DefaultMeasuredPower;

                _advertisementPublisher = new BluetoothLEAdvertisementPublisher();

                BluetoothLEAdvertisementDataSection dataSection = BeaconFactory.BeaconToSecondDataSection(_beacon);
                Logger.Debug("Advertiser.Start(): " + BeaconFactory.DataSectionToRawString(dataSection));
                _advertisementPublisher.Advertisement.DataSections.Add(dataSection);
                _advertisementPublisher.Start();

                IsStarted = true;
            }
        }
        /// <summary>
        /// Creates the second part of the beacon advertizing packet.
        /// Uses the beacon IDs 1, 2, 3 and measured power to create the data section.
        /// </summary>
        /// <param name="beacon">A beacon instance.</param>
        /// <param name="includeAuxByte">Defines whether we should add the additional byte or not.</param>
        /// <returns>A newly created data section.</returns>
        public static BluetoothLEAdvertisementDataSection BeaconToSecondDataSection(
            Beacon beacon, bool includeAuxByte = false)
        {
            string[] temp = beacon.Id1.Split(HexStringSeparator);
            string beaconId1 = string.Join(string.Empty, temp);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(ManufacturerIdToString(beacon.ManufacturerId));
            stringBuilder.Append(BeaconCodeToString(beacon.Code));
            stringBuilder.Append(beaconId1.ToUpper());

            byte[] beginning = HexStringToByteArray(stringBuilder.ToString());

            byte[] data = includeAuxByte
                ? new byte[SecondBeaconDataSectionMinimumLengthInBytes + 1]
                : new byte[SecondBeaconDataSectionMinimumLengthInBytes];
            
            beginning.CopyTo(data, 0);
            ChangeInt16ArrayEndianess(BitConverter.GetBytes(beacon.Id2)).CopyTo(data, 20);
            ChangeInt16ArrayEndianess(BitConverter.GetBytes(beacon.Id3)).CopyTo(data, 22);
            data[24] = (byte)Convert.ToSByte(beacon.MeasuredPower);
            
            if (includeAuxByte)
            {
                data[25] = beacon.Aux;
            }

            BluetoothLEAdvertisementDataSection dataSection = new BluetoothLEAdvertisementDataSection();
            dataSection.DataType = SecondBeaconDataSectionDataType;
            dataSection.Data = data.AsBuffer();

            return dataSection;
        }
Example #18
0
        public static sbyte  ParseTxPowerLevel(BluetoothLEAdvertisementDataSection section)
        {
            var db = (sbyte)(section.Data.ToArray()[0]);

            return(db);
        }
Example #19
0
 /// <summary>
 /// Converts the data of the given BluetoothLEAdvertisementDataSection to a string.
 /// </summary>
 /// <param name="dataSection">The data section instance.</param>
 /// <returns>The data of the given data section as a string.</returns>
 public static string DataSectionToRawString(BluetoothLEAdvertisementDataSection dataSection)
 {
     return(BitConverter.ToString(dataSection.Data.ToArray()));
 }
Example #20
0
        public async void OnBLEAdvertismentReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            // The local name of the advertising device contained within the payload, if any
            string localName             = eventArgs.Advertisement.LocalName.TrimEnd('\0');
            UInt16 extractedAppearanceID = 0;

            //Debug.WriteLine("## BLE SCAN ENTRY " + localName);
            try
            {
                // The BLE scan response contains the service IDs
                if (eventArgs.AdvertisementType == BluetoothLEAdvertisementType.ScanResponse)
                {
                    ScannedDevice scannedDevice = null;

                    // See if the Advertisement has been received for this device
                    if (_scannedDevices.TryGetValue(eventArgs.BluetoothAddress, out scannedDevice))
                    {
                        if (scannedDevice.ScanResponsePending)
                        {
                            // Look for the UART service
                            Guid guid = eventArgs.Advertisement.ServiceUuids.FirstOrDefault(i => i == GattServiceUuids.UART);
                            if (guid != null)
                            {
                                // Device is now registered
                                _scannedDevices[eventArgs.BluetoothAddress].ScanResponsePending = false;

                                BLE_Device bleConntectibleDevice = new BLE_Device(scannedDevice.Name, scannedDevice.BLEAddress);
#if WINDOWS_UWP
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
#else
                                Application.Current.Dispatcher.Invoke(() =>
#endif
                                {
                                    _discoveredDevices.Add(bleConntectibleDevice);
                                });
                            }
                        }
                        else
                        {
                            // Debug.WriteLine(eventArgs.Advertisement.ManufacturerData.Count);
                            if (eventArgs.Advertisement.ManufacturerData.Count > 0)
                            {
                                // Only print the first one of the list
                                var manufacturerData = eventArgs.Advertisement.ManufacturerData[0];
                                var data             = new byte[manufacturerData.Data.Length];
                                using (var reader = DataReader.FromBuffer(manufacturerData.Data))
                                {
                                    reader.ReadBytes(data);
                                    if (scannedDevice.LastManufacturerData == null || !data.SequenceEqual(scannedDevice.LastManufacturerData))
                                    {
                                        scannedDevice.LastManufacturerData = data;
                                    }
                                }
                            }
                        }
                    }
                }

                // Extract the Appearance ID from the advertisement
                BluetoothLEAdvertisementDataSection dataItem = eventArgs.Advertisement.DataSections.FirstOrDefault(i => i.DataType == GAP_ADTYPE_APPEARANCE);
                if (dataItem != null && dataItem.Data.Capacity == sizeof(UInt16))
                {
                    var data = new byte[dataItem.Data.Length];
                    using (var reader = DataReader.FromBuffer(dataItem.Data))
                        reader.ReadBytes(data);
                    extractedAppearanceID = BitConverter.ToUInt16(data, 0);

                    if (extractedAppearanceID == GAP_APPEARANCE_ID)
                    {
                        ScannedDevice scannedDevice = null;

                        // Debug.WriteLine("FOUND CANDIDATE DEVICE " + localName);
                        if (_scannedDevices.TryGetValue(eventArgs.BluetoothAddress, out scannedDevice))
                        {
                            // Update the scan time
                            scannedDevice.ScanTime = DateTime.Now;

                            // See if the device's name has changed
                            if (scannedDevice.Name.CompareTo(localName) != 0)
                            {
                                scannedDevice.Name = localName;
#if WINDOWS_UWP
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
#else
                                Application.Current.Dispatcher.Invoke(() =>
#endif
                                {
                                    var discoveredItem = _discoveredDevices.FirstOrDefault(i => i.DeviceID == scannedDevice.BLEAddress.ToString());
                                    if (discoveredItem != null)
                                    {
                                        discoveredItem.DeviceName = localName;
                                    }
                                });
                            }
                        }
                        else
                        {
                            scannedDevice = new ScannedDevice();
                            scannedDevice.Name = localName;
                            scannedDevice.BLEAddress = eventArgs.BluetoothAddress;
                            scannedDevice.ScanTime = DateTime.Now;
                            scannedDevice.ScanResponsePending = true;
                            _scannedDevices.Add(eventArgs.BluetoothAddress, scannedDevice);
                        }
                    }
                }

                ulong address = eventArgs.BluetoothAddress;
                short rssi = eventArgs.RawSignalStrengthInDBm;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("## BLE SCAN EXIT EXCEPTION " + localName + " " + ex.ToString());
                DiagnosticsHandler?.Invoke(this, "## BLE SCAN EXIT EXCEPTION " + localName + " " + ex.ToString());
            }
        }
Example #21
0
        public static (string result, BluetoothCompanyIdentifier.CommonManufacturerType manufacturerType) Parse(BluetoothLEAdvertisementDataSection section, sbyte txPower, string indent)
        {
            string        str = "??";
            byte          b   = section.DataType;
            DataTypeValue dtv = ConvertDataTypeValue(b); // get the enum value

            BluetoothCompanyIdentifier.CommonManufacturerType manufacturerType = BluetoothCompanyIdentifier.CommonManufacturerType.Other;
            try
            {
                var printAsHex = false;
                switch (dtv)
                {
                case DataTypeValue.ManufacturerData:
                    (str, manufacturerType) = BluetoothCompanyIdentifier.ParseManufacturerData(section, txPower);
                    break;

                case DataTypeValue.Flags:
                    str = ParseFlags(section);
                    break;

                case DataTypeValue.ShortenedLocalName:
                {
                    var buffer = section.Data.ToArray();
                    var allNul = true;
                    foreach (var namebyte in buffer)
                    {
                        if (namebyte != 0)
                        {
                            allNul = false;
                        }
                    }
                    if (allNul)
                    {
                        str = "";
                    }
                    else
                    {
                        printAsHex = true;
                    }
                }
                break;

                case DataTypeValue.TxPowerLevel:
                    var db = ParseTxPowerLevel(section);
                    str = $"{db}";
                    break;

                default:
                    printAsHex = true;
                    break;
                }
                if (printAsHex)
                {
                    var result = ValueParser.Parse(section.Data, "BYTES|HEX");
                    str = $"section {dtv.ToString()} data={result.AsString}\n";
                }
            }
            catch (Exception)
            {
                var result = ValueParser.Parse(section.Data, "BYTES|HEX");
                str = $"error section {section.DataType} data={result.AsString}\n";
            }
            if (!string.IsNullOrWhiteSpace(str))
            {
                str = indent + str;
            }
            return(str, manufacturerType);
        }
 /// <summary>
 /// Converts the data of the given BluetoothLEAdvertisementDataSection to a string.
 /// </summary>
 /// <param name="dataSection">The data section instance.</param>
 /// <returns>The data of the given data section as a string.</returns>
 public static string DataSectionToRawString(BluetoothLEAdvertisementDataSection dataSection)
 {
     return BitConverter.ToString(dataSection.Data.ToArray());
 }