Utilities.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Linq;
  5. using Windows.Devices.Enumeration;
  6. using Windows.Security.Cryptography;
  7. using Windows.Storage.Streams;
  8. using System.Threading.Tasks;
  9. using System.Threading;
  10. using System.Text.RegularExpressions;
  11. using BluetoothLENet.Classes;
  12. namespace BluetoothLENet
  13. {
  14. public static class Utilities
  15. {
  16. /// <summary>
  17. /// Converts from standard 128bit UUID to the assigned 32bit UUIDs. Makes it easy to compare services
  18. /// that devices expose to the standard list.
  19. /// </summary>
  20. /// <param name="uuid">UUID to convert to 32 bit</param>
  21. /// <returns></returns>
  22. public static ushort ConvertUuidToShortId(Guid uuid)
  23. {
  24. // Get the short Uuid
  25. var bytes = uuid.ToByteArray();
  26. var shortUuid = (ushort)(bytes[0] | bytes[1] << 8);
  27. return shortUuid;
  28. }
  29. /// <summary>
  30. /// Converts from a buffer to a properly sized byte array
  31. /// </summary>
  32. /// <param name="buffer"></param>
  33. /// <returns></returns>
  34. public static byte[] ReadBufferToBytes(IBuffer buffer)
  35. {
  36. var dataLength = buffer.Length;
  37. var data = new byte[dataLength];
  38. using (var reader = DataReader.FromBuffer(buffer))
  39. {
  40. reader.ReadBytes(data);
  41. }
  42. return data;
  43. }
  44. /// <summary>
  45. /// This function converts IBuffer data to string by specified format
  46. /// </summary>
  47. /// <param name="buffer"></param>
  48. /// <param name="format"></param>
  49. /// <returns></returns>
  50. public static string FormatValue(IBuffer buffer, DataFormat format)
  51. {
  52. byte[] data;
  53. CryptographicBuffer.CopyToByteArray(buffer, out data);
  54. switch (format)
  55. {
  56. case DataFormat.ASCII:
  57. return Encoding.ASCII.GetString(data);
  58. case DataFormat.UTF8:
  59. return Encoding.UTF8.GetString(data);
  60. case DataFormat.Dec:
  61. return string.Join(" ", data.Select(b => b.ToString("00")));
  62. case DataFormat.Hex:
  63. return BitConverter.ToString(data).Replace("-", " ");
  64. case DataFormat.Bin:
  65. var s = string.Empty;
  66. foreach (var b in data) s += Convert.ToString(b, 2).PadLeft(8, '0') + " ";
  67. return s;
  68. default:
  69. return Encoding.ASCII.GetString(data);
  70. }
  71. }
  72. /// <summary>
  73. /// Format data for writing by specific format
  74. /// </summary>
  75. /// <param name="data"></param>
  76. /// <param name="format"></param>
  77. /// <returns></returns>
  78. public static IBuffer FormatData(string data, DataFormat format)
  79. {
  80. try
  81. {
  82. if (format == DataFormat.ASCII || format == DataFormat.UTF8)
  83. {
  84. return CryptographicBuffer.ConvertStringToBinary(Regex.Unescape(data), BinaryStringEncoding.Utf8);
  85. }
  86. else
  87. {
  88. string[] values = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  89. byte[] bytes = new byte[values.Length];
  90. for (int i = 0; i < values.Length; i++)
  91. bytes[i] = Convert.ToByte(values[i], format == DataFormat.Dec ? 10 : format == DataFormat.Hex ? 16 : 2);
  92. var writer = new DataWriter();
  93. writer.ByteOrder = ByteOrder.LittleEndian;
  94. writer.WriteBytes(bytes);
  95. return writer.DetachBuffer();
  96. }
  97. }
  98. catch (Exception error)
  99. {
  100. Console.WriteLine(error.Message);
  101. return null;
  102. }
  103. }
  104. /// <summary>
  105. /// This function is trying to find device or service or attribute by name or number
  106. /// </summary>
  107. /// <param name="collection">source collection</param>
  108. /// <param name="name">name or number to find</param>
  109. /// <returns>ID for device, Name for services or attributes</returns>
  110. public static string GetIdByNameOrNumber(object collection, string name)
  111. {
  112. string result = string.Empty;
  113. // for devices
  114. if (collection is List<DeviceInformation>)
  115. {
  116. var foundDevices = (collection as List<DeviceInformation>).Where(d => d.Name.ToLower().StartsWith(name.ToLower())).ToList();
  117. if (foundDevices.Count == 0)
  118. {
  119. if (!Console.IsOutputRedirected)
  120. Console.WriteLine("Can't connect to {0}.", name);
  121. }
  122. else if (foundDevices.Count == 1)
  123. {
  124. result = foundDevices.First().Id;
  125. }
  126. else
  127. {
  128. if (!Console.IsOutputRedirected)
  129. Console.WriteLine("Found multiple devices with names started from {0}. Please provide an exact name.", name);
  130. }
  131. }
  132. // for services or attributes
  133. else
  134. {
  135. var foundDispAttrs = (collection as List<BluetoothLEAttributeDisplay>).Where(d => d.Name.Split(':').Last().Trim().ToLower().StartsWith(name.ToLower())).ToList();
  136. if (foundDispAttrs.Count == 0)
  137. {
  138. if (Console.IsOutputRedirected)
  139. Console.WriteLine("No service/characteristic found by name {0}.", name);
  140. }
  141. else if (foundDispAttrs.Count == 1)
  142. {
  143. result = foundDispAttrs.First().Name;
  144. }
  145. else
  146. {
  147. if (Console.IsOutputRedirected)
  148. Console.WriteLine("Found multiple services/characteristic with names started from {0}. Please provide an exact name.", name);
  149. }
  150. }
  151. return result;
  152. }
  153. }
  154. }