BleWinHelper.cs 20 KB

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