BleWinHelper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using UnityEngine;
  6. using System.Runtime.InteropServices;
  7. namespace SmartBowSDK
  8. {
  9. /// <summary>
  10. /// Windows连接BluetoothLE
  11. /// 我的扫描逻辑默认了读写特征都在同一服务下
  12. /// </summary>
  13. public class BleWinHelper : MonoBehaviour
  14. {
  15. public string LogTag = "BleWinHelper-Log: ";
  16. private void Log(string text)
  17. {
  18. Debug.Log(LogTag + text);
  19. }
  20. private void Warn(string text)
  21. {
  22. Debug.LogWarning(LogTag + text);
  23. }
  24. private void Error(string text)
  25. {
  26. Debug.Log(LogTag + text);
  27. }
  28. private string targetDeviceName = "Bbow_20210501 | ARTEMIS Pro | HOUYI Pro | Pistol | Pistol M9 | BGBox_202012";
  29. private string targetDeviceNameHOUYIPro = "HOUYI Pro";
  30. private string targetDeviceNameGun = "Pistol | Pistol M9 | Bbow_20210501";
  31. private string targetService = "{0000fff0-0000-1000-8000-00805f9b34fb}";
  32. private string targetCharacteristicsNotify = "{0000fff1-0000-1000-8000-00805f9b34fb}";
  33. private string targetCharacteristicsWrite = "{0000fff2-0000-1000-8000-00805f9b34fb}";
  34. private bool isConnectLocking = false;
  35. private bool isScanningDevices = false;
  36. private bool isScanningServices = false;
  37. private bool isScanningCharacteristics = false;
  38. private bool isSubscribed = false;
  39. private bool isSubscribing = false;
  40. private string lastError = null;
  41. [SerializeField]
  42. private string selectedDeviceId = null;
  43. private Dictionary<string, Dictionary<string, string>> deviceList = new Dictionary<string, Dictionary<string, string>>();
  44. private List<string> serviceList = new List<string>();
  45. private List<string> characteristicsList = new List<string>();
  46. private float _connectedTime = 0;
  47. private float _receiveDataTime = 0;
  48. private float _heartBeatInterval = 0;
  49. private Action OnConnected;
  50. /// <summary>
  51. /// 主动调用Disconnect()不会触发该委托
  52. /// </summary>
  53. private Action OnConnectionFailed;
  54. private static Action<string, byte[]> OnCharacteristicChanged;
  55. /// <summary>
  56. /// 注册window对象
  57. /// </summary>
  58. /// <param name="o">挂载对象</param>
  59. /// <param name="bluetoothWindows">关联的BluetoothWindows</param>
  60. /// <param name="logTip">提示的log标签</param>
  61. /// <returns></returns>
  62. public static BleWinHelper RegisterTo(GameObject o,BluetoothWindows bluetoothWindows,string logTip = "first")
  63. {
  64. //if (_Instance)
  65. //{
  66. // Error("Register fail, because only one can be registered.");
  67. // return null;
  68. //}
  69. GameObject obj = new GameObject("BleWinHelper"+ logTip);
  70. obj.transform.SetParent(o.transform);
  71. BleWinHelper bleWinHelper = obj.AddComponent<BleWinHelper>();
  72. //日志名字
  73. bleWinHelper.LogTag = "BleWinHelper-" + logTip + ": ";
  74. bluetoothWindows.Connect = bleWinHelper.Connect;
  75. bluetoothWindows.Disconnect = bleWinHelper.Disconnect;
  76. bluetoothWindows.Write = bleWinHelper.Write;
  77. bluetoothWindows.WriteByte = bleWinHelper.WriteByte;
  78. bleWinHelper.OnConnected = () => bluetoothWindows.OnConnected?.Invoke();
  79. bleWinHelper.OnConnectionFailed = () => bluetoothWindows.OnConnectionFailed?.Invoke();
  80. //多个定义共用一个OnCharacteristicChanged
  81. OnCharacteristicChanged += (deviceID,bytes) => {
  82. if (deviceID == bleWinHelper.selectedDeviceId) {
  83. bluetoothWindows.OnCharacteristicChanged?.Invoke(deviceID, bytes);
  84. }
  85. };
  86. return bleWinHelper;
  87. }
  88. /// <summary>
  89. /// 设置心跳检测
  90. /// 1.每次收到的蓝牙数据都视为心跳
  91. /// 2.帮助触发蓝牙断开监听
  92. /// </summary>
  93. /// <param name="interval">心跳检测间隔</param>
  94. public void SetHeartBeat(float interval)
  95. {
  96. _heartBeatInterval = interval;
  97. }
  98. //private static BleWinHelper _Instance;
  99. void Awake()
  100. {
  101. // _Instance = this;
  102. }
  103. void OnDestroy()
  104. {
  105. // if (_Instance == this) _Instance = null;
  106. BleApi.Quit();
  107. }
  108. void Update()
  109. {
  110. BleApi.ScanStatus status;
  111. if (isScanningDevices)
  112. {
  113. BleApi.DeviceUpdate res = new BleApi.DeviceUpdate();
  114. do
  115. {
  116. status = BleApi.PollDevice(ref res, false);
  117. if (status == BleApi.ScanStatus.AVAILABLE)
  118. {
  119. if (!deviceList.ContainsKey(res.id))
  120. deviceList[res.id] = new Dictionary<string, string>() {
  121. { "name", "" },
  122. { "isConnectable", "False" }
  123. };
  124. if (res.nameUpdated)
  125. deviceList[res.id]["name"] = res.name;
  126. if (res.isConnectableUpdated)
  127. deviceList[res.id]["isConnectable"] = res.isConnectable.ToString();
  128. //deviceList[res.id]["name"] == targetDeviceName
  129. if (targetDeviceName.Contains(deviceList[res.id]["name"]) && deviceList[res.id]["isConnectable"] == "True")
  130. {
  131. selectedDeviceId = res.id;
  132. StopDeviceScan();
  133. }
  134. }
  135. else if (status == BleApi.ScanStatus.FINISHED)
  136. {
  137. StartCoroutine(ScanServiceAndCharacteristicsToSubscribe());
  138. }
  139. } while (status == BleApi.ScanStatus.AVAILABLE);
  140. }
  141. if (isScanningServices)
  142. {
  143. BleApi.Service res;
  144. do
  145. {
  146. status = BleApi.PollService(out res, false);
  147. if (status == BleApi.ScanStatus.AVAILABLE)
  148. {
  149. serviceList.Add(res.uuid);
  150. }
  151. else if (status == BleApi.ScanStatus.FINISHED)
  152. {
  153. isScanningServices = false;
  154. }
  155. } while (status == BleApi.ScanStatus.AVAILABLE);
  156. }
  157. if (isScanningCharacteristics)
  158. {
  159. BleApi.Characteristic res;
  160. do
  161. {
  162. status = BleApi.PollCharacteristic(out res, false);
  163. if (status == BleApi.ScanStatus.AVAILABLE)
  164. {
  165. Log("res.userDescription:"+ res.userDescription+ ",res.uuid:" + res.uuid);
  166. if (res.userDescription == "no description available" || //旧设备
  167. res.userDescription == "SPP Write Channel" || //新设备
  168. res.userDescription == "SPP Read Channel")
  169. {
  170. characteristicsList.Add(res.uuid);
  171. }
  172. else {
  173. //跟着之前代码
  174. characteristicsList.Add(res.userDescription);
  175. }
  176. //string name = res.userDescription != "no description available" ? res.userDescription : res.uuid;
  177. //characteristicsList.Add(name);
  178. }
  179. else if (status == BleApi.ScanStatus.FINISHED)
  180. {
  181. isScanningCharacteristics = false;
  182. }
  183. } while (status == BleApi.ScanStatus.AVAILABLE);
  184. }
  185. if (isSubscribed)
  186. {
  187. BleApi.BLEData res;
  188. while (BleApi.PollData(out res, false))
  189. {
  190. //string text = BitConverter.ToString(res.buf, 0, res.size);
  191. // string text = Encoding.ASCII.GetString(res.buf, 0, res.size);
  192. byte[] bytes = new byte[res.size];
  193. Array.Copy(res.buf, bytes, res.size);
  194. _receiveDataTime = Time.realtimeSinceStartup;
  195. OnCharacteristicChanged?.Invoke(res.deviceId, bytes);
  196. }
  197. }
  198. {
  199. BleApi.ErrorMessage res;
  200. BleApi.GetError(out res);
  201. if (lastError != res.msg)
  202. {
  203. Error(res.msg);
  204. lastError = res.msg;
  205. //对应设备才断开
  206. if (lastError.Contains("SendDataAsync") && lastError.Contains(selectedDeviceId) && isSubscribed)
  207. {
  208. HandleConnectFail();
  209. }
  210. }
  211. }
  212. }
  213. void LateUpdate()
  214. {
  215. if (
  216. _heartBeatInterval > 0 &&
  217. isSubscribed &&
  218. Time.realtimeSinceStartup - _connectedTime >= _heartBeatInterval &&
  219. Time.realtimeSinceStartup - _receiveDataTime >= _heartBeatInterval
  220. )
  221. {
  222. HandleConnectFail();
  223. }
  224. }
  225. private bool Connect()
  226. {
  227. if (isConnectLocking || isScanningDevices)
  228. {
  229. Warn("Connect Invalid, because is in connect.");
  230. return false;
  231. }
  232. BleApi.StartDeviceScan();
  233. isConnectLocking = true;
  234. isScanningDevices = true;
  235. Log("Start Connect");
  236. return true;
  237. }
  238. private void StopDeviceScan()
  239. {
  240. if (!isScanningDevices) return;
  241. BleApi.StopDeviceScan();
  242. isScanningDevices = false;
  243. }
  244. private IEnumerator ScanServiceAndCharacteristicsToSubscribe()
  245. {
  246. isSubscribing = true;
  247. if (selectedDeviceId == null)
  248. {
  249. HandleConnectFail();
  250. yield break;
  251. }
  252. Log("SelectedDeviceId OK");
  253. BleApi.ScanServices(selectedDeviceId);
  254. isScanningServices = true;
  255. serviceList.Clear();
  256. while (isScanningServices) yield return null;
  257. bool findTargetService = false;
  258. foreach (string service in serviceList)
  259. {
  260. if (service == targetService)
  261. {
  262. findTargetService = true;
  263. Log("FindTargetService OK");
  264. break;
  265. }
  266. }
  267. if (!findTargetService)
  268. {
  269. HandleConnectFail();
  270. yield break;
  271. }
  272. BleApi.ScanCharacteristics(selectedDeviceId, targetService);
  273. isScanningCharacteristics = true;
  274. characteristicsList.Clear();
  275. while (isScanningCharacteristics) yield return null;
  276. bool findTargetCharacteristicsNotify = false;
  277. bool findTargetCharacteristicsWrite = false;
  278. foreach (string characteristics in characteristicsList)
  279. {
  280. if (characteristics == targetCharacteristicsNotify)
  281. {
  282. findTargetCharacteristicsNotify = true;
  283. Log("FindTargetCharacteristicsNotify OK");
  284. }
  285. else if (characteristics == targetCharacteristicsWrite)
  286. {
  287. findTargetCharacteristicsWrite = true;
  288. Log("FindTargetCharacteristicsWrite OK");
  289. }
  290. }
  291. if (!findTargetCharacteristicsNotify || !findTargetCharacteristicsWrite)
  292. {
  293. HandleConnectFail();
  294. yield break;
  295. }
  296. BleApi.SubscribeCharacteristic(selectedDeviceId, targetService, targetCharacteristicsNotify, false);
  297. isSubscribed = true;
  298. isSubscribing = false;
  299. Log("SubscribeCharacteristicNotify OK");
  300. _connectedTime = Time.realtimeSinceStartup;
  301. OnConnected?.Invoke();
  302. }
  303. private void HandleConnectFail()
  304. {
  305. if (selectedDeviceId != null) BleApi.Disconnect(selectedDeviceId);
  306. bool isLockBefore = isConnectLocking;
  307. ReinitAfterConnectFail();
  308. if (isLockBefore) OnConnectionFailed?.Invoke();
  309. }
  310. private void ReinitAfterConnectFail()
  311. {
  312. isConnectLocking = false;
  313. isScanningDevices = false;
  314. isScanningServices = false;
  315. isScanningCharacteristics = false;
  316. isSubscribed = false;
  317. isSubscribing = false;
  318. selectedDeviceId = null;
  319. deviceList.Clear();
  320. serviceList.Clear();
  321. characteristicsList.Clear();
  322. }
  323. private bool Write(string text)
  324. {
  325. if (!isSubscribed) return false;
  326. byte[] payload = Encoding.ASCII.GetBytes(text);
  327. BleApi.BLEData data = new BleApi.BLEData();
  328. data.buf = new byte[512];
  329. data.size = (short)payload.Length;
  330. data.deviceId = selectedDeviceId;
  331. data.serviceUuid = targetService;
  332. data.characteristicUuid = targetCharacteristicsWrite;
  333. for (int i = 0; i < payload.Length; i++)
  334. data.buf[i] = payload[i];
  335. // no error code available in non-blocking mode
  336. BleApi.SendData(in data, false);
  337. Log("Write(" + text + ")");
  338. return true;
  339. }
  340. private bool WriteByte(byte[] payload)
  341. {
  342. if (!isSubscribed) return false;
  343. BleApi.BLEData data = new BleApi.BLEData();
  344. data.buf = new byte[512];
  345. data.size = (short)payload.Length;
  346. data.deviceId = selectedDeviceId;
  347. data.serviceUuid = targetService;
  348. data.characteristicUuid = targetCharacteristicsWrite;
  349. for (int i = 0; i < payload.Length; i++)
  350. data.buf[i] = payload[i];
  351. // no error code available in non-blocking mode
  352. BleApi.SendData(in data, false);
  353. Log("Write(byte[])");
  354. return true;
  355. }
  356. private bool Disconnect()
  357. {
  358. if (!isConnectLocking)
  359. {
  360. Warn("Disconnect Invalid, because not in connect.");
  361. return false;
  362. }
  363. if (isSubscribing)
  364. {
  365. Warn("Disconnect Invalid, because is subscribing.");
  366. return false;
  367. }
  368. if (isScanningDevices) StopDeviceScan();
  369. if (selectedDeviceId != null) BleApi.Disconnect(selectedDeviceId);
  370. ReinitAfterConnectFail();
  371. Log("Disconnect OK");
  372. return true;
  373. }
  374. }
  375. }