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 void UInt64Test() { UInt64 data = 42; Assert.AreEqual(data, GattConvert.ToUInt16(GattConvert.ToIBuffer(data))); Assert.AreNotEqual(data - 1, GattConvert.ToUInt64(GattConvert.ToIBuffer(data))); }
private async Task <string> waitSendRequest(Request req) { if (connectionState != ConnectionState._connected) { return(lastError = "Error: No connection available"); } if (req == null) { return(lastError = "Error: Unable to send request"); } Log.WriteLine("~~~Waiting : " + req.index); bool isanswered = await req.IsAnswered(); if (!isanswered) { Log.WriteLine("~~~not answered : " + req.index); return(lastError = "Error: Did not received an answer"); } IBuffer myresponse = GattConvert.ToIBufferFromArray(req.GetResponse()); string strresponse = GattConvert.ToHexString(myresponse); strresponse = strresponse.Replace("-", ""); Log.WriteLine("<---Response : " + req.index + " in " + Environment.CurrentManagedThreadId + "with " + strresponse); return(strresponse); }
public void Int32Test() { Int32 data = 42; Assert.AreEqual(data, GattConvert.ToInt32(GattConvert.ToIBuffer(data))); Assert.AreNotEqual(data - 1, GattConvert.ToInt32(GattConvert.ToIBuffer(data))); }
public void Int64Test2() { Int16 data = 42; Assert.IsTrue(data == GattConvert.ToInt64(GattConvert.ToIBuffer(data))); Assert.IsFalse((data - 1) == GattConvert.ToInt64(GattConvert.ToIBuffer(data))); }
/// <summary> /// This sets the value based on the input string with regard to the characteristics first presentation format /// </summary> /// <param name="value">value to set</param> /// <param name="isHexString">is the passed in string a hex byte array</param> public void SetValueFromString(string value, bool isHexString = false) { if (isHexString == true) { Characteristic.Value = GattConvert.ToIBufferFromHexString(value); return; } if (Characteristic.Characteristic.PresentationFormats.Count > 0) { byte format = Characteristic.Characteristic.PresentationFormats[0].FormatType; // Check our supported formats to convert a string to this Characteristics Value if (!((format != GattPresentationFormatTypes.SInt32) || (format != GattPresentationFormatTypes.Utf8))) { throw new NotImplementedException("Only SInt32 and UTF8 are supported"); } //TODO: Support more presentation types if (format == GattPresentationFormatTypes.SInt32) { Characteristic.Value = GattConvert.ToIBuffer(Convert.ToInt32(value)); } else if (format == GattPresentationFormatTypes.Utf8) { Characteristic.Value = GattConvert.ToIBuffer(value); } } }
public void Int16Test2() { byte[] input = { 0, 42, 0, 42, 0, 42, 0 }; byte[] expected = { 0, 42 }; Assert.AreEqual(BitConverter.ToInt16(expected, 0), GattConvert.ToInt16(GattConvert.ToIBuffer(input))); }
public BluetoothLEAdvertisementBytePattern GetBytePattern() { var pattern = new BluetoothLEAdvertisementBytePattern(); pattern.DataType = SectionType; pattern.Offset = SectionOffset; if (SectionDataString != null && SectionDataString.Length > 0) { if (sectionDataFormat == DataFormatType.Hex) { // pad the value if we've received odd number of bytes if (SectionDataString.Length % 2 == 1) { pattern.Data = GattConvert.ToIBufferFromHexString("0" + SectionDataString); } else { pattern.Data = GattConvert.ToIBufferFromHexString(SectionDataString); } } else if (sectionDataFormat == DataFormatType.String) { pattern.Data = CryptographicBuffer.ConvertStringToBinary(SectionDataString, BinaryStringEncoding.Utf8); } } return(pattern); }
public ObservableBluetoothLEBeacon( byte[] payload, bool useExtendedFormat, bool isAnonymous, bool includeTxPower, Int16?txPower) { Context = GattSampleContext.Context; var payloadString = GattConvert.ToHexString(payload.AsBuffer()); Name = payloadString.Substring(0, Math.Min(8, payloadString.Length)); var advertisement = new BluetoothLEAdvertisement(); advertisement.ManufacturerData.Add(new BluetoothLEManufacturerData(0x0006, payload.AsBuffer())); publisher = new BluetoothLEAdvertisementPublisher(advertisement); if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 10)) { publisher.UseExtendedAdvertisement = useExtendedFormat; publisher.IsAnonymous = isAnonymous; publisher.IncludeTransmitPowerLevel = includeTxPower; publisher.PreferredTransmitPowerLevelInDBm = txPower; } publisher.StatusChanged += Publisher_StatusChanged; }
public void IntTest1() { int data = 42; IBuffer buf = GattConvert.ToIBuffer(data); Assert.AreEqual(data, GattConvert.ToInt32(buf)); Assert.AreNotEqual(43, GattConvert.ToInt32(buf)); }
/// <summary> /// Write the value to the server <<<< !!! /// </summary> public async void WriteValue() //If I press the 'WriteButton' button { if (!String.IsNullOrEmpty(ValueToWrite)) //And If the 'WriteValue' texbox is not empty { IBuffer writeBuffer = null; //writeBuffer it's the variable that will //send the string through gatt comunication if (WriteType == WriteTypes.Decimal) { DataWriter writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt32(Int32.Parse(ValueToWrite)); writeBuffer = writer.DetachBuffer(); WriteValueBuffer(writeBuffer); //I put it in here } else if (WriteType == WriteTypes.Hex) { try { // pad the value if we've received odd number of bytes if (ValueToWrite.Length % 2 == 1) { writeBuffer = GattConvert.ToIBufferFromHexString("0" + ValueToWrite); WriteValueBuffer(writeBuffer); //I put it also in here } else { writeBuffer = GattConvert.ToIBufferFromHexString(ValueToWrite); WriteValueBuffer(writeBuffer); //And here } } catch (Exception ex) { MessageDialog dialog = new MessageDialog(ex.Message, "Error"); await dialog.ShowAsync(); return; } } else if (WriteType == WriteTypes.UTF8) //"Equivalent" of our send button { //for the UTF8 format SplitProcess(ValueToWrite, writeBuffer); } } else { NotifyUser.Insert(0, "Reading json file"); openJSON(); //NotifyUser.Insert(0, "No data to write to device"); /* * IBuffer jsonBuffer = null; * * string jsonStr = File.ReadAllText(path); * SplitProcess(jsonStr, jsonBuffer); */ } }
public void Int16Test() { Int16 data = 42; Int64 wrong = Int64.MaxValue; Assert.AreEqual(data, GattConvert.ToInt32(GattConvert.ToIBuffer(data))); Assert.AreNotEqual(data - 1, GattConvert.ToInt16(GattConvert.ToIBuffer(data))); Assert.AreNotEqual(wrong, GattConvert.ToInt16(GattConvert.ToIBuffer(wrong))); }
public object Convert(object value, Type targetType, object parameter, string culture) { var byteArray = value as byte[]; if (byteArray != null) { return(GattConvert.ToHexString(byteArray.AsBuffer())); } return(""); }
/// <summary> /// Sets the value of this characteristic based on the display type /// </summary> private void SetValue() { if (data == null) { Value = "NULL"; return; } Value = GattConvert.ToHexString(rawData); }
public void IBufferTest1() { byte[] correct = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; byte[] incorrect = { 0x42, 0x42, 0x42, 0x42, 0x42 }; byte[] result; CryptographicBuffer.CopyToByteArray(GattConvert.ToIBuffer("Hello"), out result); Assert.IsTrue(StructuralComparisons.StructuralEqualityComparer.Equals(correct, result)); Assert.IsFalse(StructuralComparisons.StructuralEqualityComparer.Equals(incorrect, result)); }
private void SetHeartRate() { // Heart rate service starts with flags, then the value. I combine them here then set the characterstic value byte[] flags = { 0x07 }; byte[] heartRate = BitConverter.GetBytes(currentHeartRate); byte[] value = flags.Concat(heartRate).ToArray(); Value = GattConvert.ToIBuffer(value); NotifyValue(); }
public void StringTest1() { string testString = "Hello World"; DataWriter writer = new DataWriter(); writer.WriteString(testString); IBuffer testBuffer = writer.DetachBuffer(); Assert.AreEqual(testString, GattConvert.ToUTF8String(testBuffer)); Assert.AreNotEqual("Goodbye", GattConvert.ToUTF8String(testBuffer)); }
public object ConvertBack(object value, Type targetType, object parameter, string culture) { var byteString = value as String; if (byteString != null) { var data = GattConvert.ToIBufferFromHexString(byteString); return(data.ToArray()); } return(null); }
public void HexTest1() { byte[] data = { 0, 1, 2, 42 }; DataWriter writer = new DataWriter(); writer.WriteBytes(data); IBuffer result = writer.DetachBuffer(); Assert.AreEqual("00-01-02-2A", GattConvert.ToHexString(result)); Assert.AreNotEqual("00-00-00-00", GattConvert.ToHexString(result)); }
public void IntTest3() { Int16 data = 42; DataWriter writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt16(data); IBuffer result = writer.DetachBuffer(); Assert.AreEqual(42, GattConvert.ToInt32(result)); Assert.AreNotEqual(43, GattConvert.ToInt32(result)); }
public void IntTest2() { byte[] data = { 42, 0 }; DataWriter writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteBytes(data); IBuffer result = writer.DetachBuffer(); Assert.AreEqual(42, GattConvert.ToInt32(result)); Assert.AreNotEqual(43, GattConvert.ToInt32(result)); }
// Send one packet of BLE frame private async Task <bool> send_one_TX_Packet(int num) { int len = 0; int offset = 0; if (SPPOverLECharacteristic == null) { setUpSPP(); await SPPOverLECharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); } if (SPPOverLECharacteristic == null) { throw new InvalidOperationException("Invalid BLE Characteristics"); } // Check if last packet if (num > 0) { offset = m_TX_Buffer_rest + ((num - 1) * LEN_PACKET); len = LEN_PACKET; } else { offset = 0; len = m_TX_Buffer_rest; } // Extract frame from buffer byte[] packet = new byte[len + 1]; packet[0] = (byte)offset; for (int i = 0; i < len; i++) { packet[i + 1] = m_TX_buffer[offset + i]; } Log.WriteLine("~~~ send: " + CurrentRequest.index + " data=[" + BitConverter.ToString(packet, 0, packet.Length) + "]"); Windows.Storage.Streams.IBuffer packetBuffer = GattConvert.ToIBufferFromArray(packet); if (SPPOverLECharacteristic != null) { GattCommunicationStatus status = await SPPOverLECharacteristic.WriteValueAsync(packetBuffer, GattWriteOption.WriteWithoutResponse); return(status == GattCommunicationStatus.Success); } return(false); }
public /*async*/ void NotifyImmediatelyForCategory(AlertCategoryId categoryId) { if ((categoryId != AlertCategoryId.SimpleAlert) && (categoryId != AlertCategoryId.All)) { return; } var service = base.ParentService as AlertNotificationService; var value = new byte[] { (byte)AlertCategoryId.SimpleAlert, Convert.ToByte(service.UnreadCount) }; Value = GattConvert.ToIBuffer(value); base.NotifyValue(); }
public async void WriteTransaction() { if (!String.IsNullOrEmpty(ValueToWrite)) { IBuffer writeBuffer = null; if (WriteType == WriteTypes.Decimal) { DataWriter writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt32(Int32.Parse(ValueToWrite)); writeBuffer = writer.DetachBuffer(); } else if (WriteType == WriteTypes.Hex) { try { // pad the value if we've received odd number of bytes if (ValueToWrite.Length % 2 == 1) { writeBuffer = GattConvert.ToIBufferFromHexString("0" + ValueToWrite); } else { writeBuffer = GattConvert.ToIBufferFromHexString(ValueToWrite); } } catch (Exception ex) { MessageDialog dialog = new MessageDialog(ex.Message, "Error"); await dialog.ShowAsync(); return; } } else if (WriteType == WriteTypes.UTF8) { writeBuffer = CryptographicBuffer.ConvertStringToBinary(ValueToWrite, BinaryStringEncoding.Utf8); } context.WriteTransaction(Characteristic.Characteristic, writeBuffer); } else { NotifyUser.Insert(0, "No data to write to device"); } }
public void HexTest2() { byte[] data = { 0, 1, 2, 42 }; byte[] incorrect = { 0, 0, 0, 0 }; DataWriter writer = new DataWriter(); writer.WriteBytes(data); IBuffer dataIBuffer = writer.DetachBuffer(); IBuffer resultIBuffer = GattConvert.ToIBufferFromHexString(GattConvert.ToHexString(dataIBuffer)); byte[] result; CryptographicBuffer.CopyToByteArray(resultIBuffer, out result); Assert.IsTrue(StructuralComparisons.StructuralEqualityComparer.Equals(data, result)); Assert.IsFalse(StructuralComparisons.StructuralEqualityComparer.Equals(incorrect, result)); }
private void updateBloodPressure(Object state) { // Create random blood pressure between 100-160 over 60-100 Systolic = (Int16)rand.Next(100, 160); Diastolic = (Int16)rand.Next(60, 100); UInt16 MAP = (UInt16)(((2 * Diastolic) + Systolic) / 3); // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.blood_pressure_measurement.xml byte[] flags = { 0 }; byte[] value = flags.Concat( BitConverter.GetBytes(Systolic)).Concat( BitConverter.GetBytes(Diastolic)).Concat( BitConverter.GetBytes(MAP)).ToArray(); Value = GattConvert.ToIBuffer(value); NotifyValue(); }
//Reads the value of the characteristic public async void ReadValueAsync() { try { GattReadResult result = await this.characteristic.ReadValueAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { //Assuming the display type to be always UTF8 string value = GattConvert.ToUTF8String(result.Value); Console.WriteLine("Value of characteristic: " + value); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }
public IAsyncOperation <string> sendRequest(string device, string data) { Log.WriteLine("\n--->Send Request " + data); IBuffer mybuffer = GattConvert.ToIBufferFromHexString(data); byte[] mybyteArray = GattConvert.ToByteArray(mybuffer); Request req = (SelectedDevice != null) ? SelectedDevice.RegisterRequest(mybyteArray) : null; if (req != null) { req.index = index; index++; } return(Task.Run(() => waitSendRequest(req)) .AsAsyncOperation()); }
public void CreateBeacon(AdvertisementBeaconPageNewBeaconViewModel parameters) { short?preferredTxPower = null; if (parameters.PreferredTxPower != "") { preferredTxPower = Convert.ToInt16(parameters.PreferredTxPower); } var beacon = new ObservableBluetoothLEBeacon( GattConvert.ToIBufferFromHexString(parameters.Payload).ToArray(), parameters.UseExtendedFormat, parameters.IsAnonymous, parameters.IncludeTxPower, preferredTxPower); Beacons.Add(beacon); // Reset the parameters after creation. parameters.Reset(); }
/// <summary> /// Initializes a new instance of the <see cref="BloodPressureMeasurementCharacteristic" /> class. /// </summary> /// <param name="characteristic">Characteristic this wraps</param> public BloodPressureFeatureCharacteristic(GattLocalCharacteristic characteristic, GenericGattService service) : base(characteristic, service) { // Supports no extra features - required per spec // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.blood_pressure_feature.xml Value = GattConvert.ToIBuffer((Int16)0); }