UnityBleConnect.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using Wit.SDK.Modular.Sensor.Modular.Connector.Entity;
  3. using Wit.SDK.Modular.Sensor.Modular.Connector.Interface;
  4. using Wit.SDK.Sensor.Connector.Entity;
  5. namespace Wit.SDK.Sensor.Connector.Role
  6. {
  7. /// <summary>
  8. /// unity蓝牙连接器
  9. /// </summary>
  10. public class UnityBleConnect : IConnector
  11. {
  12. /// <summary>
  13. /// 连接器配置
  14. /// </summary>
  15. public UnityBleConfig config = new UnityBleConfig();
  16. /// <summary>
  17. /// 构造
  18. /// </summary>
  19. /// <param name="config"></param>
  20. public UnityBleConnect(UnityBleConfig config) {
  21. this.config = config;
  22. }
  23. /// <summary>
  24. /// 检查配置
  25. /// </summary>
  26. public override void CheckConfig()
  27. {
  28. if (config.Mac == null)
  29. {
  30. throw new Exception("未设置 Mac 地址");
  31. }
  32. if (config.ServiceGuid == null)
  33. {
  34. throw new Exception("未设置 ServiceGuid");
  35. }
  36. if (config.WriteGuid == null)
  37. {
  38. throw new Exception("未设置 WriteGuid");
  39. }
  40. if (config.NotifyGuid == null)
  41. {
  42. throw new Exception("未设置 NotifyGuid");
  43. }
  44. }
  45. public override void Close()
  46. {
  47. if (ConnectStatus == ConnectStatus.Closed) {
  48. return;
  49. }
  50. // disconnect
  51. BluetoothLEHardwareInterface.UnSubscribeCharacteristic(config.Mac, config.ServiceGuid, config.NotifyGuid, (characteristic) => {
  52. BluetoothLEHardwareInterface.DisconnectPeripheral(config.Mac, (disconnectAddress) => {
  53. // 标志为关闭状态
  54. ConnectStatus = ConnectStatus.Closed;
  55. });
  56. });
  57. }
  58. /// <summary>
  59. /// 获得配置
  60. /// </summary>
  61. /// <returns></returns>
  62. public override IConnectConfig GetConfig()
  63. {
  64. return config;
  65. }
  66. public override void Open()
  67. {
  68. if (ConnectStatus == ConnectStatus.Opened)
  69. {
  70. return;
  71. }
  72. CheckConfig();
  73. BluetoothLEHardwareInterface.ConnectToPeripheral(config.Mac, (address) => {}, null, (address, service, characteristic) => {
  74. ConnectStatus = ConnectStatus.Opened;
  75. // 找服务
  76. subscribe();
  77. }, null);
  78. }
  79. /// <summary>
  80. /// 找服务
  81. /// </summary>
  82. private void subscribe()
  83. {
  84. BluetoothLEHardwareInterface.SubscribeCharacteristic(config.Mac, config.ServiceGuid, config.NotifyGuid, null, (characteristic, bytes) => {
  85. onReceive(bytes);
  86. });
  87. }
  88. public override void SendData(byte[] data)
  89. {
  90. BluetoothLEHardwareInterface.WriteCharacteristic(config.Mac, config.ServiceGuid, config.WriteGuid, data, data.Length, false, (characteristic) =>{ });
  91. }
  92. }
  93. }