BleWinHelper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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";
  29. private string targetDeviceNameHOUYIPro = "HOUYI Pro | Bbow_20210501";
  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. if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.HOUYIPRO)
  135. { //需要判断是否是红外弓箭
  136. if (targetDeviceNameHOUYIPro.Contains(deviceList[res.id]["name"]) && deviceList[res.id]["isConnectable"] == "True")
  137. {
  138. selectedDeviceId = res.id;
  139. StopDeviceScan();
  140. }
  141. }
  142. else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.ARTEMISPRO)
  143. { //需要判断是否是ARTEMISPRO弓箭
  144. if (targetDeviceName.Contains(deviceList[res.id]["name"]) && deviceList[res.id]["isConnectable"] == "True")
  145. {
  146. selectedDeviceId = res.id;
  147. StopDeviceScan();
  148. }
  149. }
  150. else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.Gun)
  151. {
  152. //需要判断是否是枪
  153. if (targetDeviceNameGun.Contains(deviceList[res.id]["name"]) && deviceList[res.id]["isConnectable"] == "True")
  154. {
  155. selectedDeviceId = res.id;
  156. StopDeviceScan();
  157. }
  158. }
  159. else
  160. { //其余的九轴连接
  161. if (targetDeviceName.Contains(deviceList[res.id]["name"]) && deviceList[res.id]["isConnectable"] == "True")
  162. {
  163. selectedDeviceId = res.id;
  164. StopDeviceScan();
  165. }
  166. }
  167. }
  168. else if (status == BleApi.ScanStatus.FINISHED)
  169. {
  170. StartCoroutine(ScanServiceAndCharacteristicsToSubscribe());
  171. }
  172. } while (status == BleApi.ScanStatus.AVAILABLE);
  173. }
  174. if (isScanningServices)
  175. {
  176. BleApi.Service res;
  177. do
  178. {
  179. status = BleApi.PollService(out res, false);
  180. if (status == BleApi.ScanStatus.AVAILABLE)
  181. {
  182. serviceList.Add(res.uuid);
  183. }
  184. else if (status == BleApi.ScanStatus.FINISHED)
  185. {
  186. isScanningServices = false;
  187. }
  188. } while (status == BleApi.ScanStatus.AVAILABLE);
  189. }
  190. if (isScanningCharacteristics)
  191. {
  192. BleApi.Characteristic res;
  193. do
  194. {
  195. status = BleApi.PollCharacteristic(out res, false);
  196. if (status == BleApi.ScanStatus.AVAILABLE)
  197. {
  198. Log("res.userDescription:"+ res.userDescription+ ",res.uuid:" + res.uuid);
  199. if (res.userDescription == "no description available" || //旧设备
  200. res.userDescription == "SPP Write Channel" || //新设备
  201. res.userDescription == "SPP Read Channel")
  202. {
  203. characteristicsList.Add(res.uuid);
  204. }
  205. else {
  206. //跟着之前代码
  207. characteristicsList.Add(res.userDescription);
  208. }
  209. //string name = res.userDescription != "no description available" ? res.userDescription : res.uuid;
  210. //characteristicsList.Add(name);
  211. }
  212. else if (status == BleApi.ScanStatus.FINISHED)
  213. {
  214. isScanningCharacteristics = false;
  215. }
  216. } while (status == BleApi.ScanStatus.AVAILABLE);
  217. }
  218. if (isSubscribed)
  219. {
  220. BleApi.BLEData res;
  221. while (BleApi.PollData(out res, false))
  222. {
  223. //string text = BitConverter.ToString(res.buf, 0, res.size);
  224. // string text = Encoding.ASCII.GetString(res.buf, 0, res.size);
  225. byte[] bytes = new byte[res.size];
  226. Array.Copy(res.buf, bytes, res.size);
  227. _receiveDataTime = Time.realtimeSinceStartup;
  228. OnCharacteristicChanged?.Invoke(res.deviceId, bytes);
  229. }
  230. }
  231. {
  232. BleApi.ErrorMessage res;
  233. BleApi.GetError(out res);
  234. if (lastError != res.msg)
  235. {
  236. Error(res.msg);
  237. lastError = res.msg;
  238. //对应设备才断开
  239. if (lastError.Contains("SendDataAsync") && lastError.Contains(selectedDeviceId) && isSubscribed)
  240. {
  241. HandleConnectFail();
  242. }
  243. }
  244. }
  245. }
  246. void LateUpdate()
  247. {
  248. if (
  249. _heartBeatInterval > 0 &&
  250. isSubscribed &&
  251. Time.realtimeSinceStartup - _connectedTime >= _heartBeatInterval &&
  252. Time.realtimeSinceStartup - _receiveDataTime >= _heartBeatInterval
  253. )
  254. {
  255. HandleConnectFail();
  256. }
  257. }
  258. private bool Connect()
  259. {
  260. if (isConnectLocking || isScanningDevices)
  261. {
  262. Warn("Connect Invalid, because is in connect.");
  263. return false;
  264. }
  265. BleApi.StartDeviceScan();
  266. isConnectLocking = true;
  267. isScanningDevices = true;
  268. Log("Start Connect");
  269. return true;
  270. }
  271. private void StopDeviceScan()
  272. {
  273. if (!isScanningDevices) return;
  274. BleApi.StopDeviceScan();
  275. isScanningDevices = false;
  276. }
  277. private IEnumerator ScanServiceAndCharacteristicsToSubscribe()
  278. {
  279. isSubscribing = true;
  280. if (selectedDeviceId == null)
  281. {
  282. HandleConnectFail();
  283. yield break;
  284. }
  285. Log("SelectedDeviceId OK");
  286. BleApi.ScanServices(selectedDeviceId);
  287. isScanningServices = true;
  288. serviceList.Clear();
  289. while (isScanningServices) yield return null;
  290. bool findTargetService = false;
  291. foreach (string service in serviceList)
  292. {
  293. if (service == targetService)
  294. {
  295. findTargetService = true;
  296. Log("FindTargetService OK");
  297. break;
  298. }
  299. }
  300. if (!findTargetService)
  301. {
  302. HandleConnectFail();
  303. yield break;
  304. }
  305. BleApi.ScanCharacteristics(selectedDeviceId, targetService);
  306. isScanningCharacteristics = true;
  307. characteristicsList.Clear();
  308. while (isScanningCharacteristics) yield return null;
  309. bool findTargetCharacteristicsNotify = false;
  310. bool findTargetCharacteristicsWrite = false;
  311. foreach (string characteristics in characteristicsList)
  312. {
  313. if (characteristics == targetCharacteristicsNotify)
  314. {
  315. findTargetCharacteristicsNotify = true;
  316. Log("FindTargetCharacteristicsNotify OK");
  317. }
  318. else if (characteristics == targetCharacteristicsWrite)
  319. {
  320. findTargetCharacteristicsWrite = true;
  321. Log("FindTargetCharacteristicsWrite OK");
  322. }
  323. }
  324. if (!findTargetCharacteristicsNotify || !findTargetCharacteristicsWrite)
  325. {
  326. HandleConnectFail();
  327. yield break;
  328. }
  329. BleApi.SubscribeCharacteristic(selectedDeviceId, targetService, targetCharacteristicsNotify, false);
  330. isSubscribed = true;
  331. isSubscribing = false;
  332. Log("SubscribeCharacteristicNotify OK");
  333. _connectedTime = Time.realtimeSinceStartup;
  334. OnConnected?.Invoke();
  335. }
  336. private void HandleConnectFail()
  337. {
  338. if (selectedDeviceId != null) BleApi.Disconnect(selectedDeviceId);
  339. bool isLockBefore = isConnectLocking;
  340. ReinitAfterConnectFail();
  341. if (isLockBefore) OnConnectionFailed?.Invoke();
  342. }
  343. private void ReinitAfterConnectFail()
  344. {
  345. isConnectLocking = false;
  346. isScanningDevices = false;
  347. isScanningServices = false;
  348. isScanningCharacteristics = false;
  349. isSubscribed = false;
  350. isSubscribing = false;
  351. selectedDeviceId = null;
  352. deviceList.Clear();
  353. serviceList.Clear();
  354. characteristicsList.Clear();
  355. }
  356. private bool Write(string text)
  357. {
  358. if (!isSubscribed) return false;
  359. byte[] payload = Encoding.ASCII.GetBytes(text);
  360. BleApi.BLEData data = new BleApi.BLEData();
  361. data.buf = new byte[512];
  362. data.size = (short)payload.Length;
  363. data.deviceId = selectedDeviceId;
  364. data.serviceUuid = targetService;
  365. data.characteristicUuid = targetCharacteristicsWrite;
  366. for (int i = 0; i < payload.Length; i++)
  367. data.buf[i] = payload[i];
  368. // no error code available in non-blocking mode
  369. BleApi.SendData(in data, false);
  370. Log("Write(" + text + ")");
  371. return true;
  372. }
  373. private bool WriteByte(byte[] payload)
  374. {
  375. if (!isSubscribed) return false;
  376. BleApi.BLEData data = new BleApi.BLEData();
  377. data.buf = new byte[512];
  378. data.size = (short)payload.Length;
  379. data.deviceId = selectedDeviceId;
  380. data.serviceUuid = targetService;
  381. data.characteristicUuid = targetCharacteristicsWrite;
  382. for (int i = 0; i < payload.Length; i++)
  383. data.buf[i] = payload[i];
  384. // no error code available in non-blocking mode
  385. BleApi.SendData(in data, false);
  386. Log("Write(byte[])");
  387. return true;
  388. }
  389. private bool Disconnect()
  390. {
  391. if (!isConnectLocking)
  392. {
  393. Warn("Disconnect Invalid, because not in connect.");
  394. return false;
  395. }
  396. if (isSubscribing)
  397. {
  398. Warn("Disconnect Invalid, because is subscribing.");
  399. return false;
  400. }
  401. if (isScanningDevices) StopDeviceScan();
  402. if (selectedDeviceId != null) BleApi.Disconnect(selectedDeviceId);
  403. ReinitAfterConnectFail();
  404. Log("Disconnect OK");
  405. return true;
  406. }
  407. }
  408. }